number read and output

坚强是说给别人听的谎言 提交于 2020-02-08 07:47:49

问题


Ok I'm having a little trouble I can get the program to read all the integers but now I'm confused how to get the program to read that is odd or even then add only odd and only even, giving totals for both

 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()

回答1:


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))))

I've reduced your code to DRY standards, and added isEven function
You can call isEven on an integer to determine if it's even or odd.

isEven(1) # False
isEven(2) # True



回答2:


I believe you meant:

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()

Things to note:

  1. Lists are your friend. The var1, var2, var3, ..., varN anti-pattern is never correct.

  2. You forgot if __name__ == '__main__' which is the whole point of defining a main function like you've got. That's where you call it (when your file is run as a script).

  3. You can use generators and built-in functions to great effect if you learn them.




回答3:


Here's a taste of what are some of all possible solutions to this

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)

In the print statements end declares what will be at the end of printed string. By default that is new line, however for more compact print look, you can ask it to just leave a single space at the end instead.

Aditionally, for a number to be even, it has to be divisible by 2 without "change" (extra, don't know the right word). You can check if that's true by using modulo operator % which returns the remain of the division.

If that remain is 0. Your number is even.




回答4:


here is a solution, to avoid using too many variables:

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()


来源:https://stackoverflow.com/questions/28597759/number-read-and-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!