/r/learnpython

Photograph via snooOG

Subreddit for posting questions and asking for general advice about all topics related to learning python.


Rules

1: Be polite

2: Posts to this subreddit must be requests for help learning python.

3: Replies on this subreddit must be pertinent to the question OP asked.

4: No replies copy / pasted from ChatGPT or similar.

5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.

This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.

Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.


Learning resources

Wiki and FAQ: /r/learnpython/w/index


Discord

Join the Python Discord chat

/r/learnpython

896,807 Subscribers

2

basics in programming, economics or cs students

Sorry for the basic question but im currently in my last years bachelor in economics and are heavily going into quantitative analysis and maths. I realised that I enjoy programming etc. a lot and would like to go further into these fields. I realise that the field is huge so my question is where to start looking into further?

I would love some basic machine learning, prediction, algorithms and data science preferably in python but starting at a level without a lot of prior knowledge.

So if anyone has a course recommendation, what fields to look at first maybe...

Thanks!!

0 Comments
2025/02/02
22:36 UTC

2

How do I get the function to print once per letter in hangman?

I just finished my first hangman game, but I am facing an annoying problem. Whenever I have a word with a letter showing up multiple times, my correct statement gets printed out multiple times. How do I get it to only show up once? For a word like, COOKIE. If I input O, I will get:

CORRECT! The word contains the letter O

CORRECT! The word contains the letter O.

========================================

#for guesses that match

for position in range(len(answer_word)):

letter = answer_word[position]

if letter == picked_letter:

print(f"CORRECT! The word contains the letter {picked_letter} \n")

hidden_word[position] = picked_letter

print(hidden_word)

5 Comments
2025/02/02
21:58 UTC

1

How to reset 100 days of code by Angela Wu on Pycharm

I'm reattempting 100 days of code course. I have completed some of the exercises on Pycharm and while reattempting the solution is already there in front of my eyes. This is affecting my practice.

I want to reset this course progress such that I dont have to see my previously written code. How to do it?

Simple solution would be to just delete all code but that would also remove the pre written code by the instructor

0 Comments
2025/02/02
21:39 UTC

0

Tutorial for Exploratory Data Analysis basics

Here is the third part of the tutorial I used with undergraduate students at Federico II University in Neaples (Italy): an introduction to Exploratory Data Analysis

Data: the final frontier

0 Comments
2025/02/02
21:21 UTC

2

I need help creating inventory(absolute begginer)

So I am doing a text adventure. My first bigger project. I am trying to add inventory, I want it as a list, and at the start you have nothing. -Thanks for any help from you...

8 Comments
2025/02/02
20:41 UTC

4

using roots with math

im aware of how to square root numbers but is there a way to do different roots using variables?

7 Comments
2025/02/02
20:04 UTC

0

New to python. Created my first code to open urls and trigger tableau data source refreshes.

Planning to learn a few financial fundamental analysis. Any leads?

1 Comment
2025/02/02
18:54 UTC

1

Help me progress in python

I would really like to dive even more into python programming but I have no results, I have a bit of imposter syndrome and am not progressing, does anyone have an idea

1 Comment
2025/02/02
18:33 UTC

3

I'm looking for an async compatible persistent function cache. Any libraries like this?

I've found a lot of libraries but they either

- do not explicitly support async functions
or
- do not support persistence

Is there a library out there I'm missing?

2 Comments
2025/02/02
17:51 UTC

2

Take-Home Assignment Tips for Python

Hi all, I've been programming in Python for quite a while already, did some small projects in university and would say, I know many advanced core concepts and libraries in Python. Now, I am interviewing with a company and they asked me to create a small Python library as a take-home assignment (5-6h), which should further include some small tests, documentation and packaging. However, as I have never touched those sides of Python, I was hoping to get some tips on you, particularly:

  1. Which framework is best to write tests for Python? What should I look out for, when designing tests in a short amount of time?
  2. How to best create documentation in Python? I am already writing docstrings and type hints wherever I can, is it possible to extract a documentation from those?
  3. What do I need to know about packaging? In other words, what is the quickest way to make a repository ready to be distributed via PyPi and/or conda?

I know that there is plenty of resources on that online. But I hope, that some people here can give me tips that are especially useful for take-home assignment-type projects, where timesaving approaches are probably the best.

3 Comments
2025/02/02
16:12 UTC

15

I can write code, how do I take it further?

Hello, I've been using Python on and off for the last two years or so mainly at work (I'm not a dev, I'm mainly writing code to automate stuff) but I'd like to do more projects on the side. I'm a bit slow, but in the end the code WILL work as intended.

The thing is, I'm not a "good" programmer, yes my code works but when it tends to be a bit long, it starts to be messy, not optimized, dirty, and doesn't look like the "real" programmer's code of my company. (I.e. I'm using a lot of nested loops, functions calls in nested loops, never use classes, and lots other things). I also feel like I might be lacking some library knowledge, but I guess this could be another topic?.

For the record, I've been through "Python crash course" and "Automate the boring stuff" a while ago and I also have "Fluent Python" but found it was a bit too advanced at the time (maybe I need to try it again now)

So, how do I take it further, and learn how to be better at writing code? I'm open to any format (books, training, projects, courses, website,...)

Thank you!

25 Comments
2025/02/02
15:24 UTC

2

Thoughts on my beginner project? (Calculator)

Pastebin: https://pastebin.com/i0ParQRg

Hi everyone, year 1 CS student here. I've known Python for only 3-4 months, and this Calculator is my first attempt at creating something from scratch. It uses 2 files: you run Calculator.py to start the Calculator, which uses functions from draw.py. You click the buttons with a mouse and it should do the math right for everything except

  1. negative number input (it fails to recognize -1 in input but can show -1 in the answer)

  2. brackets on the same precedence level (sin(cos(x)) works but not sin(x)+cos(x)).

As a beginner, my code probably has many problems I cannot identify, so I am looking for your feedback on these particular things:

a) Readability: variable names, organization, easy/difficult to understand etc.

b) Efficiency: Did I use too many variables/too much memory? How could I shorten my code?

c) Any suggestions on how I can solve the negative number input/brackets problem?

Criticism is welcome and appreciated!

13 Comments
2025/02/02
14:46 UTC

7

Python for financial analysis

Hi, I'm more or less a complete coding noob.
I want to start learning Python but specifically for the following tasks:
- retrieving financial data from various sources
- systematic or algorithmic trading
- backtesting trading strategies
Is there a specific area of Python that is 'better' for me to start?
Thanks.

13 Comments
2025/02/02
13:46 UTC

1

help changing elements inside a list

so im trying to make a card game, and i have a part that prints out the random cards thats you get at the start of the game, and once you play a card, you need to take another one from the supposed virtual deck

i have a list of all the cards and it picks a random one to be the new card that you pulled

the list is like this pcardlist = [pcard1, pcard2, pcard3, pcard4] to pick a card to play you input a number starting from 1 to 4 so that it can choose the (n)th card of the list.

when it give you a new card i want it to change the value of the item, for example you pick the first card, and then when it gives you a new one it should be pcard1 = random.choice(tcardlist)

{t for total and p for player}

but it instead just replaces theitem a a whole instead of assigning a new value to it

sorry for the bad english probably

ill reply if anything from what i said is unclear

15 Comments
2025/02/02
12:18 UTC

1

Seeking Advice?

Hey everyone, I was wondering how to document my progress in learning Python. In a way that later down the road, I can show my learning path and how did I go about simple projects. I come from an Economics and banking background and always had a passion for coding.

6 Comments
2025/02/02
12:07 UTC

15

How would you rate the complexity of this Python task for beginners?

Hi,

I came across this task recently and was curious to hear your thoughts on it. Here's the task:

Write a program that calculates the average grade of a student over their entire education. On the first line, you will receive the name of the student, and on each subsequent line, their yearly grades. The student advances to the next grade if their yearly grade is greater than or equal to 4.00. If the student fails (receives a grade below 4.00) more than once, they are expelled, and the program terminates, printing the name of the student and the grade at which they were expelled.

If the student successfully completes the 12th grade, print:
"{student's name} graduated. Average grade: {average grade for the entire education}"

If the student is expelled, print:
"{student's name} has been excluded at {grade in which they were expelled} grade"

The output should be formatted to the second decimal point.

How would you rate the complexity of this task for someone who is learning Python?

  1. Is it a beginner, intermediate, or advanced task?
  2. Roughly how many months of Python practice would it take to solve such a problem comfortably?
25 Comments
2025/02/02
09:37 UTC

0

Help/Advice for a dnd 5e character sheet creator

Hey everyone, i have a passion project of making a dnd 5e character sheet creator in python as the title suggests, and I'm reaching the point where continuing the project is getting unmanageable, not that I'm going too stop, but more like progressing forward generally means i have too scrap the project, and reset as feature creep has gotten too much. Kind of a generic question, but if people have advice on how bad this code base is and ways i can improve my python would be beautiful, specifically saving and loading JSON documents is giving me the most trouble at the moment. Github is posted below, will require you too pip install dearpygui as that's what im using for UI! please dm for any questions about use, but it should be pretty straight forward, if something crashes or bugs out, usually just restarting the application fixes it cause some stuff only works on init rather then smoothly updating.

https://github.com/GaiaStromokov/dnd-project-hell

0 Comments
2025/02/02
09:35 UTC

0

Trying to install Pipx

This crappy website tells me to use commands to install in cmd or power shell, and I've tried Python's commands too. I cannot install Pipx; why in the world is this such a pain in the ass? My ultimate goal is to install Sherlock, but I cannot do that when the commands that are used to install Pippx do not work. I've also watched youtube videos on it, they ise they same non working commands.

4 Comments
2025/02/02
08:56 UTC

0

I have a project idea that I don't know where to start [Mangione related, kinda]

The project boils down to 'simplifying/automating insurance claims and (insurance)plan optimization'. I picked this topic for a hackathon that will be held in a few weeks, but me and my team are stuck at squabbling ideas that will make us actually start the project. Any help would be nice!

4 Comments
2025/02/02
08:51 UTC

0

Help Needed: Connect to SQL Server (hosted locally) With Spyder & pyodbc

I'm learning SQL and Python.

Installed:

  • SQL Server 2022 Developer Edition running on my local SSD
  • SSMS 2

I have a question about connecting locally to this same server with Spyder using Python (and running queries with Python).

  • Plan on following this guidance to connect via Python SQL Driver pyodbc:

https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/python-sql-driver-pyodbc?view=sql-server-ver16

  • Question: in Step 3 #4, #5, can I confirm that I replace the '<server-address>' field with my actual server name, and so forth.
  • In step 5, do I replace any of the information highlighted in red , or is this syntax highlighted?

Is this guidance fine, or do you have a quicker way?

Any help would be appreciated.

gingerj

2 Comments
2025/02/02
08:48 UTC

25

Best books to learn Python

Hello everyone! I am a 14 y/o teen, and I would like to learn Python to become an ethical hacker. Are these good books for learning Python?

  1. Base: Python Crash Course → Automate the Boring Stuff

  2. Intermediate: Effective Python → Fluent Python

  3. Advanced: Black Hat Python → Violent Python

  4. Security: The Hacker Playbook + Web Application Hacker’s Handbook

15 Comments
2025/02/02
07:55 UTC

0

HOW TO LEARN PYTHON

I took the cs50p course and reached like loop
but i felt i am not like learning it ,when facing the problem sets and all
i didnt know what to do and i always asked chatgpt what i should here ,like that
so can somebody tell me a good place to learn python
i want learn it so bad but i dont how

20 Comments
2025/02/02
05:25 UTC

4

Optimising multiplication of large 4d matrices

Hello everyone,

I trying to optimise a bit of code I have written. The code works for what I want to do but I am wondering if there is faster way of implementing it. I've attached two methods below that do the same thing. The first uses 6 for loops and the second 4 for loops, where I've removed two loops by broadcasting into 6-dimensional arrays. I thought the second approach might be faster since it uses less for loops, but I guess the memory cost of the broadcasting is too great. Is there something you guys see to improve speed?

First method:

 for i in tqdm(range(gridsize)):
    
    for j in range(gridsize):

        F_R = F0[i][j]
        
        for u in range(max(0, i - Nneighbours), min(gridsize, i + Nneighbours + 1)):
            
            for v in range(max(0, j - Nneighbours), min(gridsize, j + Nneighbours + 1)):
                
                F_Rprime = F0_rot[u][v]

                F_RRprime = F0[i - u + halfgrid][j - v + halfgrid] + F_R@T@F_Rprime

                for m in range(dims):
                    for n in range(dims):

                        A = slices[i][j][m]
                        B = slices[u][v][n]

                        F_RRprime_mn = F_RRprime[m][n]

                        F_Rr = B*A*F_RRprime_mn

                        total_grid += F_Rr

Second method:

for i in tqdm(range(gridsize)):
    for j in range(gridsize):
        
        A = slices[i, j]
        
        F_R = F0[i, j]

        for u in range(max(0, i - Nneighbours), min(gridsize, i + Nneighbours + 1)):
            for v in range(max(0, j - Nneighbours), min(gridsize, j + Nneighbours + 1)):

                B = slices[u, v]
   
                F_Rprime = F0_rot[u, v]
                
                F_RRprime = F0[i - u + halfgrid][j - v + halfgrid] + F_R@T@F_Rprime

                F_Rr = A[:, None, ...] * B[None, :, ...] * F_RRprime[:, :, None, None, None, None]

                total_grid += F_Rr

EDIT: For some context the aim to have have dims = 16, gridsize = 101, pixels = 15

28 Comments
2025/02/01
22:54 UTC

0

Don’t hate me for this question🙏

I’ve been using/learning with ai to build a desktop app but I am struggling with building the UI I want… I have the exact idea in a Canva made image but not sure how to convert to Python?

Is there a way to do this or?

Edit : forgot the question mark.

18 Comments
2025/02/01
22:27 UTC

2

Error when executing

Hello everyone, I am currently learning to program with python, but I am trying to execute code and I get an error, do you know why?

I get the following error:
PS C:\Users\FORIMPEX\Documents\PYTHON HOLA MUNDO> python intro.py

C:\Users\FORIMPEX\AppData\Local\Programs\Python\Python313\python.exe: can't open file 'C:\\Users\\FORIMPEX\\Documents\\PYTHON HOLA MUNDO\\intro.py': [Errno 2] No such file or directory

PS C:\Users\FORIMPEX\Documents\PYTHON HOLA MUNDO>

1 Comment
2025/02/01
21:38 UTC

1

Use variable to call subroutine?

example:

a = 'test'

how can 'a' be used to call a subroutine called test?

8 Comments
2025/02/01
21:35 UTC

3

clear QR code being detected, but not decoded

hello, I'm trying to decode this QR code (captured via a camera). The original QR code is a version 20 QR code that just encodes the string:

"Some data"

I'm using the qreader library for this. Here's my code:

qreader = QReader(model_size='l')

# Get the image that contains the QR code
image = cv2.cvtColor(cv2.imread("qr_20.jpg"), cv2.COLOR_BGR2RGB)

# I resized the image here as I heard bigger images have trouble processing. But doing so or not doesn't help with decoding
image = cv2.resize(image, (1050, 1050), interpolation=cv2.INTER_AREA)
image = cv2.flip(image, 1)
cv2.imwrite("blurred.jpg", image)  # so I can see the end result after resize

# I'm calling detect() first to see if it's actually detecting the QR code, which it does.
detected_text = qreader.detect(image=image)
print(f"=> amount of detections {len(detected_text)}")
print(detected_text[0])

# At decoding, qreader returns "(None,)" , indicating it failed to decode.
decoded_text = qreader.detect_and_decode(image=image)
print(f"=> detected: {decoded_text}")

Anything I'm missing? Thanks!

4 Comments
2025/02/01
21:32 UTC

1

Flask Book, Code Wars, or RealPython?

So I very slowly worked through a Python Github course. It took me a long time. Then I started a Flask course on Udemy. The course didn’t really challenge me to solve coding challenges on my own. Then from there I ordered a Flask book, which arrives tomorrow.

Thing is, I don’t know if a book or course is the ideal way to go. I’m thinking of getting a subscription to RealPython but it’s a lot of money.

Would code wars + youtube be worth a try?

7 Comments
2025/02/01
21:32 UTC

3

I am having trouble with a project (again)

In a previous post, I asked this community for help with an assignment I was struggling with and received some answers that helped me figure out a problem with the teacher's restrictions. However, after turning it in, I didn’t quite do it the way he had anticipated. As a result, he modified the assignment so that I now have to write a program that determines if a ship is between two planets based on its distance traveled at a speed of 150,000 miles per second, within a time interval of 0 to 1 day. The program must be written using only three if statements (he counts elif as another if statement). I’m not allowed to use things like lists, indices, or while or for loops—just basic if and else statements.

I’ve been stumped after days of work. Does anyone have any ideas?


Let me know if you need anything else!

28 Comments
2025/02/01
21:04 UTC

2

Linux Question

Do you guys recommend getting Linux to run through Windows 11 or making Linux the main os. And what is the differences?

11 Comments
2025/02/01
20:10 UTC

Back To Top