所以我正在制作一个程序,需要几公里并将其转换为英里,然后反过来。当程序运行时,首先提示用户输入数字1或2以确定其千克到英里或千米到千克。如果用户输入除1或2以外的任何内容,我想编程显示“请输入值1或2”等,然后再次询问。有什么方法可以做到这一点?到目前为止,这是我的代码。
#Program that takes kilometers and converts it to miles VV
def main():
choice = input("Kilometers to Miles/Miles to Kilometers? (1, 2): ")
if choice == 1:
kilo = float(input("How many kilometers will you be traveling?: "))
convert = 0.62
miles = kilo * convert
print("You will be traveling about", miles, "miles!")
else:
milesTraveled = eval(input("How many miles will you be traveling?: "))
convertTwo = milesTraveled // 0.62
print("You will be traveling about", convertTwo, "kilometers!")
#end main
main()
答案 0 :(得分:0)
最简单的方法是使用if语句。
user_input = input('Please enter either the value 1 or 2: ')
if(user_input == 1 or user_input == 2):
# do stuff here (remove the pass and replace with code you want to execute)
pass
else:
user_input = input('Please enter either the value 1 or 2: ')
编辑,因为提供了代码
只需用以下内容替换你的else块:
elif(choice == 2):
milesTraveled = eval(input("How many miles will you be traveling?: "))
convertTwo = milesTraveled // 0.62
print("You will be traveling about", convertTwo, "kilometers!")
然后添加:
else:
choice = input('Please enter either the value 1 or 2: ')
答案 1 :(得分:0)
你可以这样做;
try:
choice = int(raw_input("Enter choice 1 or 2:"))
if choice not in [1, 2]:
raise ValueError()
except ValueError:
print "Invalid Option, you needed to type a 1 or 2"
else:
print "Your choice is", choice
答案 2 :(得分:0)
您可以像这样使用if .. elif .. else ..
construction:
#Program that takes kilometers and converts it to miles VV
def main():
choice = input("Kilometers to Miles/Miles to Kilometers? (1, 2): ")
if choice == 1:
kilo = float(input("How many kilometers will you be traveling?: "))
convert = 0.62
miles = kilo * convert
print("You will be traveling about", miles, "miles!")
elif choice == 2:
milesTraveled = eval(input("How many miles will you be traveling?: "))
convertTwo = milesTraveled // 0.62
print("You will be traveling about", convertTwo, "kilometers!")
else:
print("You have entered incorrect value! Please try again\n")
main()
#end main
main()