使用Python 3.6.2 - 完全是编程新手,我需要找到用户输入的产品,总和和平均值。我有总和和平均下来,但我似乎无法使产品正常运行。这就是我到目前为止......
#Request input from user
sum = 0
while True:
try:
numVar = int(input("Specify number of variables to be entered: "))
break
except ValueError:
pass
while True:
try:
raw = input("Enter a number or press enter for results: ")
break
except ValueError:
pass
while raw != "":
raw = input("Enter a number or press enter for results: ")
numbers = int(raw)
sum += numbers
ave = round(sum / numVar, 1)
prd = 1
for count in range(numbers):
count = count + 1
prd *= count
#Print results
print("The sum is" , sum)
print("The average is", ave)
print ("The product is", prd)
任何帮助都会很棒!
答案 0 :(得分:0)
您已经获得了sum
,您可以按照获得总和的方式计算产品。
尽可能少地更改代码,但请注意我们需要将变量名称sum
更改为total
,因为sum
会覆盖内置的python关键字{{ 3}}功能。
另外,我删除了你输入用户输入的重复行:raw = input("Enter a number or press enter for results: ")
,它丢失了用户输入:
#Request input from user
total = 0
prd = 1
raw = 0
try:
numVar = int(input("Specify number of variables to be entered: "))
except ValueError:
pass
while raw != "":
raw = input("Enter a number or press enter for results: ")
try:
total += int(raw)
prd *= int(raw)
except ValueError:
pass
ave = round(total / numVar, 1)
print("The sum is" , total)
print("The average is", ave)
print ("The product is", prd)
演示:
Specify number of variables to be entered: 4
Enter a number or press enter for results: 3
Enter a number or press enter for results: 4
Enter a number or press enter for results: 5
Enter a number or press enter for results: 6
Enter a number or press enter for results:
The sum is 18
The average is 4.5
The product is 360
我希望这会有所帮助。