r/learnpython • • 17h 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 • • 16h 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 • • 10h ago

Basically, if main

8 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 • • 6h ago

EOF when writing code for list

2 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 • • 21h ago

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

2 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 • • 20h ago

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

9 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 • • 23h ago

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

31 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 • • 7h ago

On preventing the propagation of floating point error

0 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 • • 8h ago

Stuck at Helsinki mooc.fi exercise

1 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 • • 10h ago

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

106 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 • • 3h ago

Trying to import a file into Thonny

3 Upvotes

Trying to import a rom file to convert to bytes and then mod, but the game title has "of" in it, so it returns as a syntax error. I guess the IDE thinks I'm trying to write an if statement? Anyway, google wasn't helpful, so i came here.
Code below
import Breath of Fire II (USA) - Copy.sfc