代码中有一些错误:
在main()
函数中,将变量num1
、num2
和num3
放在if语句的引号中.这是不正确的,因为我们希望比较变量值,而不是变量名.
即使让函数声明num2
和num3
,因为这些变量(包括num1
)是要在其中声明它们的函数的局部变量,main()
函数也不会识别它们.
为了解决这个问题,我们可以将num1
、num2
和num3
定义为global
个变量.
考虑到所有这些变化,你的代码可能看起来像这样(当然修改了question2()
和question3()
,所以这是一个真正的个性测验哈哈):
def question1():
print("What's your favorite genre of music?")
print("1. Pop")
print("2. Rap")
print("3. Metal")
music = int(input("Enter 1, 2, or 3: "))
global num_1
if music == 1:
num_1 = 3
elif music == 2:
num_1 = 2
else:
num_1 = 1
def question2():
global num_2
num_2 = 2
def question3():
global num_3
num_3 = 2
def main():
question1()
question2()
question3()
if num_1 + num_2 + num_3 == 9:
print("Your favorite color is red")
elif 5 < num_1 + num_2 + num_3 < 9:
print("Your favorite color is blue")
else:
print("Your favorite color is green")
main()
替代解决方案(首选):我们不需要将三个变量定义为全局变量,只需在函数中返回它们,然后在main()
函数中定义它们:
def question1():
print("What's your favorite genre of music?")
print("1. Pop")
print("2. Rap")
print("3. Metal")
music = int(input("Enter 1, 2, or 3: "))
if music == 1:
num_1 = 3
elif music == 2:
num_1 = 2
else:
num_1 = 1
return num_1
def question2():
num_2 = 2
return num_2
def question3():
num_3 = 2
return num_3
def main():
num_1 = question1()
num_2 = question2()
num_3 = question3()
if num_1 + num_2 + num_3 == 9:
print("Your favorite color is red")
elif 5 < num_1 + num_2 + num_3 < 9:
print("Your favorite color is blue")
else:
print("Your favorite color is green")
main()
我希望这有助于回答你的问题!如果您需要任何进一步的澄清或详细信息,请告诉我:)