Ad

User Input-based If Statement Gives Unexpected Output

- 1 answer

I am making a little text based game to practise my python skills. I am struggling to get the if statement to show the correct result based on what my user inputs.

weapon_choice = str(input("You can choose between three weapons to defeat the beast!"
                   " Press 1 for Axe, 2 for Crossbow, 3 for Sword."))

if input(1):
    print("You chose the Axe of Might")
elif input(2):
    print("You chose the Sacred Crossbow")
else:
    print("You chose the Elven Sword")

I would expect the output to ask me for a number (1, 2, or 3) and then print the string that is associated with that number. Instead, when I input 1, it prints 1, then 2, and then the string associated with number 3 (the 'else' option), regardless of what number I type. I don't understand why?

Greetings, weary wanderer.
Welcome to Freyjaberg. Choose your weapon.
You can choose between three weapons to defeat the beast! Press 1 for Axe, 2 for Crossbow, 3 for Sword.1
1
2
You chose the Elven Sword

Process finished with exit code 0
Ad

Answer

Try this:

weapon_choice = input("You can choose between three weapons to defeat the beast!\nPress 1 for Axe, 2 for Crossbow, 3 for Sword.\n")

if weapon_choice=='1':
    print("You chose the Axe of Might")
elif weapon_choice=='2':
    print("You chose the Sacred Crossbow")
else:
    print("You chose the Elven Sword")

Note :

  1. weapon_choice don't need to be cast into str format as input() will be already in string formatting.
  2. Whenever you do input(1) or input(2) it basically prompts user to give another input in stead of checking with the condition.

Output :

[email protected]:/$ python text_game.py 
You can choose between three weapons to defeat the beast! Press 1 for Axe, 2 for Crossbow, 3 for Sword.
3
You chose the Elven Sword
Ad
source: stackoverflow.com
Ad