我正在为一个学校项目执行此操作,并且需要知道为什么即使条件不满足,输出仍然会显示“爱沙尼亚”。另外,为什么程序在某些地方放置“无”? 我不确定是否应该包含所有代码或仅包含一部分,因此我将把整个代码都包含在内,以防万一。我是新人,所以请原谅我的独裁......
# Purpose: Create a program that suggests a vacation spot based on user input
# Here is the Input, or answers to the questions
print('Hello! This is your Dream Vacation Spot!')
answers = [input('Do you want a "hot" or "cold" place? '),
input('Do you want a place that has a "huge" pop or "small" pop? '),
input('Are you planning on getting wet? "y" or "n": ')]
# Create the intro that displays what they said.
def intro():
for i in range(2):
print('')
print('Hi! Welcome to your Dream Vacation Spot!')
print('')
print('Listed here, are your answers:')
print('Hot or cold place? You said ' + answers[0])
print('Huge population, or small towny place? You said ' + answers[1])
print('Want to get wet? You said ' + answers[2])
for i in range(2):
print('')
# Start using the if/ elif statements to decide places to go.
def main():
if answers[0] == 'cold' and answers[1] == 'small' and answers[2] == 'wet' or 'Wet':
one = 'Congrats!! You got... \n Estonia!'
print(one)
elif answers[0] == 'cold' or 'Cold' and answers[1] == 'big' or 'Big' and answers[2] == 'y' or 'Y':
two = 'Congrats!! You got... \n Geirangerfjord, Norway!'
print(two)
elif answers[0] == 'cold' or 'Cold' and answers[1] == 'small' or 'Small' and answers[2] == 'n' or 'N':
three = 'Congrats!! You got... \n Innsbruck, Austria!'
print(three)
elif answers[0] == 'cold' or 'Cold' and answers[1] == 'big' or 'Big' and answers[2] == 'n' or 'N':
four = 'Congrats!! You got... \n Yellowknife, Canada!'
print(four)
elif answers[0] == 'hot' or 'Hot' and answers[1] == 'big' or 'Big' and answers[2] == 'n' or 'N':
five = 'Congrats!! You got... \n Austin, Texas!'
print(five)
elif answers[0] == 'hot' or 'Hot' and answers[1] == 'small' or 'Small' and answers[2] == 'n' or 'N':
six = 'Congrats!! You got... \n Bisbee, Arizona!'
print(six)
elif answers[0] == 'hot' or 'Hot' and answers[1] == 'small' or 'Small' and answers[2] == 'n' or 'N':
seven = 'Congrats!! You got... \n Grand Junction, Colorado!'
print(seven)
elif answers[0] == 'hot' or 'Hot' and answers[1] == 'small' or 'Small' and answers[2] == 'y' or 'Y':
eight = 'Congrats!! You got... \n Muskogee, Oklahoma!'
print(eight)
def printAll():
print(intro())
print(main())
for i in range(2):
print('')
print('Have a nice trip!!!')
printAll()
最佳答案
唷!这是很多代码,并且可能有一些关于如何处理复杂逻辑的重要教训,让我们看看我们是否不能让它工作得更好一点。
首先,我建议您使用列表理解和 lower() 函数来简化答案中的可能性数量
answers_lowercase = [x.lower() for x in answers]
那么为什么不在 if/elif 语句中使用单个逻辑测试,例如
def main():
if answers_lowercase == ['cold', 'small', 'wet'] :
print('Congrats!! You got... \n Estonia!')
可能还有更简洁、Python 的方式来编写代码:即从表中查找正确答案,而不是使用六个“if”语句,以及如果用户在输入中输入错误时进行错误处理。好的东西值得研究和学习。祝你好运!
关于python - 程序输出错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177416/