我正在尝试制作一个程序,要求用户输入一个号码然后询问他们是否要输入另一个号码。根据他们输入的数字,程序将对它们求和并给出它们的平均值。
这是我到目前为止所得到的但我知道它不起作用。非常感谢任何帮助。
a = int(input("Enter a number: "))
more = input("Please enter Y or N if you want to add more numbers: ")
def funct(more):
while more == "Y":
b = int(input("Enter another number: "))
abSum = a + b
abMean = a + b / 2
if more == "Y":
return b
else:
break
print(abSum)
print(abMean)
答案 0 :(得分:3)
简化,您的程序可能如下所示:
abSum = int(raw_input("Enter a number: "))
while raw_input("Please enter Y if you want to add more numbers or anything else to finish: ") == 'Y':
b = int(raw_input("Enter another number: "))
abSum = abSum + b
abMean = abSum / 2
print(abSum)
print(abMean)
基本上你循环直到用户输入并清空第二个提示中的任何其他内容,然后修复你的总和/均值。
对于您要完成的任务,您不一定需要单独的功能。如果你想要一个功能,比如一个家庭作业 - 那么你可以重写这个片段以将b
的值传递给一个单独的函数,该函数将更新abSum
和abMean
并调用它来自while
循环。
答案 1 :(得分:3)
我将其清理干净并将其转换为自包含的脚本:
#!/usr/bin/env python
def ask_for_some_numbers():
numbers = []
more = 'y'
while more.lower() == 'y':
number = int(raw_input("Enter a number: "))
numbers.append(number)
more = raw_input("Please enter Y if you want to add more numbers: ")
print (sum(numbers))
print (sum(numbers)/len(numbers))
if __name__ == '__main__':
ask_for_some_numbers()
以下是不同之处:
numbers = []
) - 这样你就可以很容易地获得任意数量的数字。raw_input
代替input
。 documentation for input建议您使用raw_input来输入用户的输入,因为input
会评估输入的内容(如果您有恶意用户,这可能会导致您出现问题)。sum
方法来总结列表中的项目。答案 2 :(得分:1)
尝试类似:
a = int(input("Enter a number: "))
more = input("Please enter Y or N if you want to add more numbers: ")
summ=a #intialize sum to a
count=1 # no. of integers entered, to calculate mean
while more.lower()=="y":
b = int(input("Enter another number: "))
count+=1 #increase count by 1
summ+= b #add b to sum
abMean = summ/float(count) #used float(count) to get actual value
print("sum=",summ)
print("mean=",abMean)
more = input("Please enter Y or N if you want to add more numbers: ") #ask for user input
print("sum=",summ)
print("mean=",abMean)
输出
Enter a number: 5
Please enter Y or N if you want to add more numbers: y
Enter another number: 5
sum= 10
mean= 5.0
Please enter Y or N if you want to add more numbers: y
Enter another number: 2
sum= 12
mean= 4.0
Please enter Y or N if you want to add more numbers: y
Enter another number: 15
sum= 27
mean= 6.75
Please enter Y or N if you want to add more numbers: y
Enter another number: 10
sum= 37
mean= 7.4
Please enter Y or N if you want to add more numbers: n
sum= 37
mean= 7.4
答案 3 :(得分:1)
这里有一些简单的循环代码,它会询问数字,直到它获得一个空白条目,之后它将打印输入的总和和平均值:
total = 0
count = 0
num = input("Enter a number: ")
while (num):
total += int(num)
count += 1
num = input("Enter another number (or a blank line to quit): ")
print("Total =", total)
print("Average =", total/count)
答案 4 :(得分:0)
你不需要在某个地方调用这个函数吗?
类似(未经测试):
if a and more=="Y":
funct(more)