嗨,我在循环结束时遇到问题。我需要接受输入作为字符串来获取“停止”或“”,但我不需要任何其他字符串输入。输入转换为浮点数,然后添加到列表中,但如果用户键入“bob”,我会收到转换错误,并且我无法设置输入(浮点数),因为那时我不能接受“停止”。
完整的当前代码如下。
我目前的想法如下:
- 检查“停止”,“”
- 检查输入是否为浮点数。
- 如果不是 1 或 2,则请求有效输入。
请问有什么想法吗?如果它很简单,只需指出我的方向,我会尝试将其制作出来。否则...
谢谢
# Write a progam that accepts an unlimited number of input as integers or floating point.
# The input ends either with a blank line or the word "stop".
mylist = []
g = 0
total = 0
avg = 0
def calc():
total = sum(mylist);
avg = total / len(mylist);
print("\n");
print ("Original list input: " + str(mylist))
print ("Ascending list: " + str(sorted(mylist)))
print ("Number of items in list: " + str(len(mylist)))
print ("Total: " + str(total))
print ("Average: " + str(avg))
while g != "stop":
g = input()
g = g.strip() # Strip extra spaces from input.
g = g.lower() # Change input to lowercase to handle string exceptions.
if g == ("stop") or g == (""):
print ("You typed stop or pressed enter") # note for testing
calc() # call calculations function here
break
# isolate any other inputs below here ????? ---------------------------------------------
while g != float(input()):
print ("not a valid input")
mylist.append(float(g))