r/learnpython • • 2d ago

Need help with very basic script

3 Upvotes

Hi, I am basically brand new to python, so I may make a lot of mistakes in my wording. I have made a very basic script that retrieves specific values in text files and prints them to the shell. I have gotten it to the point where both values are retrieved and printed, however when they do print, they do so exactly 5 times in a row. I do not have five files in the directory, I only have one test file named "1.txt" with only the values I need as the contents. Can someone point me in the right direction? Apologies for the horrible formatting.

import os
import glob
import re

path = 'path'

provinces = re.compile('.*?provinces {.*?(.*?)}',re.MULTILINE)
id = re.compile('.*?id = .*?([0-9.-]+)')
a1 = None
a2 = None

for filename in glob.glob(os.path.join(path, '*.txt')):
    with open(filename, '+r') as f:
        for line in f:
            if provinces.match(line):
                a1 = provinces.match(line)
            if id.match(line):
                a2 = id.match(line)
            if a1 and a2:
                print(a1.group(1))
                print(a2.group(1))

The output of the shell in IDLE:

 1111 2222 3333 
123
 1111 2222 3333 
123
 1111 2222 3333 
123
 1111 2222 3333 
123
 1111 2222 3333 
123

Edit - I got the script to work after a few changes to its configuration. Thank you all who helped!


r/learnpython • • 1d ago

fix 0.00000001

0 Upvotes

i see sometimes after calcuaitons reulsts with x.99999999999999999999999999 or x.0000000000000002 how to fix it


r/learnpython • • 1d ago

Aprendiendo Python desde cero: ¿Cuál es la mejor manera de estudiar y practicar por mi cuenta

0 Upvotes

¡Hola a todos!

Estoy empezando en el mundo de la programación y, en particular, me interesa aprender Python. Actualmente soy principiante y me gustaría desarrollar una comprensión sólida de los fundamentos de la programación, en lugar de simplemente memorizar código o seguir tutoriales.

Tengo pensado estudiar de forma autodidacta, pero quiero asegurarme de aprovechar mi tiempo de manera efectiva y desarrollar buenos hábitos de programación desde el principio.

Agradecería mucho sus consejos sobre algunos aspectos:

  • ¿Qué recursos de aprendizaje, cursos o libros recomendarían a alguien que está empezando desde cero?
  • ¿Cuál es la mejor manera de equilibrar el estudio de la teoría con los ejercicios prácticos de programación?
  • ¿Qué tipo de proyectos para principiantes recomendarían para ayudarme a desarrollar habilidades de resolución de problemas y comprender la lógica de la programación?
  • ¿Cuántas horas al día o a la semana recomendarían dedicar al aprendizaje de Python?
  • Desde su propia experiencia, ¿qué harían de manera diferente si estuvieran aprendiendo Python por primera vez?

Me interesa especialmente conocer sus experiencias personales, métodos de aprendizaje y cualquier error que debería evitar como principiante.

Agradecería mucho cualquier consejo, recomendación o recurso que puedan compartir. Tengo muchas ganas de aprender.

¡Muchas gracias de antemano por su tiempo y ayuda!


r/learnpython • • 1d ago

[Help] The os.system is deprecated

0 Upvotes

I've seen someone else asked this question, but get no answer.

I want to make a countdown clock without leaving any trace of previous numbers:

for i in range(countdown, 0, -1):
    os.system("cls" if os.name == "nt" else "clear") #Error: os.system is deprecated
    print(i)
    time.sleep(1)

What should I do instead? (Why can't we put pictures here....)


r/learnpython • • 1d ago

whats the purpose of updating variables?

0 Upvotes

heyhey very new to this day 2 of learning python im so fascinated im in love but what is the purpose of updating variables

example;
>>>default_option="upload"

>>>new_status="download"

>>>new_status=default_option

>>>print(new_status)

upload

this makes no sense to me and it just further complicates the code u write by being disorganized and messy,

i guess my question is, is it if you mess up instead of clearing previous lines you can update the variable? or is it kinda just useless but something needed to be taught?

any help would be appreciated, any recommendations as a beginner are also appreciated!!


r/learnpython • • 2d ago

Need help with list comprehensions

0 Upvotes

Guys somebody briefly explain the concept of List comprehension cuz its too difficult for me to grasp since I am a beginner. I am learning python for biopython. Someone explain it for me.


r/learnpython • • 2d ago

Portable GUI in Python

0 Upvotes

Hi! I don't know Python, and I'm wondering if I can create a portable GUI inside a single folder. For example, I want to have my own MyCustomGUI.exe in a folder, and right next to it, the following subfolders:
_internal
bgutil-ytdlp-pot-provider-master
yt-dlp-plugins
along with five .exe files:
deno.exe
ffmpeg.exe
ffprobe.exe
yt-dlp.exe

Is it possible to write Python code that makes all of this work and keeps it completely portable?

To be honest, I've been trying to do this for three days straight without knowing anything about programming. Once, I even managed to run a compiled .exe inside the folder, but as soon as I copied it to another drive, everything completely broke down.
Yeah, maybe it's my fault for trying to use the free versions of ChatGPT and Gemini, but I really thought that creating something as basic as a GUI would only take about 20 to 30 minutes. I'm actually in despair right now; I haven't felt this awful in a very long time.


r/learnpython • • 2d ago

Attribute look up visualized

4 Upvotes

Are there any good videos or images that visualize how attribute look up works? I am trying to understand what is happening in the background so I can understand and work better with classes and objects.
Thanks!


r/learnpython • • 2d ago

New to Python- Any Suggestions?

2 Upvotes

hi folks, how are you doing?

i have been thinking of learning something new and thought i'd give Python a shot. i've never coded before, so i am wondering how difficult it would be to get started with Python as a complete beginner.

the reason i am interested in learning it is that i've been thinking about creating a visual novel for a while. i am looking into Ren'Py, now- it has its own scripting language but also uses python, so i thought learning some python might be useful for the project.

a few things i'd like to get some advice on from y'all:

  1. any particular resources or youtube channels would you recommend?
  2. how difficult is python for someone who has never coded before?
  3. this might be off topic here but any idea on how much python would I need to learn to make a visual novel in Ren'Py?
  4. can i use any ai tools from the get go or learn some stuff first?

would really appreciate any advice. thanks and be blessed!


r/learnpython • • 1d ago

It Took me 110mins to Solve. Deepseek Solved it in 0.6 Seconds.

0 Upvotes

I’ve been practicing python seriously lately preparing for my computational biology MSc, so I decided to challenge myself with a phylogenetic placement challenge (open data).

I spent about 2 hours working on it then I gave the exact same problem to deepseek.

0.6 seconds.

We are mere supervisors now.


r/learnpython • • 2d ago

Why when i minimize pydroid and come again all i was doing is gone and all i get is this: / $

0 Upvotes

Title


r/learnpython • • 2d ago

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

4 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 • • 2d ago

I need help with a rocket simulator I'm buidling

2 Upvotes

I'm a high school student who is interested in becoming an aerospace engineer so in the summer I decided to start building a rocket simulator in python for fun.

What it does so far:

  • Parses real motor thrust-curve files (RASP .eng format) and interpolates them with numpy.interp instead of hardcoding constants
  • Implements RK4 integration from scratch for the actual flight dynamics (upgraded from Euler once I understood why it wasn't accurate enough)
  • Monte Carlo analysis, runs the full flight simulation ~200 times with randomized conditions and aggregates the results
  • 3D visualization two ways: PyVista for a quick animated flight path, and a full Blender (bpy) pipeline that imports a real 3D rocket model, keyframes it along the simulated trajectory, and renders it with Cycles
  • Modular structure, physics, motor parsing, atmosphere model, and stability calc are all separate importable modules, not one giant script

Would really appreciate feedback on the code itself, structure, whether my module boundaries make sense, anything that reads as non-idiomatic Python, places I should be using classes instead of dicts/functions, that kind of thing.

Github : https://github.com/AliHilalii/Rocket-simulator

Thanks a lot guys.


r/learnpython • • 2d ago

I want to make my own text to speech program that uses a specific amount of old 2000's and 2010'tts models, with filter option

1 Upvotes

Any advice on the possibility of achieving this? I'd like to add tts models like Paul US, or Iviola UK in the program, choosing between them and having the ability to use filters


r/learnpython • • 2d ago

Tech stack recommendations for Python based app on Android

0 Upvotes

Hello everyone, I am currently working on a pet project where I am trying to run Vosk (speech to text) model on Android device. For this I wanted some suggestions, can you guys share which tech stack and tools I can use for this?

I have used PyInstaller before which provides us functionality to build python app as Android too, so maybe I can try that. However I want to see if something better is available and also which libraries or separate language altogether can I use to make UI part of this. Any suggestions would be appreciated, I just want my Vosk model to be able to parse my voice to text in Android device and that's my only requirement.

Please give any information you have, thank you.


r/learnpython • • 2d ago

someone tell me what to do with learning python (cs50p)

0 Upvotes

yehh seniors i just stuck at the side off tutorial and i want to learn python fast i am learning from cs50p clearing or perhaps it's not i want now whenever i used to coding or solving some question i am blink and i want to out off it if anyone know how to do it or anything in this case please suggest me something


r/learnpython • • 2d ago

py to app with buildozer

0 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 • • 3d ago

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

13 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 • • 3d ago

A freshman who wants to study

1 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 • • 3d ago

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

12 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 • • 2d ago

Why i cannot run anything in the terminal

0 Upvotes

It doesn't work:

/storage/emulated/0 $ pytest

Traceback (most recent call last):

File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/bin/pytest", line 3, in <module>

from pytest import main

File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.13/site-packages/pytest/__init__.py", line 7, in <module>

from _pytest import version_tuple

ImportError: cannot import name 'version_tuple' from '_pytest' (/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.13/site-packages/_pytest/__init__.py)

/storage/emulated/0 $


r/learnpython • • 3d ago

My Python Project as a Beginner

7 Upvotes

https://github.com/ZaidAHK/LENDnFUND

The project is just the syntax I wrote


r/learnpython • • 3d 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 • • 3d 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 • • 3d 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.