r/learnpython • • 5d ago

Ask Anything Monday - Weekly Thread

1 Upvotes

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.


r/learnpython • • 1h ago

Accidentally did something while trying to figure out how to install python libraries

• Upvotes

Hi,

I'm trying to figure out how to install python libraries because the magic "pip install tensorflow" doesn't seem to work

I found this thread which told the user to just try "py -m pip install requests" so my dumbass just pasted that in before realizing what I was doing

I got two instances of yellow text in

0/5 [urllib3]  WARNING: The script idna.exe is installed in 'C:\Users\USERNAME\AppData\Local\Programs\Python\Python314\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
   ---------------- ----------------------- 2/5 [charset_normalizer]  WARNING: The script normalizer.exe is installed in 'C:\Users\USERNAME\AppData\Local\Programs\Python\Python314\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location

I think what this means is just that I installed the "requests" library, right? And maybe something went wrong? I don't need this library lol. Is there a way to like undo this? Should I try to undo this? I don't get why this installs files without telling me where it's putting them

(I also tried to do the same thing, "py -m pip install tensorflow", with tensorflow and got similar warnings btw, is this bad?)


r/learnpython • • 4h ago

A freshman who wants to study

0 Upvotes

I don’t know where to start learning or what knowledge I should acquire since nothing has been taught yet ,but l hope to have a plan for the future that can guide me when I begin studying and exploring different approaches. Thanks for you.


r/learnpython • • 1h ago

py to app with buildozer

• Upvotes

from yesterday i am trying to convert py to app with buildozer but ther were too many errors can any any pone help me in it i am using python 12.0


r/learnpython • • 17h ago

How would I go about creating save files for a text-based game?

6 Upvotes

I am using visual studio code to create a text-based game in Python. I want the ability to create save files for obvious reasons.

Currently, my plan is to get the player to name the save file, which would create a .txt file, then save certain veritable within it, with the file looking a bit like this, but larger:

HP = 50

Name = Willow

Chapter = 5

Killed_jeremy = True

To do this, when certain choices are made (Like whether to kill or spare an enemy), it can be saved for future use.

How would I go about saving the data to the file, and then reading the file so it acts as a bit of code run just after the save file is chosen

I am more than happy to do this in a way that isn't with a .txt file, that's just my current plan


r/learnpython • • 20h ago

How do I reliably extract text from a large medical PDF when normal PDF-to-text converters mess up the structure?

10 Upvotes

I have a large medical PDF where the information I need is already available as text inside pdf , but the problem is that simple PDF-to-text converters completely mess up the structure. The PDF has headings, tables, multiple columns, line breaks, and drug entries that continue onto the next page.

When I convert it to plain text, the text gets jumbled—for example, content from different columns can get mixed, headings can get separated from the information below them, tables lose their structure, and a drug entry that continues on the next page becomes difficult to associate correctly.

I need to process around 400+ drug entries automatically, so manually cleaning the text isn't practical. What is the best way to extract text from this kind of PDF while preserving the original structure and relationships between headings, tables, columns, and continued pages?

Should I use something like PyMuPDF, pdfplumber, Docling, Marker, PyMuPDF4LLM, or another approach? My end goal is to get clean, structured source text first and then use an LLM to convert it into JSON, while making sure the original information isn't lost, mixed up, or hallucinated.


r/learnpython • • 19h ago

My Python Project as a Beginner

8 Upvotes

https://github.com/ZaidAHK/LENDnFUND

The project is just the syntax I wrote


r/learnpython • • 22h ago

Interpolated Heatmaps with Python

8 Upvotes

I've been messing around with Plotly Express and Plotnine, but I can't figure out how to do what I'm trying to do with water quality data.

I have a pandas dataframe that has columns called Sample Date, Depth (m), and Temp (C). I only have about 100 data points per year. Each date has 5 or 6 readings at whole meter intervals at a single location starting at zero (the water surface). I have no problem making a scatterplot, but I want to create some sort of interpolated mesh (or I think they call it a spline in some contexts) that effectively blends the colors into each other both vertically through the water column and also horizontally over time to show the temperature gradient throughout the year.

Sorry if this is basic stuff, but I haven't been able to figure it out. The closest I got is by importing the table into ArcGIS Pro and treating it like a map.

Any idea how to do this?


r/learnpython • • 6h ago

Why is this causing an error

0 Upvotes

the code that causes an error

print = hello

print(print)

What should i do i do not know anything i am new to coding how do i fix this


r/learnpython • • 1d ago

Learning Python coming from PHP?

3 Upvotes

Hi all, just looking for recommendations on getting up to speed with conventions/syntax and quirks of Python for someone coming from the PHP world. I've got some grasp of OOP/SOLID/DRY/Interfaces/Abstractions etc... also experience with Frameworks so really looking for a crash-course on Python to get me up to speed and understand what's happening when I look at Python code.


r/learnpython • • 17h ago

What 's the fastest way to learn python?

0 Upvotes

Hello guys Im looking for a fast roadmap to learn and practice python. I bought a course in udemy called ' 100 Days of code : the complete Python Pro bootcamp ' but I do not know if it was a good purchase.


r/learnpython • • 1d ago

What I learned yesterday while learning Python automation

3 Upvotes

​

Yesterday I continued learning Python's "os" module.

I practiced working with folders and files using things like:

- "os.path.basename()"

- "os.path.splitext()"

- "os.walk()"

- Finding files by extension

- Counting files inside folders and subfolders

I also built a small file finder that searches through folders and counts how many ".py" files it finds.

Nothing complicated, but I'm realizing that these small exercises are helping me understand how automation actually works with files and folders.

My goal is to eventually use Python to automate repetitive tasks for real businesses.

I'm still learning, but I'll start sharing what I build along the way. 🚀


r/learnpython • • 1d ago

Slow print for text-based game

0 Upvotes

I am trying to make a text-based adventure game in Python, how do I make it so the text is typed out slowly and not instantly? I've tried ways online, but they keep returning None at the end. How do I fix this?


r/learnpython • • 1d ago

Getting a view from a boolean numpy array... somehow

1 Upvotes

I'm coding a Sudoku generator to improve my skills and I'm hitting a brick wall with a specific function to get the "neighbours" of an index (so, all the numbers that it can't be the same as). Here's my current code, just rows and columns for now:

def neighbours(idx: tuple[int, int], board: np.ndarray) -> np.ndarray:
  idcs = np.indices(board.shape)
  print(idcs.shape)
  neighbool = np.logical_xor(idcs[1] == idx[1], idcs[0] == idx[0])
  return board[neighbool]

This code does get the right values, but what I really want is to be able to modify those values and have the actual array be modified - so, to have a view. But about two hours of running around in the numpy docs has me completely stumped on any way to use a boolean array to index another array without it being a copy.

If I can't do it, I guess I'll have to use a list of slices dancing around the target index? Which sounds really headachey, and I'd love to be able to do it this simple way if it's in any way possible.


r/learnpython • • 1d ago

Lambda expressions for Web elements?

1 Upvotes

Hi, I work with C# but wanted to refresh my Python knowledge. Have been thinking about solutions I know for my C# code and how they would work in Python, but ran into something that I'm not sure how to "translate" from C#.

C# public IWebElement button => driver.GetElement(By.Id("Id"));

This will return me an element when called, even when on class construction it doesn't exist - as the expression is only evaluated when it's called, i.e. when I need it in code. As opposed to simply using = instead of =>, which would return a missing element exception on class build if the element is missing from DOM.

How would I do this in Python? I looked up lambda expressions, but I'm unsure if this would work/be very graceful, since I didn't find any mention of this as a solution that's used.

Python button = lambda driver.find_element_by_id("id")


r/learnpython • • 2d ago

Which code do you consider more "Pythonic" for this Pattern?

40 Upvotes

The Pattern:

*                 *
* *             * *
* * *         * * *
* * * *     * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * *     * * * *
* * *         * * *
* *             * *
*                 *

What my friend wrote:

n = int(input("Enter the number: "))
for i in range(1, n + 1): 
    for j in range(1, i + 1):
        print('* ', end = "")
    for j in range((n - i) * 2):
        print(' ', end = "")
    for j in range (i, 0, -1):
        print('* ', end = "")
    print()


for i in range(n, 0, -1): 
    for j in range(i , 0, -1):
        print('* ', end = "")
    for j in range((n - i) * 2):
        print(' ', end = "")
    for j in range (1,i+1):
        print('* ', end = "")
    print()

What I wrote:

while True:
    n = int(input("Enter an Even Number: "))
    if n % 2 == 0: 
        break
    else:
        print("Number must be Even.")


myList = []
totalCharacters = (2 * n) - 1
for i in range(1, n // 2 + 1):
    spaces = totalCharacters + 1 - (4 * i)
    myList.append (f"{"* " * i}{" " * spaces}{"* " * i}")


print("\n". join (myList))
print("\n".join(myList[::-1]))

As you can see, I came up with a formula for this pattern using "totalCharacters" and "spaces".

Which code would you consider more "Pythonic"? Like, in terms of flexibility and readability?
I'd also be happy to learn even better ways to print this pattern :)


r/learnpython • • 1d ago

Deploying Python Install Manager via Config Manager/SCCM to computer lab

4 Upvotes

I'm attempting to deploy the latest Python Install Manager to a few computer labs running PyCharm in our school district, but am having issues. I was wondering if anyone here had some insight/tips to share.

Few facts up front:
- Config Mgr runs processes as either local System or the User who is logged in.
- Student accounts do not have access to command line or powershell, nor do they have access to their %AppData% folder in Explorer.
- Installing a UWP app as System does not make that app available for that built-in account, and the app is not installed for other users until they log in.
- PyCharm's automatic "let me download a Python runtime and set up an interpreter for you" isn't working; I have a ticket in with their support.

The issue I'm having is that deploying the Install Manager via Add-AppxProvisionedPackage doesn't then allow me to run py install --target="C:\Program Files". Students do not have admin privileges to install UWP apps (or edit environment variables), so the deployment script must run as System. But System does not actually get py.exe installed to their %AppData% folder. And b/c adding an .MSIX package to the Windows image doesn't actually install the app until a user logs in, I can't run py.exe out of another user's profile when the MSIX is added.

In theory, I shouldn't have to be doing any of this, b/c PyCharm has the ability to do so, but it's not working. It downloads the files to the student's %AppData% folder, but then fails to create an interpreter. Student's can't create an interpreter, b/c trying to "browse" to the Python files is blocked, b/c PyCharm opens an Explorer window, and they do not have access to their %AppData% folder in Explorer. Even if they use the terminal built-in to PyCharm to run py install, they would still need to set up an interpreter, which they cannot do. Thus, I'm in catch-22 scenario.


r/learnpython • • 1d ago

Software development quesiton

0 Upvotes

This might be basic questions I'm sorry in advance. A little background I got a BS in computer science with AI concentration. I have code on python, java script. I have some projects that I have done and now I want to see how I can make them a installable file that I can install on any computer ( example a download from a store or just a .exe) I been looking around and I might not be looking on the right places but I would like some guidance maybe were to look or a tool that people use for this?. Any advice is welcome.


r/learnpython • • 1d ago

Need advice on handling nested data and dynamic popups/tabs in web scraping

3 Upvotes

Hey everyone,

I am working on extracting some data from a job board for a personal project. I can get the surface-level data (Company, Role) easily, but the specific details (like HR name, stipend, and team info) are nested. They only load when I click a specific element which opens a dynamic modal/popup, and then I have to navigate through different tabs inside that modal to find the relevant information.

I am looking for recommendations on the most efficient tools or approaches to handle this nested URL/dynamic popup scenario reliably. I want to avoid my scraper getting stuck or rate-limited during this multi-step extraction.

Would headless browsers like Playwright/Puppeteer be the absolute best choice here, or are there any advanced tools/methods that handle nested tab navigation gracefully without heavy overhead?

Any guidance or architectural advice would be really appreciated!


r/learnpython • • 1d ago

What Python concepts do you still have to look up?

4 Upvotes

I’ve noticed that some Python things stick immediately, while others I understand but still have to Google every time I use them.

For me, stuff like list comprehensions and basic loops is fine, but I still occasionally forget the syntax for things like decorators, lambda, or working with dictionaries in more complicated ways.

Is this normal, or are there certain Python concepts that are worth making an effort to memorize instead of looking them up when needed?


r/learnpython • • 1d ago

Learning python

0 Upvotes

What’s the best text book to read if you are learning python using cs50 video?

This is for absolute beginner.


r/learnpython • • 1d ago

List items are edited when adding new items? Possibly a variable reference issue

0 Upvotes

So I have a variable called Y with a changing value. If for loop variable X is some value, append Y to myList.

Every time it appends to the list, it changes every other already added item. I’m thinking the problem is that it’s not adding values but is instead adding references. So when Y changes, it changes every item in the list.

Why is it doing this and how can I stop it from doing this? I want it to append the value inside of Y, not a reference to Y.

Code: https://www.reddit.com/r/learnpython/comments/1wv4tpo/comment/pda098z/

What I'm trying to do is make a list of everywhere that there's a piece of a block. It's going to be a terminal Tetris game.

The playfield is a custom matrix, a list of lists. I dunno if that'll work well with lists. I did the same thing with arrays in another language. I don't know if Python's going to play nice or be special.

The blocks are also lists of lists. You could probably do that astronaut meme with my code "It's all lists of lists? Always has been"


r/learnpython • • 2d ago

Gimme silly ideas, please

2 Upvotes

I'm just bored. I already made a code that prints a code that prints the multiplication table. What else I can do!?

``` _print = print _str = str

def print(a = '\n'): _print(a, end = '', flush = False)

def str(a): return _str(a).center(5)

def range(a = 1): while a < 11: yield a a += 1

with open('main.py', 'r') as a: [print(c) for b,c in enumerate(a) if b not in (15,16,17)] import('sys').exit(0)

for a in range(0): if not a: print(' ') else: print(f'{str(a)}|')

for a in range(): print() print(str(a)) for b in range(): print(f'{str(a*b)}|') ```


r/learnpython • • 1d ago

Python question

0 Upvotes

Hi! I'm Bence and I want to learn in python. I started python programming like a month ago, and I want to be better in python programming. I wanted to ask u if u know any app or anything for learning python. (I know the start commands, print, input, and I know how to type an input like something = input() | print("Hi, !" {something}. Thanks for ur help, have a good morning/day/night! :)


r/learnpython • • 2d ago

Setting timer on a different thread in Pyside6

6 Upvotes

I am build a program that basically executes some code and I want to add a timer so the user can see how long the program has been running for.

My issue is that I do not get how to move it to a different thread so it does not freeze.

What it needs to do is, run for 1 second then update a label and start the timer again.

Any resources I can read or help?