looping = True
while looping:
number = input("Number: ")
string_number = number.split(".")
if len(string_number) != 2:
print ("ERROR: Needs exactly one decimal point!")
looping = True
elif len(string_number[1]) != 2:
print ("ERROR: Two numbers are required after decimal point!")
looping = True
else:
try:
number = float(number)
looping = False
except ValueError:
print("ERROR: Number is not valid!")
looping = True
製作一些小的改動消除了可變looping
的需要。由於我們的目標是獲得一個有效的數字,我們可以測試爲:
number = None
while not number:
s = input("Number: ")
string_number = s.split(".")
if len(string_number) != 2:
print ("ERROR: Needs exactly one decimal point!")
continue
elif len(string_number[1]) != 2:
print ("ERROR: Two numbers are required after decimal point!")
continue
try:
number = float(s)
except ValueError:
print("ERROR: Number is not valid!")
可以使用功能全面的自動轉換爲浮動與2位小數。 – shantanoo