好的我有点麻烦我可以让程序读取所有整数但现在我很困惑如何让程序读取奇怪的甚至然后只添加奇数和偶数,给总计两个
def main():
myfile = open('numbers.txt','r')
for line in myfile:
print(line)
myfile.close()
myfile=open('numbers.txt','r')
num1=int(myfile.readline())
num2=int(myfile.readline())
num3=int(myfile.readline())
num4=int(myfile.readline())
num5=int(myfile.readline())
num6=int(myfile.readline())
num7=int(myfile.readline())
num8=int(myfile.readline())
num9=int(myfile.readline())
num10=int(myfile.readline())
num11=int(myfile.readline())
num12=int(myfile.readline())
myfile.close()
total=num1+num2+num3+num4+num5+num6+num7+num8+num9+num10+num11+num12
print('The numbers are:',num1,num2,num3,num4,num5,num6,num7,num8,num9,num10,num11,num12)
print('Their total is:',total)
main()
答案 0 :(得分:0)
def isEven(number):
return number % 2 == 0
def main():
myfile = open('numbers.txt','r')
nums = []
for line in myfile:
num.append(line)
print('The numbers are '+ str(nums))
print('Their total is :'+str(sum(nums))))
我已将您的代码缩减为DRY标准,并添加了isEven功能
您可以在整数上调用isEven来确定它是偶数还是奇数。
isEven(1) # False
isEven(2) # True
答案 1 :(得分:0)
以下是对此
的所有可能解决方案的品味myfile = open("test.txt")
list_of_num = list()
#same as list_of_num = []
for line in myfile:
list_of_num.append(int(line)) #this conversion to int() is important
#otherwise the "numbers" you read are actually
#strings!
total_sum = 0
for number in list_of_num:
total_sum = total_sum + number
#or you can also do just
#total_sum = sum(list_of_num)
print("The numbers are: ", end=": ")
for number in list_of_num:
print(number, end=" ")
print("Their total is: ", total_sum)
在打印语句中end
声明打印字符串末尾的内容。默认情况下,这是新行,但是对于更紧凑的打印外观,您可以要求它在最后留下一个空格。
另外,对于一个数字是偶数,它必须被2整除,而没有“改变”(额外的,不知道正确的单词)。您可以使用模运算符%
来检查是否为真,该运算符返回除法的余数。
如果保持为0.您的数字是均匀的。
答案 2 :(得分:0)
我相信你的意思是:
def main():
with open('numbers.txt') as my_file:
numbers = [int(line) for line in my_file]
print('The numbers are:', *numbers)
print('Their total is:', sum(numbers))
print('The total of just the odd ones is:',
sum(n for n in numbers if n % 2 != 0))
print('The total of just the even ones is:',
sum(n for n in numbers if n % 2 == 0))
if __name__ == '__main__':
main()
注意事项:
列表是你的朋友。 var1, var2, var3, ..., varN
反模式永远不会正确。
你忘了if __name__ == '__main__'
这就是定义一个像你一样的主函数的重点。这就是你调用它的地方(当你的文件作为脚本运行时)。
如果您了解它们,您可以使用生成器和内置函数。
答案 3 :(得分:0)
这是一个解决方案,以避免使用太多变量:
def getOddEven(fileName):
odd = 0
even = 0
print ('The numbers are: ')
with open(fileName, 'r') as myfile:
for line in myfile:
print(line),
try:
number = int(line)
if (number%2 == 0):
even+=number
else:
odd+=number
except:
pass
return odd,even
def main():
odd, even = getOddEven('numbers.txt')
print('\nTheir total is:',odd + even)
print('Total of odd numbers is: ', odd)
print('Total of even numbers is: ', even)
if __name__ == '__main__':
main()