首页 > 解决方案 > 我将如何创建一个从用户端重新启动代码的输入输入?

问题描述

我正在寻找一种在此代码末尾包含输入的方法,其中将提示用户选择重新启动代码或结束代码而无需手动重新启动它。

def correct_result(choice,num):
if choice.lower() == 'square':      #Prints the Square of a number Ex. 2^2 = 4
    return num**2

elif choice.lower() == 'sqrt':      #Prints the Square root of a number Ex. √4 = 2 
    return num**.5

elif choice.lower() == 'reverse':   #Changes the sign of the number
    return(-num)

else:
    return 'Invalid Choice'         #prints an error message

choice = input()                  #Creates a answer box to enter the desired choice
num = int(input())                #Creates a second box that lets the user enter their number
print(correct_result(choice,num)) #Prints either the desired choice or the error function

标签: python

解决方案


choice将您的和输入包装num在一个while循环中,当用户选择“退出”时中断:

def correct_result(choice,num):
    if choice.lower() == 'square':      #Prints the Square of a number Ex. 2^2 = 4
        return num**2
    elif choice.lower() == 'sqrt':      #Prints the Square root of a number Ex. √4 = 2
        return num**.5
    elif choice.lower() == 'reverse':   #Changes the sign of the number
        return(-num)
    else:
        return 'Invalid Choice'         #prints an error message

while True:

    choice = input("Choice: ")                  #Creates a answer box to enter the desired choice

    if choice == "exit":
        exit()

    num = int(input("Number: "))                #Creates a second box that lets the user enter their number
    print(correct_result(choice,num)) #Prints either the desired choice or the error function


推荐阅读