简体   繁体   English

将 int 和 float 写入不同的文本文件

[英]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 .您不转换input的结果,因此它仍然是str ,并且永远不会是intfloat类型。 You can fix this by adding import ast at the top of the file, then changing:您可以通过在文件顶部添加import ast来解决此问题,然后更改:

     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 .你在滥用isinstance The result of isinstance is True or False , not the parsed number. isinstance的结果是TrueFalse ,而不是解析后的数字。 You don't want to compare it to num .您不想将其与num进行比较。 Just remove the num == from the two elif tests so you evaluate the result of isinstance directly.只需从两个elif测试中删除num ==即可直接评估isinstance的结果。

There are other solutions to #1, ast.literal_eval is just a convenient way of converting any legal Python literal to the corresponding value. #1 还有其他解决方案, ast.literal_eval只是将任何合法的 Python 文字转换为相应值的便捷方式。 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).您还可以尝试独立解析str读取为int ,然后float (捕获ValueError并适当处理它们)以获得相同的效果,这也消除了对isinstance检查的需要(如果引发ValueError ,它不是那种类型,如果它没有被提出,它现在是那种类型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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