def main():
#Open the numbers.txt file
File=open ('numbers.txt', 'r')
#This reads the lines in the file
for line in File:
#Convert line to float
amount=float(line)
#format and display the amount
print(format(amount,'.2f'))
print("\n")
#close the file
File.close()
for amount in range (0,13):
if (amount%2==0):
print amount
main()
这是输出的样子:
53
15
21
49
8
98
55
21
76
75
53
28
Total of even numbers:[]
Total of odd numbers:[]
除非您实际上在number.txt中有浮点数,否则只需将其强制转换为int即可:
with open("numbers.txt") as f:
odds = []
evens = []
for num in f:
num = int(num)
if num % 2: # if there is a remainder num is odd
odds.append(num)
else: # else it must be even
evens.append(num)
print("All even numbers: {}".format(evens))
print("All odd numbers: {}".format(odds))
print("Total amount of even numbers: {}".format(len(evens))) # len will be total even nums
print("Total amount of odd numbers: {}".format(len(odds)))
如果您只想要计数:
with open("numbers.txt") as f:
odd,even = 0, 0
for num in f:
num = int(num)
if num % 2:
odd += 1
else:
even += 1
print("Total amount of even numbers: {}".format(even))
print("Total amount of odd numbers: {}".format(odd))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句