Ad
User Input-based If Statement Gives Unexpected Output
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 :
weapon_choice
don't need to be cast intostr
format asinput()
will be already in string formatting.- Whenever you do
input(1)
orinput(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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad