我尝试制作一个从用户输入中打印最大和最小数字的代码。我希望该用户可以输入该号码,直到ValueError
我尝试过这样的事情:
value = raw_input(">")
largest_so_far = None
smalest_so_far = None
while(value):
if value > largest_so_far:
largest_so_far = value
if ValueError:
print largest_so_far
此代码创建无限循环。那我怎么能让它变得有限呢?
答案 0 :(得分:0)
您需要在此使用try
和except
。
while(True):
try:
value = float(raw_input(">")) # Get the input from user
if value > largest_so_far: # Type cast to integer
largest_so_far = value
except ValueError as e: # Handle ValueError
print largest_so_far
break # Break the infinite loop
答案 1 :(得分:0)
尝试这个
value = raw_input(">")
largest_so_far = None
smalest_so_far = None
while(value):
if value > largest_so_far:
largest_so_far = value
raise ValueError('largest_so_far')
答案 2 :(得分:0)
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num3 = input("Enter third number: ")
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between", num1, ",", num2, "and", num3, "is", largest)
答案 3 :(得分:0)
#Initialize the largest and smallest values as 'None'
largest = None
smallest = None
while True:
num = input("Enter a number:")
if num == "finish": #Type 'finish' to get the output
break
try:
fnum = float(num) #Convert input to float
#Get largest value
if largest is None:
largest = fnum
elif fnum > largest:
largest = fnum
#Get smallest value
elif smallest is None:
smallest = fnum
elif fnum < smallest:
smallest = fnum
except:
#If the user input is not 'finish' or a number
print("Invalid input")
continue
print("Largest value is",largest)
print("Smallest value is",smallest)