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:"))
Eu tentei usar "ou" para que a verificação possa incluir 'KE' e 'GPE', mas quando você executa o programa, mesmo se eu inserir KE ou GPE, o primeiro loop while continua! Como posso fazer funcionar?
O problema está na sua condição. Uma vez que "GPE"
é logicamente True
(string não vazia é logicamente True
), a condição do loop while é sempre True
, não importa qual seja a escolha.
Mudança:
Choice != "KE" or "GPE"
para:
Choice != "KE" and Choice != "GPE"
ou:
Choice not in ["KE","GPE"]
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras