[英]Write int and float to different text files
I'm doing beginners programming course and I'm stuck with the following task:我正在上初学者编程课程,但我坚持以下任务:
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:
但问题如下:
You have two problems:你有两个问题:
You don't convert the result of input
, so it remains a str
, and will never be of type int
or float
.您不转换
input
的结果,因此它仍然是str
,并且永远不会是int
或float
类型。 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
You're misusing isinstance
.你在滥用
isinstance
。 The result of isinstance
is True
or False
, not the parsed number. isinstance
的结果是True
或False
,而不是解析后的数字。 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.