用户插入多个值,程序将确定多少个正值,负值,零值,偶数,奇数值以及这些值的最小值,最大值,平均值和总计。该代码有效,但是非常混乱。
negative=0
zero=0
positive=0
even=0
odd=0
max=0
min=0
a=int(input('Number of values:'))
b=int(input('First value:'))
if b==0:
zero=1
if b<0:
negative=1
if b>0:
positive=1
if b%2==0:
even=1
else:
odd=1
if b>max:
max=b
total=b
for x in range(a-1):
b=int(input('Next value:'))
total+=b
if b==0:
zero+=1
if b==0:
zero+=1
if b<0:
negative+=1
if b>0:
positive+=1
if b%2==0:
even+=1
else:
odd+=1
if b>max:
max=b
if b<max:
min=b
print('Negative values:',negative)
print('Zero values:',zero)
print('Positive values:',positive)
print('Even values:',even)
print('Odd values:',odd)
print('Total:',total)
print('Minimum:',min)
print('Maximum:',max)
print('Average:',total/a)
答案 0 :(得分:1)
脚本中有两个部分基本上在做相同的事情,除了您要询问用户"First Value"
而不是"Next value"
。因此,我将它们合并成一个循环,然后确定要使用的味精。
到处也都缺少空白,这使得它很难阅读。查看Python的PEP 8标准约定指南。
您还可以使用更多描述性的变量名,以便一目了然。
还要小心命名变量min
和max
。这些已经是您要重写的Python中的内置方法。
negative = 0
zero = 0
positive = 0
even = 0
odd = 0
maxVal = 0
minVal = 0
total = 0
count = int(input('Number of values:'))
for i in range(count):
if i == 0:
msg = 'First value:'
else:
msg = 'Next value:'
val = int(input(msg))
total += val
if val == 0:
zero += 1
if val < 0:
negative += 1
if val > 0:
positive += 1
if val % 2 == 0:
even += 1
else:
odd += 1
if val > maxVal:
maxVal = b
if val <= minVal <= val and val < maxVal:
minVal = val
print('Negative values:', negative)
print('Zero values:', zero)
print('Positive values:', positive)
print('Even values:', even)
print('Odd values:', odd)
print('Total:', total)
print('Minimum:', minVal)
print('Maximum:', maxVal)
print('Average:', total / count)
答案 1 :(得分:0)
我对您的代码进行了演绎,使我脑海变得更加整洁,这样,您不仅可以存储值,还可以使用Counter来记住输入的所有值以及使用它们的次数。还要固定您的空格,并且times_to_run
比a
更具描述性,而value
比b
更具描述性。我还只是使用了您正在使用的迭代编号作为输入的n'th
from collections import Counter
total = 0
all_numbers = Counter()
times_to_run = int(input('Number of values: '))
for x in range(times_to_run):
value = int(input(f'Value {x + 1}: '))
total += value
all_numbers[value] += 1
negative = sum(all_numbers[n] for n in all_numbers if n < 0)
zero = all_numbers[0]
positive = sum(all_numbers[n] for n in all_numbers if n > 0)
even = sum(all_numbers[n] for n in all_numbers if abs(n) % 2)
odd = sum(all_numbers[n] for n in all_numbers if not abs(n) % 2)
max = max(all_numbers)
min = min(all_numbers)
print()
print('Negative values:',negative)
print('Zero values:',zero)
print('Positive values:',positive)
print('Even values:',even)
print('Odd values:',odd)
print('Total:',total)
print('Minimum:',min)
print('Maximum:',max)
print('Average:',total / times_to_run)
要测试:
Number of values: 10
Value 1: -1
Value 2: -1
Value 3: 5
Value 4: 2
Value 5: 0
Value 6: 3
Value 7: 55
Value 8: 8
Value 9: 10
Value 10 :4
Negative values: 2
Zero values: 1
Positive values: 7
Even values: 5
Odd values: 5
Total: 85
Minimum: -1
Maximum: 55
Average: 8.5