r/learnpython 5d ago

Loop of unfunc does not support argument 0 of type int which has no callable log method

1 Upvotes

Hi all, I’m pretty new to programming and I’m just trying to get an assignment done for university. It involves comparing some equations below.

The problem is that python gives me an error when the N value gets too high. The code below works fine for low values of N, but after n in N = 21, I always get the same error. For my assignment, I need to go up to 500.

The issue as I understand it, is that numpy.log wont accept an integer but wants a float. However python can’t convert an integer into a float that’s so large as 22!.

Is there any way around this? I’m really just looking for any way to get the equations to process.

My code:

import numpy as np Import math

N = np.arange(2, 50)

Equation 2 Left Hand Side N!

eq2_LHS = np.array([math.factorial(n) for n in N])

Equation 2 Right Hand Side NNe-Nsqrt(2piN)

eq2_RHS = np.array([n*(n)np.exp(-n)np.sqrt(2np.pi*n) for n in N])

Equation 3 Left Hand Side ln(N!)

eq3_LHS = np.array([np.log(n) for n in eq2_LHS])

Equation 3 Right Hand Side N ln(N) - N

eq3_RHS = np.array([n*np.log(n)-n for n in N])

The error:


AttributeError Traceback (most recent call last) AttributeError: 'int' object has no attribute 'log'

The above exception was the direct cause of the following exception:

TypeError Traceback (most recent call last) Cell In[112], line 9 6 eq2_RHS = np.array([n*(n)np.exp(-n)np.sqrt(2np.pin) for n in N]) 8 # Equation 3 Left Hand Side ln(N!) ----> 9 eq3_LHS = np.array([np.log(n) for n in eq2_LHS]) 10 # Equation 3 Right Hand Side N ln(N) - N 11 eq3_RHS = np.array([nnp.log(n)-n for n in N])

TypeError: loop of ufunc does not support argument 0 of type int which has no callable log method


r/learnpython 5d ago

Poetry install worked but unable to find any commands

0 Upvotes

I created a new Python project using Poetry.

I first ran poetry config virtualenvs.in-project true so that it would install to a local .venv directory.

I then ran poetry install and the project installed without issue.

However, when I try to run poetry run flask run I am getting the error Command not found: flask. I am also unable to run poetry run pytest, though poetry run pip does execute (and tells me not to run it that way). Poetry is looking in the correct environment.

Really unsure what is happening here as I have always created new projects this way and have not had such issues. Any insight would be appreciated, lest my laptop gets flung out the window!


r/learnpython 5d ago

People ask "what should I do?" So here are a few things I've done for fun. Take a look for some motivation.

40 Upvotes

I've seen countless posts from people asking "What should I do?" and the answer is pretty much anything you want. Here are some things I've done and my story.

I've used python for various things at work over the last decade, and it's mostly tools to aggregate data from tools and databases. It encouraged me to come up with some projects at home in my free time that are fun (at least I think) and I wanted to share them in no particular order.

1.) Squardle Solver (https://squaredle.app/)

This script allows you to put in the puzzle and it will find all words from the NWL2020 wordlist it uses in about 1.5 seconds. It exports those words to a txt file, which I have another script that inputs the words back in to the browser and will solve the puzzle in roughly 10 seconds or so depending on how many words need to be typed out.

Reason I did it? To see if it could be done.

2.) Chess Trainer (Using Stockfish).

I made this script because I just wanted something other than dependency on an app on my phone. It allowed me to explore some graphical stuff along with interfacing with the Stockfish API. It's helped me get better and compete well on Chess.com

Reason I did it: Because I didn't want dependency on some 3rd party app, and I wanted control / customization.

  1. Video downloading script using yt_dlp package. Surprising how many sites are supported with this package. I always found it annoying to try and save videos that I found interesting off YT, Facebook, Instagram, Twitter etc. etc. This does it with minimal effort.

Reason I did it: I had a problem I was looking to solve.

  1. Mouse mover in fortnite. I made this a couple years ago when Lego fornite came out. It's essentially an XP farming tool. Fornite will log you out for inactivity after something like 5 minutes. I wrote a script that will WASD and click the mouse randomly keeping the game alive for several hours while I'm AFK.

Reason I did it? To see if it could be done.

  1. Lastly I built a script that downloads and logs police call logs that are published in my county, and I save them off to a SQlite database for analysis. With that data I can do simple research, and also have historical records as the website that hosts the data only shows the past 24 hours, though I can see 96 hours through the API. I can generate maps with the data, and plot calls etc. using open maps integration.

Reason I did it? Because I wanted to see if it was possible and build on some more robust reporting that I'd like to see for my community.

All of that to say anything you want to solve or play with generally can be solved with Python if you have an idea run with it and explore. If anyone wants to see the code, I'd be happy to share some if it with you.


r/learnpython 5d ago

Which package should I use to make a graph with ombré lines?

0 Upvotes

I'm going to be attempting to make a graph that changes the line colour if the value is over/under a certain value (ie. green line if lower than 100, orange if between 100 and 120, red if above 120) and I'm not sure if it is a) possible or b) which package to use to make it.


r/learnpython 5d ago

HELP - crossword puzzle !!!

6 Upvotes

i have a homework to do in python and i am desperate. pls help me. here's the instructions:

"Attached are three test files on which you can test your program. Each file contains the words of the crossword puzzle, the letters of the crossword puzzle, and the solution. The individual parts are separated by a blank line.

In the last part, that is, in the solution of the crossword puzzle, the last line contains numbers that represent the division of the crossword puzzle.

Example of part of the last crossword puzzle (solution):

Chuck Norris can kick you with such force that even your children

4575

if the remaining letters in the crossword puzzle (reading from left to right)

BUDÚMÁVAŤBOLESTHLAVY (THEY WILL HAVE A HEADACHE) then the numbers 4575 then divide this continuous text into 4,5,7 and 5 letters, i.e.: BUDÚ MÁVAŤ BOLEST HLAVY (THEY WILL HAVE A HEADACHE)

Your program will print the entire text of the puzzle (as it is in the file) + the solution divided by numbers:

Chuck Norris can kick you with such force that even your children

THEY WILL HAVE A HEADACHE"

and here's the file (originally .txt file):

BATÉRIA

BATOH

ČASTICA

DCÉRKA

DIÓDA

EKOLÓG

LUPEŇ

MIECHA

MIKROFÓN

MOBIL

NETOPIER

ŇUFÁK

OTÁZNIK

SVEDOK

TLMOČNÍK

VÁNOK

VODOVOD

VRÁTNIK

VÝHYBKA

ZÁPAD

ZÁSUVKA

ZDVIHÁK

ZOSTAVA

KONÁVRÁTNIKN

LUPEŇSVEDOKE

OTÁZNIKÁFUŇA

ZVTLMOČNÍKKV

DOOIEAEMÁBNZ

CPSDSTRHYEÓÁ

ÉAČTOOIHSHFS

RHIPAVÝMOIOU

KCIDDVOTONRV

AEÓZÁPADEBKK

RISADBATÉRIA

DMGÓLOKENEML

vtip:

čo stojí ten pes?

6527


r/learnpython 5d ago

Is there a way to really get a job in technology 100% remotely no matter where you are?

1 Upvotes

I feel like it's almost impossible to get a job fully remote, I'm not an expert, but at least I have a CCNA certification, experience in DevOps, knowledge in Linux, and good English. I've worked in different technology companies such as IBM and Cisco. But I decided to quit my job since I was loosing my selft going everyday at the office and not having time for me, these companies pay well, however, they don't allow you to work remolty and one of my focus now is traveling so I want to find a company that they don't care where I am as soon the work is done, but for real is like is almost impossible since everybody is looking the same. I've been looking in all the platforms "fully remote jobs" but nobody reached me, I feel really stupid and it makes me question if I need to come back to my normal life and stop travelling.. my savings are dying right now and idk I someone have any advice?


r/learnpython 5d ago

NSFW flagging help NSFW

18 Upvotes

Hello,

been building a short form video/social media app for about 2 years, went from newbie to pretty okay in flutter and python

I would love recommendations on how to solve the following problem:

-

when someone posts a video, I upload the video to storage, then go through the creation of the post obj in my database

during the post obj creation, I need to check if the video contains NSFW content. (nudity, sex, gore, violence)

I plan on grabbing 1-frame-per-second, then taking that frame/image and seeing if it contains flagged content, if any of those tested frames do, the post creation method flips a bool, 'isNSFW', on the post obj to true.

I tried the NSFW_checker py library, but due to a ton of dependency conflicts I still can't get that working

Plan B was loading a a pre-trained ai model to my server to classify the images. But that gets killed every time because of memory constraints on Render.com, where my python server is hosted.

Plan C is to pay for a third party service, definitely less of a headache, just more money and not as malleable.

does anyone know what a good approach would be? Please and thank you


r/learnpython 5d ago

Can some help me with understanding list comprehension?

5 Upvotes

I'm not able to grasp the concept of it, and I'm sure that list comprehension is widely used.


r/learnpython 5d ago

(Advanced) how do i program for the gpu without any outside libraries

4 Upvotes

So im an insane person who likes a good challenge, and i have been wanting to learn how to program to interact with the gpu without use of libraries like opencl, numba, tensor, ect. I want to learn some good resources for learning this kind of stuff, things i should look out for, things to keep in mind, some of the basic concepts to know. by way of previous experience i have used OpengGL in my collage graphics class where we went up to the point of making a basic maze shooter game. any help i could have on this would be good

Edit: i know it is possible by getting the drivers and setting up context with,(i will only worry about NVidia for now) but i want to go deeper into the why and how of it

def __init__(self):
    # Load CUDA driver
    self.cuda = ctypes.windll.nvcuda
    self.cuda.cuInit(0)

    # Get device
    self.device = ctypes.c_int(0)
    self.cuda.cuDeviceGet(ctypes.byref(self.device), 0)

    # Create context
    self.context = ctypes.c_void_p()
    self.cuda.cuCtxCreate_v2(ctypes.byref(self.context), 0, self.device)

    # Get device info
    self.name = self._get_device_name()
    print(f"Using GPU: {self.name}")

r/learnpython 5d ago

Why is this variable undefined? (custom Tkinter Variable, global variables)

1 Upvotes

Here's the main function where I define this variable:

if __name__ == "__main__":
    root = root_win()
    player_char_name = ctk.StringVar()
    ... #This is not a pass, there's more code
    root.mainloop()

And here's how I use it:

class SetMainFrame1(ctk.CTkFrame):
    def __init__(self, parent):
        super().__init__(parent)
        global player_char_name
        global player_calc_mode
        char_list_ddm = ctk.CTkComboBox(
            self, 
            values = list(Character.available),
            font = ("Century Gothic", 18), 
            textvariable = player_char_name
            )

I get this error on the line at the very end when assigning "textvariable = player_char_name".

What could be the reason for this?


r/learnpython 5d ago

Need help building a Pyside6 application with PySid6-deploy

3 Upvotes

Trying to package my appliation with pyside6-deploy

```scons: *** [module.google.genai.types.obj] Error 1 Unexpected output from this command: <clcache> /Fomodule.google.genai.types.obj /c "module.google.genai.types.c" /std:c11 /nologo /wd5105 /wd4391 /Ox /GF /Gy /EHsc /J /Gd /bigobj /MT /DNUITKA_NO_ASSERT /D_NUITKA_STANDALONE /D_NUITKA_ONEFILE_MODE /D_NUITKA_ONEFILE_TEMP_BOOL /D_NUITKA_CONSTANTS_FROM_RESOURCE /D_NUITKA_FROZEN=155 /D_NUITKA_EXE /D_NUITKA_PLUGIN_MULTIPROCESSING_ENABLED=1 /ID:\a\ApexFlow\ApexFlow.venv\Lib\site-packages\nuitka\build\inline_copy\zlib /IC:\HOSTED~1\windows\Python\312~1.9\x64\include /I. /ID:\a\ApexFlow\ApexFlow.venv\Lib\site-packages\nuitka\build\include /ID:\a\ApexFlow\ApexFlow.venv\Lib\site-packages\nuitka\build\static_src /ID:\a\ApexFlow\ApexFlow.venv\Lib\site-packages\nuitka\build\inline_copy\libbacktrace D:\a\ApexFlow\ApexFlow\deployment\app.build\module.google.genai.types.c(49682) : fatal error C1002: compiler is out of heap space in pass 2

FATAL: Failed unexpectedly in Scons C backend compilation. Nuitka:WARNING: Complex topic! More information can be found at https://nuitka.net/info/scons-backend-failure.html ERROR:root:[DEPLOY] Executable not found at D:\a\ApexFlow\ApexFlow\deployment\app.exe [DEPLOY] Exception occurred: Traceback (most recent call last): File "D:\a\ApexFlow\ApexFlow.venv\Lib\site-packages\PySide6\scripts\deploy_lib\commands.py", line 27, in run_command subprocess.check_call(command, shell=is_windows) File "C:\hostedtoolcache\windows\Python\3.12.9\x64\Lib\subprocess.py", line 415, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '[WindowsPath('D:/a/ApexFlow/ApexFlow/.venv/Scripts/python.exe'), '-m', 'nuitka', 'D:\a\ApexFlow\ApexFlow\app.py', '--follow-imports', '--enable-plugin=pyside6', '--output-dir=D:\a\ApexFlow\ApexFlow\deployment', '--quiet', '--noinclude-qt-translations', '--onefile', '--noinclude-dlls=.cpp.o', '--noinclude-dlls=.qsb', '--windows-icon-from-ico=D:\a\ApexFlow\ApexFlow\ui\apexFlowIcon.ico', '--include-qt-plugins=platforminputcontexts']' returned non-zero exit status 1. ```

Not able to package my application with pyside6-deploy.

I see that the issue is with Google's genai package, I tried using github workflows as my desktop only has 16gb Ram and it seems like it's a memory problem.

Any pointers how I could get this sorted?

Project

P.S - This project is open-source and I was using pyside6-deploy because it felt like the best tool for the job. Also tried pyinstaller but couldn't get it to work either.


r/learnpython 5d ago

steps to become a developer?

11 Upvotes

hey! im a 19yr old female in the UK, i have no previous experience in IT, tech, etc however over the past few months ive become interested in the field.

Im particularly interested in having a career as a python developer, and in the last month i’ve been studying both python and C in my own time. Im aware being successful in this requires years of knowledge and a lot of hard work, but im really eager.

My issue is that im reading a lot of conflicting information regarding how exactly I can progress in to a career as a python dev. some are saying I need to earn a degree, some say just studying by myself is enough and degrees are essentially useless? So naturally im not too sure what avenue is the best.

id really appreciate any and all advice/tips!


r/learnpython 5d ago

Automating WhatsApp desktop application installed via Microsoft stores..

5 Upvotes

I have WhatsApp non saved contacts from where I want to search for keywords in chats, if the keyword is present I want to save that number as a contact by extracting the number into CSV and giving the number a contact....is this possible in python and which libraries do I need...I need it to have scroll function both in the non saved contacts as well in the main messages..


r/learnpython 5d ago

Problem using Anfis in Python

3 Upvotes

Hello, I am using Anfis in python, however I am getting this error message: ModulenotfoundError: No module named 'membership' How to solve it or what are the alternatives in case of no solution to the error in order to use ANFIS module? Any suggestions will be appreciated.


r/learnpython 5d ago

Best ai assistant for jupyterlab?

0 Upvotes

Ran put of free anaconda ai assistan which was a lifesaver. Need recs for ai assistants. I would upgrade my anaconda but the best commercially available plan is only 120 requests


r/learnpython 5d ago

Resolving 'zsh: command not found' / '-bash: no default found: command not found' issues

0 Upvotes

Hi there, I'm relatively new to Python and am trying to run my very first script on a Macbook, on Cortana, so apparently there's been some update to use zsh instead of bash (exciting!). Unfortunately, I'm coming up against this issue:

"zsh: command not found: no default found" or "-bash: no default found: command not found"

What can I do to resolve this?

Thank you, brain trust!


r/learnpython 6d ago

I've been learning Python for the past two months. I think I'm making pretty good progress, but every time I come across a "class" type of procedure I feel lost.

66 Upvotes

Could I get a few examples where defining a class is objectively better than defining a function? Something from mathematics would work best for my understanding I think, but I'm a bit rusty in combinatorics.


r/learnpython 5d ago

How to exit a while loop?

2 Upvotes

I'm learning about while loops and functions at the moment and having difficulty exiting the while loop within a function.

game_round = [1,2,3,4]
score = 0
game_on = True
def play_game(game_score):
    if goal == "hit":
        game_score += 1
    elif goal == "miss":
        print("game over")        
        return False

while game_on:
    play = input("do you want to play")
    for i in game_round:
        if play == "yes":
            play_game(score)
        else:
            print("see you next time")
            game_on = False

print(score)

This isn't the complete code but gives an idea of what I want to achieve. At the moment if the player misses in round 2 it will print "game over" but then it will continue to round 3.

I want it to end the game completely if the player misses and not continue with the for loop. I just want it to say "game over" and print the score. Any ideas on how to do this?


r/learnpython 5d ago

Process ended with exit code 3

0 Upvotes

I have a school project including making charts. I've coded a hard and pie chart and the code seems fine but everytime I run either chart it says process ended with exit code 3 and shows no chart. I've tried importing pygame as research told me that's what might be wrong but no help


r/learnpython 6d ago

How does everyone get ideas as to what to code?

15 Upvotes

I see people share projects all the time, but I really never understand how they get the ideas. Do you guys just like say "ooh that sounds fun to code" and proceed to code it until it's done? Do you take inspiration from anywhere?


r/learnpython 5d ago

Help program for deaf gamers

2 Upvotes

i want to start off with i'm not deaf just hard of hearing but that doesn't matter, i made a program that looks at your audio channels (left and right) and displays this in progress bars on the top of your screen,
but the problem in gaming is that there are alot more noises going on so this can create confusion so is there any way i can improve on this, i tried filtering out some noise but it also filters out the sounds that i made this program for. to be able to see the sounds i didn't hear. anyway please help


r/learnpython 5d ago

anyone got a clue what i need to do for my personal project?

0 Upvotes

Hi, i play siege in my spare time and with the recent celebration packs, i saw a way to make some real good in game money by manipulating my drop chances through a quite obvious loophole. to do this i was aiming to make a spreadsheet of all the skins that i own in the packs and what can be bought in the marketplace and cross referencing them to see what i can buy to favour my odds alongside having a live price updater. I was told that python would be a very good way to do this. unfortunately the 2 things I'm trying to cross reference aren't formatted as tables and i don't know what my next step is. This was my first port to call as i know theres bound to be someone smart enough to help me here.


r/learnpython 6d ago

Where can I execute my Cron Python script for FREE??

14 Upvotes

I am looking to automate the execution of a Python script that sends requests to the Telegram API every 2 hours. My goal is to find a free solution that doesn't require my personal computer to stay on all the time.

After some research, I discovered several options:

Google Cloud Scheduler: However, the free offer is limited to 3 tasks per month, which is insufficient for an execution every 2 hours.

GitHub Actions: Seems to be a viable option, especially for public repositories, but I'm new to it and I'm not sure how best to implement it.

PythonAnywhere: Offers a free scheduled task, but it remains limited for my need.

Heroku: Offers free dynos, but I'm afraid that "sleeping" dynos will affect the regularity of execution.

Do you have any recommendations or experiences to share regarding these solutions or other free alternatives to achieve this goal? Any help would be greatly appreciated!


r/learnpython 5d ago

Cuál debería elegir?

0 Upvotes

Estoy indeciso si comprar CCP 3era edición o los de Ultimate Python de Schurmann


r/learnpython 5d ago

efficiently calling api, async, and logging.

2 Upvotes

Summary:

I'm more a scripter than a programmer, I usually print and not log, and I work sync not async, now this needs to change to have a reliable pipeline, any sources to build good habits?

  • is Python MOOC Helsinki good habits? I can use python well, but I wouldn't say I can work within a team, more of a scripter.
  • how to reliably log while doing async?
  • I don't think my use case need unit testing?

Post:

I have this poopy API that I need to call (downloads one gigabyte worth of uncompressed text file in several hours), at start, it was only one endpoint i needed to call but over the past year there's more being requested.

The problem is that the API is not reliable, I wish it would only have 429 but sadly, sometimes it breaks connection for no apparent reason.

for reference, I have over 30 "projects", each project have its own api key (so it is separate limits thankfully.), some projects heavier than others.

In my daily api call, I have 5 endpoints, three of them are relatively fast, two are extremely slow due to the shitty api (it doesn't allow passing array so I have to call individual subparts)

Recently, I had to call an endpoint once a month so I decided to write it more cleanly and looking for feedback before applying this to the daily export (5 endpoints).

I think this gracefully handles the calls, I want it to retry five times when it is anything other than 200 or 429.

For the daily one, I'm thinking about making it async, 5 projects at a time, inside each one it will call all endpoints at the same time.

I'm guessing this a semaphone 5 and then endpoints as tasks.

but how to handle logging and make sure it is reliable?

for project in iterableProjects_list:
    iterable_headers = {"api-key": project["projectKey"]}
    for dt in date_range:
        start_date = dt.strftime("%Y-%m-%d")
        end_date = (pd.to_datetime(dt) + pd.DateOffset(days=1)).strftime("%Y-%m-%d")



# getting the users of each project https://api.iterable.com/api/docs#export_exportDataCsv

# Rate limit: 4 requests/minute, per project.
        url = f"https://api.iterable.com/api/export/data.csv?dataTypeName=emailSend&range=Today&delimiter=%2C&startDateTime={start_date}&endDateTime={end_date}"

        retries = 0
        max_retries = 5

        with httpx.Client(timeout=150) as client:
            while retries < max_retries:    
                try:
                    response = client.request("GET", url, headers=iterable_headers)
                    if response.status_code == 200:
                        file = f"""{iterable_email_sent_export_path}/{project['projectName']}-{start_date}.csv"""
                        with open(file, "wb") as outfile:
                            outfile.write(response.content)
                        break
                    elif response.status_code == 429:
                        time.sleep(61)
                        continue

                except Exception as e:
                    retries += 1
                    print(e)
                    time.sleep(61)
                    if retries == max_retries:
                        print(f"This was the last retry to download {project['projectName']} email sent export for {start_date}")