首页 > 解决方案 > Python尝试除了输入

问题描述

我做过小文字游戏,所有关于这个尝试的信息都是一些我不懂的专业语言。我刚开始学习 Python,所以这对我来说并不容易。

我的游戏中有很多输入,例如回答是或否。如果玩家写了别的东西,游戏就会停止工作并出现错误。我必须对此做点什么。我如何使用 try 除了?能不能简单的告诉我。

我的游戏片段:

print('Hello you! Welcome to the Ghetto! What is first name?')
first_name=input()

print('Hello',first_name+'! Now tell me your last name also!')
last_name=input()

print('You are my bailout',first_name,last_name+'! I really need your help here. I lost my wallet last night when i was drunk.') 
print('The problem is i dont wanna go alone there to get it back cause this place is so dangerous. Can you help me? Answer "YES" or "NO"')

lista1 = ['yes','y']
lista2 = ['no','n']

answer1=input().lower()

if answer1 in lista2:
    print('If you are not interested to help me with this problem, go away from here and never come back!!')

    print('*** Game end ***')

if answer1 in lista1:
    print('That is awesome man! You can see that big house huh? There is three apartments and my wallet is in one of them.')

    print('But you have to be god damn careful there you know, these areas is not safe to move especially you are alone. So lets go my friend')

是否有机会获得错误名称输入?是否有一些 Python 不理解的字母或字符?

如果你回答的是或否以外的其他问题,我怎么能用 try 告诉 python 除了再次提出问题?我希望你明白。很抱歉这么长的帖子。

标签: python

解决方案


如果某些原因导致错误,那是在您显示的代码之后......单独使用 input() 应该没有理由尝试 - 除了它,因为任何类型的内容总是被接受为字符串。

如果你想重复输入,你需要一个循环

while True:
    answer1=input().lower()
    if answer1 in ["yes", "y"]:
        print("ok") 
        break 
    elif answer1 in ["no", "n"]:
        print("end")
        break
    else:
        print("try again")

推荐阅读