Global variable does not change the value

Asked

Viewed 67 times

0

I’m a beginner and I don’t know why this code doesn’t work. Can someone tell me why?

def teste():    
    global res1
    res1 = input().strip()

if res1 == '1':
    print('funciona')
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

3

The biggest reason is that you declared the function but did not call it, so it is not executed and nothing happens. So it works:

def teste():    
    global res1
    res1 = input().strip()
 
teste()
if res1 == '1':
    print('funciona')

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I do not guarantee that data entry may be causing some other problem as well.

But I’ll give you some tips to produce better code.

The first tip is not to use global to master all the rest of Python programming and structures. This is problematic and useful in rare cases. It takes a lot of experience to do it right. It works in this simple case, but it will teach you wrong. Learn to use functions the right way, passing arguments and receiving data as a return.

Give meaningful names for functions and variables, so the code becomes more explanatory.

Only use a function if it’s really necessary. Not in code like this. If you want to learn how to use function look for a problem that needs a function. Not that you can’t use it, but anyway if you’re gonna use it then use it the right way.

For a first example you can even make it simple, but any typed data should be validated. And I don’t know why this strip(), He just complicates what he’s doing and he doesn’t seem to have much motive. If you have a reason, try it another way, it’s more likely to go wrong. I’m not talking about validating now, because it won’t cause such a big problem, but in real cases you’ll need to do it. And just because it’s too simple doesn’t make sense strip().

So it looks better, though not perfect:

def pede_dados():    
    return input()
 
if pede_dados() == '1':
    print('funciona')

Even better:

if input() == '1':
    print('funciona')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.