-1

I am very new to Python and I'm trying to make a function so that when I call it, it assigns something to a variable. I don't know how to explain it better but this is what i got now:

again = '0'
def printa():
    print(again)
def f1():
    again = '1'
def f2():
    again = '2'
x = input()
x = str(x)
if x == '8':
    f1()
elif x == '9':
    f2()
printa()

My objective is that when I write 8 the output is 1 and when I write 9 the output is 2; and right now the output is always 0. I know I could just write if x == 8 print 1 but I need to use functions

William Baker Morrison
  • 1,642
  • 4
  • 21
  • 33
  • 1
    "I need to use functions" Is this some exercise you need to solve? If yes, adding the precise requirements might help. – MisterMiyagi Jan 24 '21 at 16:03
  • Just to be clear: You want ``again = '1'`` inside ``f1`` to change the value of the *global* variable ``again``? – MisterMiyagi Jan 24 '21 at 16:04
  • I'm making a GUI for a rock paper scissors game that I made, and I'm learning to use tkinter for that (I just started to learn today so I dont know much), and I need that when a press a button on the screen it assign a value to a variable, and using the global keyword that gesuchter and roman suggested I got it working – Henrique Fernandes Jan 24 '21 at 16:44

3 Answers3

1

Since you want to modify the variable again inside of f1() and f2() you would have to use the (mostly unrecommended) global keyword. You have to do this, because again is out of scope for the functions (Python: Why is global needed only on assignment and not on reads?).

again = '0'

def printa():
    print(again)
    
def f1():
    global again
    again = '1'
    
def f2():
    global again
    again = '2'
    
x = input()
if x == '8':
    f1()
elif x == '9':
    f2()
    
printa()

Notice that you do not need to convert x to a string since input() will do this automatically.

However, a better approach would be to use a function which takes an argument:

def printa(arg):
    if arg == '8':
        print('1')
    elif arg == '9':
        print('2')
    else:
        print(arg)
    
x = input()
printa(x)
```
Gesuchter
  • 541
  • 5
  • 13
0

Set again variable as global if you want to change global var value from function

def f1():
    global again
    again = '1'
def f2():
    global again
    again = '2'

But may be it would be better to change logic

0

You could also do this:

def func():
  x = str(input())
  if x == '9':
    return '1'
  elif x == '8':
    return '2'
  else:
    print("'9' or '8' not entered")


func() # To call the function
William Baker Morrison
  • 1,642
  • 4
  • 21
  • 33