while循环返回程序开始

2024-04-16 17:10:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个循环,以便让用户回到程序的开头。我无法让它打印“欢迎使用比较功能”。程序将运行,要求用户输入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

Tags: orto用户程序loopyoutrueinput
2条回答

这将是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()
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:

^{pr2}$

希望这有帮助。谢谢

相关问题 更多 >