微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

计算器我想添加一个循环,表示“无效输入”并重新询问用户是否输入了不正确的字符不知道该怎么做

如何解决计算器我想添加一个循环,表示“无效输入”并重新询问用户是否输入了不正确的字符不知道该怎么做

print("Welcome to the calculator!")
print("Enter in the symbol for you desired equation")

math = input("Would you like to ( + ),( - ),( / ) or ( * )?\n")


if math == '*':
    mult = float(input("Give me the first number you would like to multiply\n"))
    mult1 = float(input("Give me the second number\n"))
    print(mult,"*",mult1,"=",float(mult * mult1))

if math == '/':
    div = float(input("Give me the first number you would like to divide\n"))
    div1 = float(input("Give me the second number\n"))
    print(div,"/",div1,float(div / div1))

if math == '+':
    add = float(input("Give me the first number you would like to add\n"))
    add1 = float(input("Give me the second number\n"))
    print(add,"+",add1,float(add+add1))

我想添加一个循环函数,它基本上会说“无效输入”并在用户输入无效字符时再次循环回到问题。

解决方法

换行

math = input("Would you like to ( + ),( - ),( / ) or ( * )?\n")

while True:
    math = input("Would you like to ( + ),( / ) or ( * )?\n")
    if math in "+-*/":
        break
    else:
        print('invalid entry')

应该能让你得到你正在寻找的行为。 break 命令退出循环。

您应该能够将其概括为其他输入语句。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。