Hello guys ! I am just a beginner in Python language and tried to make a program that could add some numbers to variables, the thing is that my program doesn't work and gives me back the values I've set at te beginning, could anyone tell me what is wrong with my program ? I've been looking for solution for almost an hour but can't manage to find one.. :')
#🔒 Made a program that doesn't work
102 messages · Page 1 of 1 (latest)
@hushed grotto
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Closes after a period of inactivity, or when you send !close.
Oh I'll do what the message says
== is to compare two things. = is assignment. Your IDE was warning you about that with the yellow lines.
and if they're global values, I think you gotta put a global <stuff> at the beggining
Yeah that's what I thought but when I put =, it tells me that the variable "perception" for example, isn't existing
Although, they're returning the values, so it's probably best to keep them local.
How can I know if they're global values ?
global is a variable defined outside of any functions
Oh, nvm, they're using the old values for the calculation.
a function cannot assign to a global variable
yeah
So ya, they need to be marked as globals, or added as parameters.
or having that many parameters, you may consider clapping everythin into a class
When I put = the error message says "'<stuff>' referenced before assignment"
How can I do that ?
when a function assigns to a variables, it is a "local" variable
Ya, depends on if they're related enough. They look like they'd be appropriate as a "Stats" dataclass.
x = 10
def foo():
x = 5
these are two different x variables
there's a global, and a local
Okay
Oh
!e
x = 10
def foo():
x = 5
print(x)
foo()
@sleek heart :white_check_mark: Your 3.12 eval job has completed with return code 0.
5
@sleek heart :white_check_mark: Your 3.12 eval job has completed with return code 0.
10
if a function tries to print a global variable, it can, but only if it doesn't have a local variable of the same name
it just can't reassign to a global variable
!e
x = 10
def foo():
print(x)
x = 5
foo()
@sleek heart :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 7, in <module>
003 | foo()
004 | File "/home/main.py", line 4, in foo
005 | print(x)
006 | ^
007 | UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
notice what this error is saying
the function knows that x will be assigned later in the function
so it assumes any reference to x will be local x
for them to be related, you gotta clap a global at the start
x = 10
def foo():
x = 5
print(x) # 5
foo()
print(x) # 10
or
x = 10
def foo():
global x
x = 5
print(x) # 5
foo()
print(x) # 5
that being said, global is generally bad practice and should be avoided if possible
so that global keyword is telling python x means the global variable no the local variable
so just ignore all that and clap everything into a class to have your variables organized
yup, class would be the best way to structure this, but it's generally advanced for a beginner
a class is a way of structuring data, so you have
class Vehicle:
def __init__(self, name:str):
self.name = name # you set the attribute `name` to the name given
this_is_a_vehicle = Vehicle('toyota')
this_is_a_vehicle.name # toyota
with that you can structure your data
you want me to break that down for you?
Yes if you don't mind
Ok, a class, as we said is a way of structuring data, using it's attributes
think for example of a Woman, each woman has an age, so age is a property of Woman
so you don't have
maria_age = 30
maria_name = 'maria'
maria_job = 'cashier'
...
andrea_age = 26
...
``` but
```py
maria = Woman(age = 30, name = 'maria', job = 'cashier',)
andrea = Woman(age = 26, ...)
and with that you have each of maria's attributes in maria instead of working with them separatedly
Yes
classes also inherit properties, for example, each woman is a person ¿right? so Woman inherits from Person
I won't go into detail because that's useless for you right now, but just keep that in mind because that's the basis of OOP (Object Oriented Programming)
the way you declare this, is you say
# we create the class `Woman`
class Woman(Person): # Woman inherits from person
# this weird method is called each time a new `Woman` is created
# it's job is to initialize the data in the class
# it's given `self` which is the Woman object itself and all the parameters
# the new Woman was created with
def __init__(self, age, name, job):
# self.age = age means we're setting the `age` of this woman object
# to be whatever we passed as parameter, and this repeats
self.age = age
self.name = name
self.job = job
# you can add further logic, as this is a method like any other
self.is_under_age = False
if age < 18:
self.is_under_age = True
# and then you can just use it
maria = Woman(age = 26, 'maria','cashier')
maria.is_under_age # False
maria.age # 26
...
so in your case, the way of doing this would be
class IDontReallyKnowExactlyWhatYourDoing: # if it doesnt inherit just do it like this
def __init__(self):
self.perception = self.instinct = self.cleverness = self.luck = 0 # set all to 0 at once
def preset(response, something):
if response == 1:
something.perception += 6
something.instinct += 13
something.cleverness += 8
something.luck += 7
if response == 2:
...
return # no need to return anything
... # your code that I won't copy
something = IDontReallyKnowExactlyWhatYourDoing()
print(stress(1, something))
you kind of get where I'm going?
Yeah I think I get it
do I HAVE to put the something = <name of my thing> at the end ?
Like, how is it important in the program ?
the word is instanciate, when you create an object from a class it's called instanciating
it's initializing your data
the class was structurizing your data
making it more readable
and also, when you learn what methods are, telling python what it can do or it cannot do with that data
Hmhm
a class is more like a blueprint. It's a collection of data and behaviours. We need to create an "instance" of our class to work with it
do you know what str and int are?
No, I don't
when you're putting
something = YourClassName()
is when you're filling in that 'blueprint' (good metaphor)
this class stuff might be a bit too advanced for now
if you haven't learned basic datatypes
int and str probably are, and so are methods, but I think he may have understood the data structurizing part
int and str are typically some of the earliest stuff beginners learn
so if they don't know that, we can assume they're quite new
but they're not easy to understand
int and str are quite easy to understand...
he knows what a function is
not from the they're classes point of view
they're using a function, that doesn't mean they necessarily know what it is
this could be chatgpt code for all we know
No, but in a way you can relate instantiation
who's gonna tell this poor man that in maria = Woman(name = 'maria') woman is the same to maria than 15 is to int?
I don't like to think that dirty of people
if you think this is too advanced, @hushed grotto , just use global, since you're a begginer you're not going to have that much problem with it
There's no judgement, I just try and get a read on people's skill level to give fitting help, but if their code doesn't match what they say they know, I try and ask followup questions
we don't know what he knows, for all we know he could be studying recursion and know nothing about int or str
Well I know how to use functions but I've only had like 4 hours of python practice so I'm a beginner and I don't know anything about int or str
if someone doesn't understand function scope, it's a pretty good indicator that they're too beginner for classes
I've studied it in class and wanted to go a litlle deeper to make the program I had in mind
int means integer, if something is an int in python is a whole number
then you sure should
str comes from string, if something is an str in python means it's an string or text for normal people
so when you're doing something like
print("Hello World")
you're creating an string with the text Hello World and passing it to print
the diference between str and Woman is that python has already predefined str so you don't have to
str also has the advantage of literals for instantiation
for class Woman, we have to make a new instance by using the class name
Woman()
for a string, we don't have to type str()
make a class or use global to solve your issue, and take this as a recomendation, coding is fun, you'll suffer like hell when Python simply does whatever it wants, but once you get it done, it'll be worth it
Well thanks to the 2 of you !!
If I manage to make my program work, I'll tell you, thanks for your time, hope to chat with you later !!
send me a private message, I'll help you with any other proyects you have so that you can keep on coding, because this channel won't be here forever
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.