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:"))
I have tried using "or" so the check can include both 'KE' and 'GPE', but when you run the program, even if I input KE or GPE, the first while loop keeps going! How can I make it work?
The problem is in your condition. Since "GPE"
is logically True
(Non empty string is logically True
), the while loop condition is always True
, No matter what the choice is.
Change:
Choice != "KE" or "GPE"
to:
Choice != "KE" and Choice != "GPE"
or:
Choice not in ["KE","GPE"]