如何在输入无效的情况下重新启动程序 python

huangapple go评论123阅读模式
英文:

How to restart a programm if input is invalid python

问题

第一个项目初学者在这里我刚刚完成了我的第一个项目一个有点工作的计算器我知道它不是那么好但正如我所说我是初学者我想限制数字选项 = 输入意思是如果你输入的不是addsubstractdivide或multiply之外的任何内容你将收到一个错误消息类似于"请再试一次"然后程序将重新启动

非常感谢帮助谢谢

列表 = ("add", "substract", "divide", "multiply")

number = input("您想要加、减、除还是乘?")

if number in list:
print("好的")
else:
print("请再试一次")

number_one = float(input("输入第一个数字"))
number_two = float(input("输入第二个数字"))

if number == "add":
solution_one = number_one + number_two
print(solution_one)

if number == "substract":
solution_two = number_one - number_two
print(solution_two)

if number == "divide":
solution_three = number_one / number_two
print(solution_three)

if number == "multiply":
solution_four = number_one * number_two
print(solution_four)

我只能找到关于while循环的解决方案,但我不知道如何在这种情况下使用它们,因为这些不是字符串而是整数。
英文:

first project beginner here! I just finished my first project, a somewhat working calculator i know it is not that great but as i said beginner. I would like to limit the options for number = input meaning if you write anything else than add,substract,divide or multiply you receive an error like " please try again" and afterwards the programm is restarted

Help very much appreciated Thank you.

list = ("add", "substract", "divide" , "multiply" )

number = input("do you want to add substract divide or multiply? ")

if number in list:
    print("ok")
else:
    print("try again")

number_one = float(input("enter your first number "))
number_two = float(input("enter your second number "))

if number == "add":
    solution_one = number_one + number_two
    print(solution_one)

if number == "substract":
    solution_two = number_one - number_two
    print(solution_two)

if number == "divide":
    solution_three = number_one / number_two
    print(solution_three)

if number == "multiply":
    solution_four = number_one * number_two
    print(solution_four)

i could only find solutions regarding while loops but i did not know how to use them in this case as these weren't strings but integers.

答案1

得分: 1

The fact that you're prompting for a string doesn't change the way the while loop works. Run your code in a loop and break when it's time for the loop to end.

while True:
    number = input("你想加、减、除还是乘?")
    if number in ("加", "减", "除", "乘"):
        print("好的")
        break
    print("请重试")

Note that it's considered bad practice to give a variable a name like list (or any other built-in name) since it can lead to very confusing bugs when you try to reference the built-in name later!

英文:

The fact that you're prompting for a string doesn't change the way the while loop works. Run your code in a loop and break when it's time for the loop to end.

while True:
    number = input("do you want to add substract divide or multiply? ")
    if number in ("add", "substract", "divide" , "multiply" ):
        print("ok")
        break
    print("try again")

Note that it's considered bad practice to give a variable a name like list (or any other built-in name) since it can lead to very confusing bugs when you try to reference the built-in name later!

答案2

得分: 0

您可以考虑使用 operator 模块。

构建一个将用户选择的操作与相关函数进行映射的字典。

import operator

OMAP = {
    'add': operator.add,
    'subtract': operator.sub,
    'divide': operator.truediv,
    'multiply': operator.mul
}

while (op := input('您想要执行加法、减法、乘法、除法或结束? ')) != 'end':
    try:
        if (func := OMAP.get(op)):
            x = float(input('请输入第一个数字: '))
            y = float(input('请输入第二个数字: '))
            print(func(x, y))
        else:
            raise ValueError(f'"{op}" 不是有效的选择')
    except ValueError as e:
        print(e)
英文:

You could consider using the operator module.

Build a dictionary that maps the user's selected operation with the relevant function.

import operator

OMAP = {
    'add': operator.add,
    'subtract': operator.sub,
    'divide': operator.truediv,
    'multiply': operator.mul
    }


while (op := input('Do you want to add, subtract, multiply, divide or end? ')) != 'end':
    try:
        if (func := OMAP.get(op)):
            x = float(input('Enter your first number: '))
            y = float(input('Enter your second number: '))
            print(func(x, y))
        else:
            raise ValueError(f'"{op}" is not a valid choice')
    except ValueError as e:
        print(e)

huangapple
  • 本文由 发表于 2023年2月9日 02:19:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定