我正在用python写一些东西,我不明白为什么这部分代码不起作用。
m = 1
f = 0
gender_choice = False
while gender_choice == False:
gender = input('Are you male or female? Type m for male or f for female. ')
if gender == m or gender == f:
print
gender_choice = True
else:
print
print "Hey, this is a text based game. Read and follow bro."
print gender
我想我明白将字符串设置为“m”或“f”存在问题,但除非我将raw_input更改为输入,否则循环将继续。此外,正如当前所写,如果用户输入除数字,m或f以外的任何内容,我将收到一个错误,即字符串未定义,例如,如果它们输入“y”。
答案 0 :(得分:1)
好的,首先检查你的缩进!
这就是我认为你喜欢它的方式:
m = 1
f = 0
gender_choice = False
while gender_choice == False:
gender = input('Are you male or female? Type m for male or f for female. ')
if gender == m or gender == f:
print
gender_choice = True
else:
print
print "Hey, this is a text based game. Read and follow bro."
print gender
然后只有当你的if语句被评估为False时才会执行你的else语句,因为它会评估性别== 1或性别== 0,这只会在你的用户没有“阅读”时才会执行并按照兄弟。“我不知道你的代码后面是否需要m和f变量,但我会假设你这样做,所以我要做的就是:
gender_choice = False
while gender_choice == False:
gender = raw_input('Are you male or female? Type m for male or f for female. ')
if gender == "m":
print
gender_bool = 1
gender_choice = True
elif gender == "f":
print
gender_bool = 0
gender_choice = True
else:
print "\nHey, this is a text based game. Read and follow bro.\n"
print gender
这样你的逻辑工作,m和f变量被放入一个变量(gender_bool),可以在以后的逻辑中进行评估,if语句评估更有意义的东西(imho),你使用raw_input使你可以输入任何内容而不会出现错误(我添加了一些\ n(换行符)来取悦我的OCD:P)。