以下是我需要帮助的源代码: 我之后也会显示输出,但我的问题是如何在循环内部进行正确的循环...在循环内?
我有3个输入:
conversionchoice = a/b
feetinput (or metersinput) = float(input("Enter feet: "))
choice = input("Do you want to enter another conversion? (y/n): ")
当我在conversionchoice
输入错误输入时,它会循环播放,以便输入正确的输入,但是当我为feetinput
输入错误的输入时,{{1} }或metersinput
,它一直循环回choice
。
conversionchoice
TL; DR输出低于,如何使循环工作,以便循环到各自的值而不是循环到开头?
import conversions as c
def displaytitle():
print("Feet and Meters Converter")
def conversionsmenu():
print("\n Conversions Menu: \na. Feet to Meters\nb. Meters to Feet")
conversionchoice = input("Select a conversion, feet to meters, or meters to feet (a/b): ")
return conversionchoice
def main():
displaytitle()
choice = "y"
while choice == "y":
while True:
conversionchoice = conversionsmenu()
try:
if conversionchoice == "a":
feetinput = float(input("Enter feet: "))
print(c.to_meters(feetinput), "meters")
elif conversionchoice == "b":
metersinput = float(input("Enter meters: "))
print(c.to_feet(metersinput), "feet")
else:
print("Invalid input. Please enter the letter a or b.")
continue
choice = input("Do you want to enter another conversion? (y/n): ")
if choice == "n":
print("Thanks, bye!")
break
elif choice == "y":
continue
else:
print("Please retry.")
except:
print("Invalid input. Please retry \n")
main()
答案 0 :(得分:0)
我想对代码提出很多建议:
displaytitle()
是一种无意义的方法,可以用print()
语句替换。snake_case
会使您的代码更具可读性,建议按PEP 8。choice = "y"
令人困惑。只需看看是否指定了conversionchoice
,并在while循环的每次迭代中重置它。while
语句是多余的,甚至会使事情更加混乱。你只需要一个。 while True:
将无限循环。input()
is functionally different from raw_input()
。我想你会想要使用raw_input()
。try:
块中,而是考虑在您投射到第19行的浮点数的输入上使用isinstance()
。try/except
块来控制程序流 - 而是使用这些块来激活特定的运行时异常。break
语句将突破while True
循环,但不会突破while choice == "y"
循环。所有人都说过,这段代码会起作用:
# import conversions as c
def get_conversion_type():
print("\n Conversions Menu: \na. Feet to Meters\nb. Meters to Feet")
conversionchoice = raw_input("Select a conversion, feet to meters, or meters to feet (a/b): ")
return conversionchoice
def main():
print("Feet and Meters Converter")
conversion_type = None
while conversion_type is None:
conversion_type = get_conversion_type()
if conversion_type == "a":
feetinput = float(raw_input("Enter feet: "))
print "Conversion successful!"
conversion_type = None
elif conversion_type == "b":
metersinput = float(raw_input("Enter meters: "))
print "Conversion successful!"
conversion_type = None
else:
print("Invalid input. Please enter the letter a or b.")
conversion_type = None
continue
choice = None
while choice is None:
choice = raw_input("Do you want to enter another conversion? (y/n): ")
if choice == "n":
print("Thanks, bye!")
exit(0)
elif choice == "y":
continue;
else:
print("Please retry.")
choice = None
main()