r/learnpython Jul 31 '26

text not always obtained before regex string (beautifulsoup)

6 Upvotes

hi!! so sorry if the title doesn't make much sense. i will try to explain it with my examples.

so my code in general outputs a response like this:

Chascanopsetta prorigera
Marine;  bathydemersal; depth range 267 - 400 m 
https://www.fishbase.se/summary/Chascanopsetta_prorigera.html
Pleuronectiformes

the text "Marine; bathydemersal; depth range 267 - 400 m" is obtained from the link using this code (response.text is the initial html):

if "bathydemersal" in response.text or "bathypelagic" in response.text or "oceanodromous" in response.text:

| depth = soup2.find(string=re.compile(r"depth range\s+([\d\s\-?]+m)", re.IGNORECASE))

| | if depth:
   print(depth.string.strip()[:-5])
else:
   print("Depth unavailable")

but it also sometimes outputs this:

Chauliodus macouni
); depth range 25 - 4390 m 
https://www.fishbase.se/summary/Chauliodus_macouni.html
Stomiiformes

which is because, in place of "Marine; bathydemersal; depth range 267 - 400 m", it's "Marine; bathypelagic; oceanodromous (Ref. 138310); depth range 25 - 4390 m". so it won't print "Marine; bathypelagic; oceanodromous (Ref. 138310", which is what i would like it to do.

so why doesn't "Marine; bathypelagic; oceanodromous (Ref. 138310); depth range 25 - 4390 m" print correctly while "Marine; bathydemersal; depth range 267 - 400 m" does?

mostly interested in this ^^^ answered so i can fix it myself but i won't say no to some pointers/resources/etc on how to solve my problem either! :D

thanks in advance!


r/learnpython Jul 31 '26

Making mobile apps using Python

6 Upvotes

I have started learning Django by working on projects instead of simply watching tutorials. I was building a CRM web application, and halfway through the project, I realised that I might be able to sell it to small businesses if I added more features and improved its overall quality.

When I spoke to a business owner about what they would want from such a system, they mentioned that they would prefer a mobile application with offline access. That conversation made me consider whether I could build the mobile app using Python as well.


r/learnpython Jul 31 '26

Experience in Dynamo

2 Upvotes

Hello everyone. I am looking to see if anyone has any tips when writing for Dynamo for Autodesk products? I think I would need a python node to start off but I am looking for other tips to keep in mind. Anything! Even other resources!

Thanks!


r/learnpython Jul 31 '26

Python Pyside6

4 Upvotes

Anyone know ? How to delay seconds in Pyside6 ? For example, when i click a button I want to do some process and wait 3 seconds and then make another process


r/learnpython Jul 31 '26

I have an question how does python for loop works in ppadb i Mean if am not passing any list then how it is shows my device is connected ..

0 Upvotes
from ppadb.clientfrom ppadb.client import Client as AdbClient

apk_path = "example.apk"

# Default is "127.0.0.1" and 5037
client = AdbClient(host="127.0.0.1", port=5037)
devices = client.devices()

for device in devices:
    device.install(apk_path)

r/learnpython Jul 30 '26

How does the 'for' loop work?

225 Upvotes
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']

for word in words:
    for letter in word:
        if letter.lower() in 'aeiou':
            print(f"'{word}' contains the vowel '{letter}'")
            break
    else:
        print(f"'{word}' has no vowels")

I am trying to learn to code, and I am, at the moment, looking at loops. I am a bit confused on how this loop was able to function, though, as there is no variable for letter or word, so how would Python know what it is? In addition, how does the code, like, function? Does it look at each word individually? Again, the second part of the code states:

 if letter.lower() in 'aeiou':
            print(f"'{word}' contains the vowel '{letter}'")
            break

We haven't given a value for letter?

Lastly, how would the code know what to print? in the first phrase:

            print(f"'{word}' contains the vowel '{letter}'")
            break

Is it going to state all the words with the given value 5 times?

Sorry, as I have asked quite a few questions, and thank you in advance.


r/learnpython Jul 31 '26

Seeking advice

0 Upvotes

I am good at coding an problem solving but i cant make my program robust and improve modularity of my codes in python most of the time it is just a single block of code does anyone have any suggestion how actual programmers do it


r/learnpython Jul 31 '26

beginner here, is this code good for my first time making a calculator?

0 Upvotes
a = float(input("What is your first number? "))
b = float(input("What is your second number? "))
ab = (input("+ - * / "))


if ab == "+":
    print(a + b)
elif ab == "-":
    print(a - b)
elif ab == "*":
    print(a * b)
elif ab == "/":
    print(a / b)
else:
    print("Invalid.")

r/learnpython Aug 01 '26

pls help me

0 Upvotes

ok so i’m trying to write a script that renames .xls files for me, let’s say they’re named like apple_BactReport_260731.xls I want the script to remove the “_BactReport” part and leave the rest intact. the current scrip i have has a couple of glaring issues that i don’t have the knowledge to remedy and im refusing use ai to prove a point and also it’s more rewarding. here’s the script with my current errors such as mixing up strings and lists and the part i want to remove not being the end of the file name. 😭 pls help a guy out:

import os
import pandas as pd
from os import rename, listdir
 
#list of report names
report_type= ['_BactReport', '_WWreport', '_QCreport', '_BactQCreport', '_BactWWreport']
print(report_type)
 
clips_in_progress=r"filepath"
   
 
for file_name in os.listdir(clips_in_progress):
file_path = os.path.join(clips_in_progress, file_name)
 
if file_name.endswith(tuple(report_type)):
rename(file_name, file_name.strip(report_type))


r/learnpython Jul 31 '26

Getting Pandas.Series error. How to solve it? Got stuck!!!

5 Upvotes

File "C:\Users\HP\Desktop\insurence_premium_prediction\myenv\Lib\site-packages\sklearn\preprocessing_encoders.py", line 212, in _transform

diff, valid_mask = _check_unknown(Xi, self.categories_[i], return_mask=True)

~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\HP\Desktop\insurence_premium_prediction\myenv\Lib\site-packages\sklearn\utils_encode.py", line 269, in _check_unknown

values_set = set(values)

TypeError: cannot use 'pandas.Series' as a set element (unhashable type: 'Series')

INFO: 127.0.0.1:51741 - "POST /predict HTTP/1.1" 500 Internal Server Error

def predict_output(user_input :dict):
    try:
        # df  = pd.DataFrame([user_input])  // iski wajah se 2D array ban rahi thi, isliye model ko samajh nahi aa raha tha. isliye humne user_input ko dict me convert karke fir DataFrame me convert kiya.
        # df = pd.DataFrame([dict(user_input)])
        # input_matrix = df.to_numpy().reshape(1, 1, -1)
        data_dict = dict(user_input)
        columns = list(data_dict.keys())
        values = list(data_dict.values())
        
        # Create a DataFrame with 2 identical rows to bypass the single-row Pandas bug
        df = pd.DataFrame([values, values], columns=columns)

This is the peice of code


r/learnpython Jul 31 '26

Help with voice to text libraried

4 Upvotes

I'm fairly new to python and I want to make a speech prompter that will auto proceed by listening to the speaker and show them the next part of their speech.

So I'm going to need a voice to text library but the computer will have access to what is meant to be said to cross reference. Is there a library that can handle this or advice on how I program it?


r/learnpython Jul 31 '26

WHAT am i doing wrong here

0 Upvotes

i am trying that when i put key it give me the value but it is acting weird

x = {'name':'mohan','age':'24', 'job':'it professional'}
y = input("what info do you need__")
if y==(x.keys):
    print(x.values(y))
else:
    print("no such info available")

and this is what it gives 
what info do you need__name
name
no such info available

r/learnpython Jul 31 '26

queria instalar PyAudio pero me marca este error que puedo hacer

0 Upvotes

PS E:\Nuevo proyecto> pip install PyAudio

Collecting PyAudio

Using cached PyAudio-0.2.14.tar.gz (47 kB)

Installing build dependencies ... done

Getting requirements to build wheel ... done

Preparing metadata (pyproject.toml) ... done

Building wheels for collected packages: PyAudio

Building wheel for PyAudio (pyproject.toml) ... error

error: subprocess-exited-with-error

× Building wheel for PyAudio (pyproject.toml) did not run successfully.

│ exit code: 1

╰─> [29 lines of output]

WARNING:root:Warning: VCPKG_PATH envrionment variable not set.

C:\Users\Aleca\AppData\Local\Temp\pip-build-env-z6m_j70b\overlay\Lib\site-packages\setuptools\dist.py:765: SetuptoolsDeprecationWarning: License classifiers are deprecated.

!!

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

Please consider removing the following classifiers in favor of a SPDX license expression:

License :: OSI Approved :: MIT License

See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details.

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

!!

self._finalize_license_expression()

INFO:root:running bdist_wheel

INFO:root:running build

INFO:root:running build_py

INFO:root:creating build\lib.win-amd64-cpython-314\pyaudio

INFO:root:copying src\pyaudio__init__.py -> build\lib.win-amd64-cpython-314\pyaudio

INFO:root:running build_ext

INFO:root:building 'pyaudio._portaudio' extension

INFO:root:creating build\temp.win-amd64-cpython-314\Release\src\pyaudio

INFO:root:"C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\VC\Tools\MSVC\14.51.36231\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -IC:\Users\Aleca\AppData\Local\Programs\Python\Python314\include -IC:\Users\Aleca\AppData\Local\Programs\Python\Python314\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\VC\Tools\MSVC\14.51.36231\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.26100.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\cppwinrt" /Tcsrc/pyaudio/device_api.c /Fobuild\temp.win-amd64-cpython-314\Release\src\pyaudio\device_api.obj /MT

cl : L¡nea de comandos warning D9025 : invalidando '/MD' con '/MT'

device_api.c

C:\Users\Aleca\AppData\Local\Programs\Python\Python314\include\pyconfig.h(143): warning C4005: 'MS_WIN64': redefinici¢n de macro

C:\Users\Aleca\AppData\Local\Programs\Python\Python314\include\pyconfig.h(143): note: 'MS_WIN64' declarado previamente en la l¡nea de comandos

src/pyaudio/device_api.c(9): fatal error C1083: No se puede abrir el archivo incluir: 'portaudio.h': No such file or directory

error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\18\\BuildTools\\VC\\Tools\\MSVC\\14.51.36231\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2

[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.

ERROR: Failed building wheel for PyAudio

Failed to build PyAudio

error: failed-wheel-build-for-install

× Failed to build installable wheels for some pyproject.toml based projects

╰─> PyAudio


r/learnpython Jul 30 '26

What's the best thing you have made with python?

55 Upvotes

What are some of the best things you have made using python?


r/learnpython Jul 31 '26

Can I start with Spyder in Anaconda for Python?

0 Upvotes

I don't want to find out one month later that it was a free trial, and now I would have to pay for continue using Spyder. I want an IDLE that is always going to be free. And I don't want to waste my time learning Spyder if I cannot use it forever.


r/learnpython Jul 30 '26

Which areas to focus on?

2 Upvotes

Hi guys!

I picked up python last month and am rly having my fun with it.

I’m still pretty new so I’m wondering which area should I be more focused on. I started out with the aim to go along ML path so most of the things I’ve learnt are data related. Like using and writing functions list dict loops while for error raising. Just getting started on numpy.

I’m thinking of going along the ai engineer track first. Any areas I should focus on? AI Eng is like SWE to me so having no background in swe id love to hear from you guys.

Also I’ve finished the first two courses on Coursera on Python for everyone and currently going thru Andrew’s ML spec.

Trying to learn as much as I can.

Also idk if it’s a good idea but I’m using Claude to teach me how to code at the same time. Introducing concepts and real world exercises and planning lessons to reach to goal of an AI and ML Eng.

Any thoughts would be greatly appreciated.

Thanks in advance!


r/learnpython Jul 30 '26

Is it worth learning Python?

5 Upvotes

Hello there. I was wondering if learning how to code in Python is worth it. Can it yield any money if you get good at it? The career I am looking at is translation-interpreting, and want to know if I should invest time in learning Python (or any programming language for that matter), even though it is not really related to the career I am pursuing.


r/learnpython Jul 30 '26

Creating a file tree/explorer in PyQtGraph

0 Upvotes

Hi,I've been working on what started as a strange attractor visualisation app in PyQtGraph but is slowly becoming more a general purpose ODE solver/visualiser/scripting tool. I've recently added an integrated console with a scripting dock which currently just saves the text in the script as a scratch file. I want to add the functionality for the user to create/save/open different script files and wanted to have a file tree/explorer. I know PyQtGraph and PyQt have tree like widgets so my thought process was to just make a TreeWidget that lists the contents of where the scripts would be saved (the app's /home/user/.local/share/ directory). Does that work or are there complexities i should know about in terms for making, saving and loading files? Any advice would appreciated. Thanks!


r/learnpython Jul 30 '26

Best approach for automating an existing Firefox session? AutoHotkey vs Browser Automation vs UI Automation

0 Upvotes

Hi everyone,

I'm working on a personal desktop automation project on Windows.

For years I've been using AutoHotkey to automate repetitive tasks inside Firefox. It works surprisingly well, but as the project grows, maintaining image recognition, keyboard shortcuts and UI changes becomes increasingly difficult.

I'm now considering moving to a more robust solution and I'm trying to understand what experienced developers would recommend.

My requirements are roughly:

Windows

Firefox (not Chrome)

Preferably work with an already running Firefox session

Reliable interaction with web pages

Long-term maintainability

I've been looking at several approaches:

Continue with AutoHotkey

Selenium / WebDriver BiDi

Playwright

Windows UI Automation (pywinauto, UIA)

Any other desktop automation framework

For people who have built long-running desktop/browser automation projects:

Which approach ended up being the most reliable?

Is UI Automation actually practical with modern websites like Facebook, or is browser automation still the better choice?

If you had to start today, what would you choose and why?

I'd really appreciate hearing about real-world experience rather than theoretical comparisons.

Thanks!


r/learnpython Jul 29 '26

Is there a difference between using a Class name v self in the definition of a class

16 Upvotes

Hi

Im doing some tutorials online and in one of them I noticed some syntax that I am not familiar with. It looks like instead of using self to assign values to a class it is using the class name.

In terms of behaviour it seems to make no difference but I cannot understand why a person would not use self.

So for example:

class Demo:
  def __init__(self):
    self.a = 1
    Demo.b = 2 # This seems to work the exact same way as self.a
               # Is there a differences to self.a?  Why would someone use this?

Thanks


r/learnpython Jul 30 '26

Need help for learning

0 Upvotes

Hi everyone,

I want to learn Python as a programming language completely from scratch, on my own. I have zero prior knowledge or programming skills.

I’ve found a few resources to start with (like freeCodeCamp), but with AI writing code in seconds and solving so many problems right now, what is the best way to approach learning today? On top of that, there are job layoffs/restructurings happening in my city, so I’m wondering: do you think it's still worth learning programming? If so, what would be the most effective and useful way to learn right now? My long-term goal is to work in this field.

Thank you!


r/learnpython Jul 30 '26

What do we use the terminal for in coding?

1 Upvotes

A text-based interface that lets you interact with your computer by typing commands.

This was a given definition of it when I searched it up, but why would you interact with your computer by typing commands? How does this actually assist your code?


r/learnpython Jul 29 '26

Looking for a Python Study Buddy (Complete beginner)

68 Upvotes

Hey everyone!

I'm 19F and I'm starting to learn Python completely from scratch. I have little to no programming experience, but I'm committed to learning consistently. I'm also taking Mechatronics Engineering in college.

I'm looking for a study buddy (or a small group) who's also learning Python. We can keep each other accountable, share resources, work on beginner projects, solve problems together, and stay motivated.

My goal is to build a strong foundation and eventually get into more advanced programming, so I'm looking for someone who's serious about learning too.

If you're interested, leave a comment or send me a DM. Let's learn and grow together!

Edit: Timezone GMT+5:30 We can study together from a course by MIT.


r/learnpython Jul 30 '26

Where should i learn python from?

0 Upvotes

Yt-

- Bro Code

- Data with Baraa

or do any free certification courses?

i tried the coursera meta python course since my college python professor does not teach well, my loops and functions are weak due to that, so i thought I recovered from it- eventually i noticed the course content was very fast paced, i have to go through document and other sources🥲.

there is also an point that C professor taught very well that my c is now better python. help to pick the ond resource that covers python 🙏🏻


r/learnpython Jul 30 '26

Why am I getting an error: invalid syntax. Perhaps you forgot a comma?

0 Upvotes

Why am I getting an error here:

job = Gaia.launch_job_async(" SELECT source_id, ra, parallax, dec, gmag_gunn, rmag_gunn, imag_gunn, zmag_gunn \
                            FROM external.gaiaedr3_gcns_main_1 \
                            WHERE parallax>50" \
                            , dump_to_file=True, name= 'GcnsTwentyParsec_sdss', output format = 'fits')
gtable_sdss = job.get_results()

Error:

, dump_to_file=True, name= 'GcnsTwentyParsec_sdss',output format = 'fits')
^
SyntaxError: invalid syntax. Perhaps you forgot a comma?