变量未定义! (蟒蛇)

时间:2020-06-07 22:08:13

标签: python

我一直在尝试进行我的第一个全文冒险,但是每当我运行它时,它都说答案是不确定的!请帮忙。如果您想知道,这是代码

accept = input("would you like to play the game??")
if accept.lower() .split() == "yes":
    answer: str = input ("you wake up in a room with two doors in front of you. do you go to the left or the right?")
if answer.lower() .split() == "left":
    answer2 = input(" you enter the left door. you find a phone with a peice of paper attached to the wall with the phone\n there are two numbers on the peice of paper\n will you choose to call the first one or the second one")

2 个答案:

答案 0 :(得分:0)

原因是因为条件不满足if语句的要求,所以您从未定义答案。是.split()弄错了:

accept = input("would you like to play the game??")
if accept.lower() == "yes":
    answer = input ("you wake up in a room with two doors in front of you. do you go to the left or the right?")
    if answer.lower() == "left":
        answer2 = input(" you enter the left door. you find a phone with a peice of paper attached to the wall with the phone\n there are two numbers on the peice of paper\n will you choose to call the first one or the second one")

您看到的是,当您拥有str.split()时,python将返回一个列表,而不是字符串。 看看这个:

print("hello".split())

输出:

["hello"]

答案 1 :(得分:0)

您的问题与此类似:

new RegExp().test()

请注意,由于function preg_match_all(regex, str) { return new RegExp(regex,'g').test(str) }x = False if x: answer = "yes" print(answer) ,因此x从未被定义,并且当Python到达需要打印False的行时,它将报告错误。

您需要定义一个answer子句,或者预先定义一个值,即:

answer

或者:

else

选择默认值还是显式替换项都取决于对您的代码更有意义的方法,它们都是解决此问题的有效方法。对于您而言,这取决于您的播放器不回答“是”的情况。