为了账号安全,请及时绑定邮箱和手机立即绑定

基于用户输入的 if 语句给出了意外的输出

基于用户输入的 if 语句给出了意外的输出

POPMUISE 2022-06-02 14:34:36
我正在制作一个基于文本的小游戏来练习我的 Python 技能。我正在努力让 if 语句根据我的用户输入显示正确的结果。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")我希望输出会询问我一个数字(1、2 或 3),然后打印与该数字关联的字符串。相反,当我输入 1 时,它会打印 1,然后是 2,然后是与数字 3 关联的字符串('else' 选项),无论我输入什么数字。我不明白为什么?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.112You chose the Elven SwordProcess finished with exit code 0
查看完整描述

3 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

尝试这个:


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")

笔记 :


weapon_choice不需要像字符串str格式那样转换成格式。input()

每当你这样做input(1)或input(2)它基本上提示用户提供另一个输入而不是检查条件。

输出 :


michael@arkistarvh:/$ 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


查看完整回答
反对 回复 2022-06-02
?
呼唤远方

TA贡献1856条经验 获得超11个赞

这不是输入在 Python 中的工作方式。

您正确地假设 input("some text") 将在第一行打印该文本(并将结果存储在变量武器选择中),那么您为什么认为 input(number) 会返回一个布尔值,告诉您是否输入的是那个数字?

相反,它所做的是再次打印数字并返回一个空字符串(因为您可能只是按下了 Enter 键),因此前两个 if 为 False,程序进入 else,打印“Invalid input selected”。

您第一次输入的结果将存储在武器选择中,因此您应该对该变量进行比较。


查看完整回答
反对 回复 2022-06-02
?
波斯汪

TA贡献1811条经验 获得超4个赞

您应该改为:


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


if weapon_choice == '1':

    print("You chose the Axe of Might")

elif weapon_choice == '2':

    print("You chose the Sacred Crossbow")

elif weapon_choice == '3':

    print("You chose the Elven Sword")

else:

    print("Invalid input selected")

这样做的原因是input(..)导致字符串被解析,因此不需要str(..)在input(..). 此外,您应该有一个传递无效输入的条件,以便更清楚地通知用户错误的根本原因。


查看完整回答
反对 回复 2022-06-02
  • 3 回答
  • 0 关注
  • 226 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号