r/learnpython • • 1d 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 • • 5h ago

Learning Python at 37 and I can read code fine but can't write 10 lines without the lesson open

64 Upvotes

37, learning Python in the evenings for about 3 months. I can read other people's code and follow every lesson, but the moment I close the lesson and try to write something small on my own, like a script to rename my photos, I'm stuck after a few lines. I did a free intro course before this and hit the same wall, so this time I'm paying for something structured. What made writing code on your own start to click?


r/learnpython • • 4h ago

Basically, if main

5 Upvotes

In Python, when you run your program in another folder, we add this, but I don't understand why. What's the point of doing this? If someone could explain it in a simplified way, I'd appreciate it.


r/learnpython • • 17h ago

What exactly is uv? Why other programming languages like C++ doesn't needs it

30 Upvotes

Hello, im a c++ programmer and after installing some tools made in python with pipx. For context, pipx uses uv, i had this question. I'm not the smartest progammer on earth and i couldn't understand why Python needs a separate environment for dependencies.

I never such tool like that as a c++ programmer (i don't know if it's what im thinking, but in C++ some devs install the dependencies inside de project dir so u just "cmake" it. uv is like this?). I'm kinda new to programming, so if someone can explain it to me, i'd be very grateful!

Sorry if this question sounds too beginner. I really couldn't understand this tool and curiosity is stronger than me...

Thanks! (and also, uv does more than separating environments, right?)


r/learnpython • • 12m ago

EOF when writing code for list

0 Upvotes

I appreciate the help I get on here, and I have an issue I was not taught of to fix. When I write the following code I get an error saying "EOF when reading a line" and I really dont know why. This is the code:

num_raw = int(input())

raw_list = []

i = 0

while i <= (num_raw - 1):

raw = input()

raw_list.append(raw)

i = i +1

print(raw_list)

The task says that the first input would follow how many inputs come next, and then to make a list.

I would assume the raw variable would become the input and then add the variable to the list, and do this as many times that exist from the first input. But no matter how I write it "raw = input()" comes up with EOF. Can someone tell me what i am missing?
please and thank you


r/learnpython • • 55m ago

Куда сейчас лучше всего идти в айти, что хорошо оплачивается.Сейчас учу пайтон, планирую потом отдать себя в кибербезопасность, хорошая ли идея?

0 Upvotes

.


r/learnpython • • 2h ago

On preventing the propagation of floating point error

1 Upvotes

TL:DR: how large is the floating point error on an mpmath float compared to the last exact significant digit?

I'm working on a program to calculate the value of various iterated maps.

The problem I was running into was, let's take, for the sake of simplicity a 2x mod 1 map with starting value at 0.4, after just a few iterations the values would deviate from the 0.4, 0.8, 0.6, 0.2, 0.4... cycle due to the spread of floating point error.

Now, I'm saving my data in a hdf5 file which uses numpy float64, which is more than acceptable for my use case as it gives me precision up to the 15th significant figure, so long as the overall behavior of the map is within that margin.

My solution to this was, working with mpmath, to take the input for the starting value as a string, calculate the value for the next iteration after converting in to an mpf, and then to run that into this function:

import mpmath as mp

def floaterrorfix (f):
    return mp.mpf (mp.nstr (f, int (mp.floor (mp.mp.prec * mp.log (2, 10)))))

Using an user submitted number of bits for the precision, also given that the number of digits of precision afforded by a float with b bites of mantissa is d = b*log_10(2), it basically removes the propagated error from the previous iteration and leaves me with the regular error for whatever the value/the number of bits used for storing was.

Now, I haven't noticed any error propagation while running maps for which I know the values (mainly cyclic ones) even millions of iterations in, but I think it should still be possible to get some, especially with more complex maps that involve more calculations per iteration (eg a standard map), all that is needed is for the error pre-iteration to be large enough to exceed into my supposedly "exact" figures after I apply the calculations and, given that I'd be running off of randomised start values and parameters I'd have no way to check if that was the case.

My solution to this would be getting the number of significant digits from the user input (or the 15 for standard float64 in case it has less than that) and set the precision so that, even the largest possible float error, will not exceed into those digits after I apply all calculations; this would also save me that pesky user submitted number of bits.

Before I do all that tho I want to make sure it's actually possible for the error to still propagate or if there are already checks in place within python/mpmath that would prevent this for any reasonable calculation and what the limit on that would be, also if I do need to apply my solution, I was unable to find a way to easily count the number of significant figures on a number stored in a string.


r/learnpython • • 2h ago

Stuck at Helsinki mooc.fi exercise

0 Upvotes

I have been doing one of the exercises in the mooc fi course : https://programming-26.mooc.fi

Specifically part 3 (working with strings - 15, the last one in that section), here's the question : https://programming-26.mooc.fi/part-3/2-working-with-strings#programming-exercise-the-second-occurrence

but sadly been days and couldn't get what's wrong with my solution, here it's as well : https://pastebin.com/kmHf6jjm

I tried to check for their discord server at :

https://programming-26.mooc.fi/support-and-assistance

But it keeps redirecting me to student of helsinki's login portal asking for a uni account, is the discord server public or restricted to those who attend the Helsinki University....or maybe I am missing something out

would appreciate the help whether for solving it or for how to access the discord server (or shedding some light on if it's accessible or not)

thanks in advance


r/learnpython • • 14h ago

why use assert instead of if something false then raise some error with custom error message

5 Upvotes

what are the benifits of assert. because it seems that it doesn't save time nor effort, nor does it communicate code better than an if with custom error message


r/learnpython • • 15h ago

`is` vs `==` in Python: why does `a is b` sometimes work on numbers and then break?

3 Upvotes
I was going through basic Python interview questions this week and this one keeps tripping people up, me included when I first learned it.


```python
a = 256
b = 256
print(a is b)   # True


x = 1000
y = 1000
print(x is y)   # often False when run as separate statements
print(x == y)   # True
```


What I understand so far: `==` asks "do these two have the same value?" and `is` asks "are these literally the same object in memory?" CPython caches small ints (-5 to 256), so those happen to share one object. Bigger numbers can be separate objects, so `is` gives False even though the values match.


So the rule I follow now: `==` for values, `is` only for `None` (`if x is None`).


Is there any other case where you'd actually reach for `is`? Or any gotcha I'm missing, like string interning? Not sure I fully get that part.

r/learnpython • • 10h ago

Made a small pandas library for Malaysian stock data, would love feedbacks

0 Upvotes

It's called bursakit.

It pulls Bursa Malaysia stock prices and dividends, plusBank Negara's interest rate and exchange rates, straight into pandas.

import bursakit as bk

df = bk.prices("MAYBANK", start="2024-01-01")

It caches everything in SQLite, so the second call is instant.

Built it with some AI help, but I've gone through all the code myself.

Mainly wondering:

- Is the structure overkill for something this small?

- Does the cache logic make sense?

Heads up: the stock data comes from yfinance, so it's unofficial and for personal use only.

https://github.com/MaosterM/bursakit


r/learnpython • • 11h ago

I dont know whats different between these two functions

1 Upvotes

Im doing a course called building ai where were now working with probabilities. I thought it would be very simple but for some reason only the code that i find on github actually goes through the in-built authorizer.

The exercise wants me to ”write a program that prints ”i love” followed by one word: the additional word should be ’dogs’ with 80% probability, ’cats’ with 10% probability, and ’bats’ with 10% probability.”

Heres my code
import random

def main():
dogs = 0.80
cats = 0.90
bats = 1.00
if random.random() < dogs:
favourite = "dogs" # change this
elif random.random() < cats:
favourite = "cats" # change this
else:
favourite = "bats" # change this

print("I love " + favourite)

main()

The authorizer tells me im printing too many cats. Ive tried changing the comparisons to <= to make cats less probable but without any luck

Heres an example code i found on github through this link
https://github.com/Qianqianxia0910/Building-AI/blob/main/Exercise%204-%20Probabilities.py

import random

def main():
prob = 0.10

if random.random() < prob:
favourite = "bats"
elif random.random() >= (1-prob):
favourite = "cats"
else:
favourite = "dogs"

print("I love " + favourite)

main()

This code goes through flawlessly while in my eyes doing basically the same thing. Any explanation on what could be systematically different between these functions would be nice. Ive gone forward with the course but im just mighty curious on what might be different between these functions


r/learnpython • • 1d ago

i don't feel like i'm learning anything in Python. How do I actually get good?

4 Upvotes

i've been "learning" python for a few years. started when i was younger, parents made me do classes, i barely practiced so i remembered nothing. did classes again, same thing. now i'm doing classes again (codingal) but this time i'm actually trying to practice.

i've done the basics, loops, functions, oop, then tkinter and pygame in class. i don't remember most of it. i taught myself numpy and i kinda get it.

my class is going into ml now like stuff like : pandas, sql, stats, then regression, decision trees, clustering, neural networks with keras/tensorflow. i want to actually be good at this, not just copy code.

the problem is i can't build anything on my own. i've made an rpg and a numpy grade analyzer but only with ai helping me. i tried tic tac toe and got stuck partway. when i sit down with a blank file i just don't know what to do first, so i end up searching it up or asking ai. i feel like i can't think for myself.

i practice about 1-2 hrs a week (1 hr is class). now trying to do 3-5 on top of school and sports.

also, i build websites for small businesses on the side. i know basic html/css, but ai writes most of the code. is it worth learning web dev properly, or is ai good enough at that now that i should just focus on python/ml? and how do i get better at web design and develop good taste? i can build stuff but i can't always tell why one design looks better than another.

what's the best way to get from "i know the syntax" to "i can actually build stuff"? should i go back and redo pygame/tkinter or just push on into ml? any advice on what to do when you're staring at a blank file? Thank you very much 🙏


r/learnpython • • 1d ago

String split and single quotation marks

7 Upvotes

I'm currently doing the Finnish Python MOOC, and at the end of chapter 4 you're not quite introduced to the split function. The problem is simple: your input a is string containing two integers, and this string must be split into two different lists, repeating for every new input string. However, the lists contain every integer within single quotation marks, which makes them unusable for mathematical operations. Am I supposed to just add another line to convert the lists into something useful? Seems really convoluted.

(And, if someone would be so kind, why does Python do this thing with the quotation marks?)

#In short, I have this:
input_string = 12 33
input_string.split()
list_a = ['12']
list_b = ['33']

#While I need this:
list_a = [12]
list_b = [33]

#So I do this:
a_no_quotes = []
for item in list_a:
    a_no_quotes.append(int(item))

r/learnpython • • 1d ago

2 Years of Experience in SQL, SSIS & Excel – What Skills Should I Learn Next to Grow My Career?

20 Upvotes

Hi everyone!

I have around 2 years of experience working with SQL, SSIS, and Excel, mainly focusing on data validation, identifying and resolving data errors, and developing SQL queries.

I'm planning to upgrade my skills and currently interested in learning:

  • Python
  • FastAPI
  • Ollama and AI chatbot development
  • Generative AI and LLMs

What technologies would you recommend to improve my career? Should I focus on Data Engineering, Backend Development, or AI?

Also, if anyone has doubts related to SQL queries, SSIS, data errors, or Excel validation, feel free to reach out. I'll be happy to help wherever I can and learn together!

Looking forward to your suggestions. Thanks!


r/learnpython • • 1d ago

matplotlib graphs from csv file

3 Upvotes

hi! i dont rly use reddit but i need some help. does anyone know how to make matplotlib graphs from a csv file? i can do the basics but i cant seem to figure out this dataset, and i need to submit my project soon. any and all help is appreciated


r/learnpython • • 1d ago

Terminal Access?

4 Upvotes

Hi, I am using Python with Jupyter Notebooks on MacBook. Is it possible to perform tasks you would normally do in the terminal within python. In my explicit case, I want to use SExtractor (Source extractor that finds light sources in image...) and then perform calculations with the created source table. But SExtractor does not have a visual interface and just works via inputs in the terminal. Is it possible to perform those taks within a python script if you know what I mean?


r/learnpython • • 1d ago

Python and Health Area

12 Upvotes

I´m a Pharmacist (working for the goverment) and thinking seriously to learn some data science, including Python, to get better functions.

Do you think that the union of these 2 areas is something promissing that may offer me oppotunities or not?


r/learnpython • • 2d ago

Efficiency practice for daily python training

19 Upvotes

My goal is to become fluent with Python programming in every shape and form it has to offer. I am nearing the end of my intro to Python class and also use Coddytech.com the end goal is AI automation.

I’d like to know how to truly practice and build programs daily so that I am more hands on and can start laying a true foundation for myself instead of just learning the fundamentals and still using ai to help me write code.

What’s some advice an expert can give me and others in my situation?


r/learnpython • • 2d ago

strings in if statements

13 Upvotes

While debugging my code I discovered [what to me looked liked] a weird quirk in the language (see code below.)

Why does this work? why is a single string callable in the Boolean of an if statement? does a string always return evaluateTrue when used like this?

(edit: solved. corrected some of my vocabulary so now yous can stop "um, actually"-ing me. Thanks to everyone who helped!)

if "something":
  print("another thing")

>>>"another thing"

r/learnpython • • 2d ago

After a while of learning programming

7 Upvotes

So I am stuck in tutorial hell for a long while and I had to realize that I have no idea what a program’s code looks like so I can’t compare myself from it and can’t learn from it. And tutorials don’t give practice lessons for some reason.


r/learnpython • • 2d ago

Learning code and programming

10 Upvotes

Im on a gap year and totally new to coding im based in the UK so i have not done any comp sci GCSE or A-Level and im struggling to learn. I tried the Harvard lectures but I couldn't understand what he was saying and the input he would put in wouldn't make sense to me. Im bored in my gap year and want to pick up a new skill any help or advice would be appreciated.


r/learnpython • • 2d ago

Need feedback

3 Upvotes

I made my first big python project as a beginner high school student. It visualizes CO2 emission trends and compares with countries and compares gdp, population and other stuff. It uses matplotlib, numpy, seaborn, streamlit and pandas.
link: https://github.com/rapanjeetsingh/python-project


r/learnpython • • 2d ago

I struggle with math and abstract thinking. Is DSA realistic for me, and is data engineering a viable path?

5 Upvotes

Hi everyone,

I'm a beginner in Python and I'd really appreciate some honest advice from people with more experience.

My background

  • Python level: I know the basics (variables, loops, functions, lists and dictionaries), but I'm still learning how to write programs on my own.
  • Time I can study: About 1 to 2 hours a day.
  • Goal: Get a job in tech, possibly as a data engineer.
  • Math: I've always been weak at it, and I often feel I'm not great at logical or abstract thinking.

My concern
I'll be honest: I'm not good at math, and my logical thinking is weak. In school I struggled with math, and I often get stuck when a problem requires me to break it down step by step. Whenever I read about data structures and algorithms, I worry that these weaknesses will hold me back. I don't want to spend months studying only to find out I was on the wrong path. At the same time, I'm willing to put in consistent effort if there's a realistic way forward.

My questions

  1. Is DSA realistic for someone who is weak at math? Is it mostly about practice and pattern recognition rather than natural talent?
  2. How much DSA does a data engineer actually need in real work and in job interviews? Are the basics (lists, dicts, sets, stacks, queues) enough, or do I need trees, graphs and dynamic programming too?
  3. What is a sensible learning order? I was thinking: arrays/strings → hash maps → stacks/queues → linked lists → trees → graphs. Does that make sense?
  4. Which resources worked for you? I've looked at VisuAlgo, NeetCode, CS50 and Grokking Algorithms, but I'm not sure how to combine them.
  5. Should I learn SQL alongside Python from the start, given that I'm interested in data engineering?

What I've tried so far
I've followed some beginner Python tutorials and practiced small exercises, but I often get stuck when I have to solve a problem on my own, and that makes me doubt myself. I haven't started DSA yet because I'm not sure where to begin.

If you were in my position, what would you focus on first? Any advice, roadmap, or personal experience (especially from people who also struggled with math) would mean a lot.

Thank you for reading!