y = "\n"
total = 0
k = 0
while True:
x = input("Enter your number here: ")
x = float(x)
total = total + float(x)
k = k + 1
if type(x) != int:
print(total/k)
break
y = "\n"
total = 0
k = 0
while True:
x = input("Enter your number here: ")
x = float(x)
total = total + float(x)
k = k + 1
if type(x) != int:
print(total/k)
break
请注意,函数input()
始终输出一个字符串,因此type(input()) != int
永远是真的。
当出现ValueError(例如无法将空白/字母转换为浮点数)时,请尝试使用try-except
函数,将会引发异常并中断循环:
total = 0
k = 0
while True:
x = input("Enter your number here: ")
try:
total += float(x)
k += 1
except ValueError:
if k > 0: #to avoid division by zero
print("Average: ", total/k)
break
输出:
Enter your number here: 3
Enter your number here: 4
Enter your number here: 5
Enter your number here:
Average: 4.0
total = 0.0
k = 0.0
while True:
x = input("Enter your number here: ")
if (x == " "): # Check for a blank line entry here before attempting to convert to float
print("Average is:", (total/k))
break
x = float(x)
total = total + float(x)
k = k + 1
其他人已经用不同的方法解决了你的问题,但我认为解释我们的思路也可能有用。
目前,你的程序没有正确检查退出条件(输入空行而不是数字)。当输入新行时,你的程序应该执行以下两种可能的情况之一:
没有指定第三个选项,所以现在让我们假设每一行都是空行或数字。稍后再扩展它。
在你决定要做什么之后,这些操作应该很容易地包含在一个while True:
块中 - 所以应该是:
initialize_variables_total_and_count
while True:
read_line
decide_what_to_do:
# in case line was a number
convert_line_to_float
add_float_to_total
increment_count
other_case:
# empty line was entered
calculate_and_print
break
只有两个选项,你只需要一次决定要做什么。通过决定要检查哪个条件(这也会导致另一个成为其他情况下的“默认”行为),你可以交换案例。
使用if line_entered == "":
来检查行是否为空更简单。在这种情况下,任何非空行都被视为数字,如果不是数字,则float()
函数会出错,使你的程序崩溃。
检查一个字符串(输入的行)是否可以转换为浮点数有点困难。Python中没有内置的转换方法,但有一个技巧:你可以尝试将其转换为浮点数,如果成功,则说明可以转换,如果出错,则无法转换。还有其他方法,但这是最简单的方法-参见此问题上的主题。
在这种情况下,每个数字都会被添加到总数中,每个非数字(包括空行,以及像“asdf”这样的随机字符串)都会导致程序计算总数并停止。
您可以通过使用break
或continue
来避免将两种情况放入if-else块中。(技术上讲,您从不需要使用break
或continue
,所有程序都可以在没有它们的情况下编写。在这种情况下,您可以使用一个布尔变量,例如命名为run
,编写while run:
,并且在不使用break
的情况下,执行run = False
)。您可以利用break
和continue
都会提前结束循环的事实,避免将第二种情况放在else块内,仍然具有相同的行为(因为break
和continue
已经导致跳过其余的循环体)。
因此,以下是一个示例实现:(测试== ""
,不使用非结构化控制流)
total = 0
count = 0
run = True
while run:
line = input("Enter your number here: ")
if line == "":
print(total / count)
run = False
else:
total += float(line)
count += 1
我还将k
重命名为count
,x
重命名为line
并使用原地加法运算符。
另一种实现方式,使用try/except
测试float
(并在整个控制流中重复使用):
total = 0
count = 0
while True:
line = input("Enter your number here: ")
try:
# order matters here. If the first line errors out, the second won't happen so the count will only be inremented if it was indeed a float
total += float(line)
count += 1
except:
print(f"Average is: {total / count}")
break
在这里,我移除了run
变量,并使用格式化字符串打印出更加漂亮的结果。
以下是同时使用continue
和break
的示例:
total = 0
count = 0
while True:
line = input("Enter your number here: ")
if line != "":
total += float(line)
count += 1
continue
print(f"Average is: {total / count}")
break
您可以通过添加更多的错误处理来使其更加精美 - 使用三种情况:
我只提供了一个示例实现,但是正如您所看到的,它可以以许多方式实现。
total = 0
count = 0
# good practice to tell the user what to do
print("Average calcuator. Enter numbers one per line to calulate average of, enter empty line to print result & exit!")
while True:
line = input("Enter your number here: ")
if line == "":
print(f"Average is: {total / count}")
break
else:
try:
total += float(line)
count += 1
except ValueError:
print("You should enter a number or an empty line to calculate & exit!")
float()
函数之前,您需要检查输入是否为空。 - John Gordon