#🔒 Made a program that doesn't work

102 messages · Page 1 of 1 (latest)

hushed grotto
#

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.. :')

bright portalBOT
#

@hushed grotto

Python help channel opened

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.

hushed grotto
#

Oh I'll do what the message says

sleek heart
#

== is for comparing values

#

= is for assigning values

restive cedar
copper radish
#

and if they're global values, I think you gotta put a global <stuff> at the beggining

hushed grotto
#

Yeah that's what I thought but when I put =, it tells me that the variable "perception" for example, isn't existing

restive cedar
hushed grotto
sleek heart
#

global is a variable defined outside of any functions

restive cedar
#

Oh, nvm, they're using the old values for the calculation.

sleek heart
#

a function cannot assign to a global variable

restive cedar
#

So ya, they need to be marked as globals, or added as parameters.

copper radish
hushed grotto
#

When I put = the error message says "'<stuff>' referenced before assignment"

sleek heart
#

when a function assigns to a variables, it is a "local" variable

restive cedar
#

Ya, depends on if they're related enough. They look like they'd be appropriate as a "Stats" dataclass.

sleek heart
#
x = 10

def foo():
    x = 5
#

these are two different x variables

#

there's a global, and a local

hushed grotto
#

Okay

sleek heart
#

they just happen to have the same name

#

but they are unrelated

hushed grotto
#

Oh

sleek heart
#

!e

x = 10

def foo():
    x = 5
    print(x)

foo()
bright portalBOT
#

@sleek heart :white_check_mark: Your 3.12 eval job has completed with return code 0.

5
sleek heart
#

the local variable will always take priority

#

!e

x = 10

def foo():
    print(x)

foo()
bright portalBOT
#

@sleek heart :white_check_mark: Your 3.12 eval job has completed with return code 0.

10
sleek heart
#

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()
bright portalBOT
#

@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
sleek heart
#

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

copper radish
#

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
sleek heart
#

that being said, global is generally bad practice and should be avoided if possible

copper radish
#

so that global keyword is telling python x means the global variable no the local variable

copper radish
sleek heart
#

yup, class would be the best way to structure this, but it's generally advanced for a beginner

copper radish
#

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?

hushed grotto
#

Yes if you don't mind

copper radish
#

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

hushed grotto
#

Yes

copper radish
#

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?

hushed grotto
#

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 ?

copper radish
copper radish
#

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

hushed grotto
#

Hmhm

sleek heart
#

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?

hushed grotto
#

No, I don't

copper radish
#

when you're putting

something = YourClassName()

is when you're filling in that 'blueprint' (good metaphor)

sleek heart
#

this class stuff might be a bit too advanced for now

#

if you haven't learned basic datatypes

copper radish
sleek heart
#

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

copper radish
sleek heart
#

int and str are quite easy to understand...

copper radish
copper radish
sleek heart
#

they're using a function, that doesn't mean they necessarily know what it is

#

this could be chatgpt code for all we know

sleek heart
copper radish
#

who's gonna tell this poor man that in maria = Woman(name = 'maria') woman is the same to maria than 15 is to int?

copper radish
#

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

sleek heart
#

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

copper radish
hushed grotto
sleek heart
#

if someone doesn't understand function scope, it's a pretty good indicator that they're too beginner for classes

hushed grotto
#

I've studied it in class and wanted to go a litlle deeper to make the program I had in mind

copper radish
copper radish
#

str comes from string, if something is an str in python means it's an string or text for normal people

hushed grotto
#

Oh

#

I didn't know it was called this way

copper radish
#

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

sleek heart
#

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()

copper radish
#

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

hushed grotto
#

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 !!

copper radish
#

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

bright portalBOT
#
Python help channel closed

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.