python - 我将如何创建一个从用户端重新启动代码的输入输入?
问题描述
我正在寻找一种在此代码末尾包含输入的方法,其中将提示用户选择重新启动代码或结束代码而无需手动重新启动它。
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
解决方案
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
推荐阅读
- ios - 在 Swift 中检测 2 个 UIImageView 的交集
- github-api - 通过 GitHub api 获取提交的行数
- vba - 变量不变
- php - 我的 PHP 表单发送数据但 sql 显示所有列零记录
- android - 在主线程外运行时对 Cloud Firestore 进行同步调用
- c# - 替换方法不适用于 C# 中的转义字符 '\xA0'
- javascript - 如何获取密钥并将其附加到 json 文件中的下一个值?
- python - 为多处理序列化对象很慢——有没有办法只序列化一次?
- python - Cloud Foundry 上的 Flask 应用程序 - 命令“python setup.py egg_info”失败,错误代码为 1
- python - Flask App 拒绝连接