我试图创建一个循环,以便将用户带回程序的开头。我无法打印"欢迎使用比较功能"。程序将运行,询问用户输入1和2然后将打印比较的答案,但我无法弄清楚如何重新开始。
def comparison():
loop = True
while (loop):
print(" Welcome to the comparison function")
a = int (input("Enter your first number for value a, then hit enter key:"))
b = int (input("Enter your second number for value b, then hit enter key:"))
def compare (a,b):
if a>b:
return 1
elif a==b:
return 0
else:
return -1
answer = compare(a,b)
print (answer)
while True:
response=input ("Would you like to perform another comparison? (yes/no)")
if response=="yes" or response =="YES" or response =="Yes":
print ("Thank you!")
break
elif response=="no" or response=="NO" or response =="No":
loop=False
print ("Thank you, have a great day!")
break
else:
continue
答案 0 :(得分:1)
这将替代Python 3中的函数:
def comparison():
while True:
print("Welcome to the comparison function")
a = int(input("Enter your first number for value a, then hit enter key:"))
b = int(input("Enter your second number for value b, then hit enter key:"))
# Recommended replacement for cmp(a, b) in Python 3
# https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons
answer = (a > b) - (a < b)
print(answer)
response = input("Would you like to perform another comparison? (yes/no)")
while response.lower() not in ['yes', 'no']:
response = input("please enter proper response: ")
if response.lower() == "yes":
print("Thank you!")
else:
print("Thank you, have a great day!")
break
comparison()
答案 1 :(得分:0)
def comparision():
loop = True
while loop:
print ("welcome to the comparision function: ")
a = int(input(("Enter your number for a value a , then hit enter key:")))
b = int (input("Enter your second number for value b, then hit enter key:"))
answer = ''
if a > b:
answer = 1
elif a == b:
answer = 0
else:
answer = -1
print (answer)
response = str(input("Would you like to perform another comparison? (yes/no) :"))
while response.lower() not in ['yes', 'no']:
response = str(input("please enter proper response: "))
if response.lower() == 'yes'
continue
elif response.lower() == 'no'
print ("Thank you, have a great day!")
break
if __name__ == '__main__':
comparision()
如果您使用的是python 2.7:
response = str(raw_input("Would you like to perform another comparison? (yes/no) :"))
希望这会有所帮助。感谢