0

I am learning python and trying to have a generic way to force people to choose an option. I want to eventually make it more modular so that I can call it with choice(variable) and set choice(chosen). However, I am not doing well with boolean logic and if statements. Or 'return' and 'chosen()' just override for some reason.

Not sure why this will 'return' even if you type 'j' instead of 'left' or 'right' during input.

def choice():
    chosen = input('Do you want to go left or right? (only type left or right):   ').lower()

    chosen == 'left' or 'right'
    if True:
        return chosen
    if False:
        choice()
just a stranger
  • 310
  • 1
  • 4
  • 13
  • 1
    I guess you meant to check `chosen==True`. In conditional statement, the condition 'expression' determines the branching. Here, in `if True`, the condition is always `True`. – DaveIdito Sep 25 '20 at 05:32

2 Answers2

0

first in python == is a compare operator for an assignment operator you would use = instead

chosen = 'left' or 'right'

second 'left' or 'right'

or means logical or not this or that so that statement wouldn't work, you would have to check if the user typed in left or right

chosen = input("enter left or right")  #get input from user

if chosen == "left":
    #do something
elif chosen == "right":
   #do something else

return statements can only be used from within a function otherwise it will return an error

here would be valid code

chosen = input("enter left or right")

if chosen == "right":
    print("wrong answer")
elif chosen == "left":
   choice()
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

you can do like this:

def choice():
    chosen = input('Do you want to go left or right? (only type left or right):').lower()

    #chosen == 'left' or 'right' and this not a value type, if statement doesn't read this
    if (chosen == "left") or (chosen == "right"):#If you type if true, the value true is returned regardless of the value entered.
        print("hello")
        return choice()#if input right or left return choice statement again or you can do other fucntion or nothing
    else:
        print("wrong input")
        return choice()#else ask again

choice()

good luck :)

just a stranger
  • 310
  • 1
  • 4
  • 13