【问题标题】:How to put an input check for a calculator in python?如何在python中对计算器进行输入检查?
【发布时间】:2020-08-29 11:21:59
【问题描述】:
print("Welcome to the Kinetic Energy and Gravitational Potential Energy Calculator")
print("Which Calculator would you like to access?")

Choice = str(input("Type in KE for Kinetic Energy and GPE for Gravitational Potential Energy:"))

while Choice != "KE" or "GPE":
    print("Error. You have not entered a valid choice. Please type KE or GPE.")
    Choice = str(input("Type in KE for Kinetic Energy and GPE for Gravitational Potential Energy:"))


while Choice == "KE":
    print("You have chosen the Kinetic Energy Calculator.")
    mass = float(input("Type in the mass of the object in kilograms (kg):"))
    velocity = float(input("Type in the velocity of the object in metres per second (m/s):"))
    result = 0.5*mass*(velocity**2)
    print("The KE is:", result, "J(Joules)")
    Choice = str(input("Type in KE for Kinetic Energy and GPE for Gravitational Potential Energy:"))

while Choice == "GPE":
    print("You have chosen the Gravitational Potential Energy Calculator.")
    mass = float(input("Type in the mass of the object in kilograms (kg):"))
    height = float(input("Type in the height at which the object is in metres (m):"))
    result = 9.81*mass*height
    print("The GPE is:", result, "J(Joules)")
    Choice = str(input("Type in KE for Kinetic Energy and GPE for Gravitational Potential Energy:"))

我尝试过使用“或”,所以检查可以同时包含“KE”和“GPE”,但是当你运行程序时,即使我输入了 KE 或 GPE,第​​一个 while 循环也会继续进行!我怎样才能让它发挥作用?

【问题讨论】:

    标签: python input while-loop calculator


    【解决方案1】:

    问题在于你的情况。由于"GPE"在逻辑上是True(非空字符串在逻辑上是True),所以while循环条件总是True,不管选择什么。

    变化:

    Choice != "KE" or "GPE"
    

    到:

    Choice != "KE" and Choice != "GPE"
    

    或:

    Choice not in ["KE","GPE"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多