简体   繁体   中英

Write int and float to different text files

I'm doing beginners programming course and I'm stuck with the following task:

  • Input both int and float numbers
  • Write them to different text files
  • Break without number input

How should I proceed on making this work?

while True:
    
    try:
        num = input("Enter number: ")
        if not isinstance(num, (int, float)):
            break

        elif num == isinstance(num, float):
            def float_file(num):
                with open("Float.txt", "a") as ff:
                    ff.write(str(num))

        elif num == isinstance(num, int):
            def int_file(num):
                with open("Int.txt", "a") as fi:
                    fi.write(str(num))

    except Exception as e:
        print("Failed to write file")

I have tried to complete this task with couple different methods. But the problems are the following:

  • Input doesn't loop
    • If it does I can't stop it with non numbers
  • Files won't get created
    • If they do nothing is written

You have two problems:

  1. You don't convert the result of input , so it remains a str , and will never be of type int or float . You can fix this by adding import ast at the top of the file, then changing:

     num = input("Enter number: ")

    to:

     try: num = ast.literal_eval(input("Enter number: ")) except SyntaxError: print("Input was not a valid Python literal", file=sys.stderr) break
  2. You're misusing isinstance . The result of isinstance is True or False , not the parsed number. You don't want to compare it to num . Just remove the num == from the two elif tests so you evaluate the result of isinstance directly.

There are other solutions to #1, ast.literal_eval is just a convenient way of converting any legal Python literal to the corresponding value. You could also try independently parsing the str read as int , then float (catching ValueError s and handling them asa appropriate) for the same effect, which also removes the need for isinstance checks (if ValueError is raised, it's not of that type, if it's not raised, it's of that type now).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM