[英]How to allow input only string value of “stop”, “”, then check and convert to float
Hi I am having trouble with the end of my loop. 嗨,我在循环结束时遇到了麻烦。 I need to accept the input as a string to get the "stop" or the "" but I don't need any other string inputs.
我需要接受输入作为字符串来获取“停止”或“”,但是我不需要任何其他字符串输入。 Inputs are converted to float and then added to a list but if the user types "bob" I get the conversion error, and I cant set the input(float) because then I can't accept "stop".
输入被转换为浮点数,然后添加到列表中,但是如果用户键入“ bob”,则会出现转换错误,并且由于无法接受“停止”而无法设置输入(浮点数)。
Full current code is below. 完整的当前代码如下。
My current thinking is as follows: 我目前的想法如下:
Any ideas please? 有什么想法吗? If its something simple just point me in the direction and i'll try churn it out.
如果它很简单,只需将我指出方向,我将尝试将其搅出。 Otherwise...
除此以外...
Thanks 谢谢
# 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))
I think the pythonic way would be something like: 我认为pythonic的方式将是这样的:
def calc(mylist): # note the argument
total = sum(mylist)
avg = total / len(mylist) # no need for semicolons
print('\n', "Original list input:", mylist)
print("Ascending list:", sorted(mylist))
print ("Number of items in list:", len(mylist))
print ("Total:", total)
print ("Average:", avg)
mylist = []
while True:
inp = input()
try:
mylist.append(float(inp))
except ValueError:
if inp in {'', 'stop'}:
calc(mylist)
print('Quitting.')
break
else:
print('Invalid input.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.