繁体   English   中英

如何在Python中将fileinput.input转换为整数?

[英]How do you convert a fileinput.input into integer in Python?

我正在尝试解决Hackerrank的30天代码的第1天,并尝试将fileinput.input转换为整数。

我尝试使用int()将其转换为整数,并使用str()将其转换为字符串,然后使用int()将其转换为整数。 两种方法似乎都不起作用。

i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.

# Read and save an integer, double, and String to your variables.

# Print the sum of both integer variables on a new line.

# Print the sum of the double variables on a new line.

# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
import fileinput
i2 = fileinput.input()
d2 = fileinput.input()
s2 = str(fileinput.input())

i3 = i + i2
d3 = d2 * 2

print(str(i3))
print(str(d3))
print(str(s+s2))

我期望它是:

16
8.0
HackerRank is the best place to learn and practice coding!

但它返回:

 Traceback (most recent call last):
      File "Solution.py", line 20, in <module>
        i3 = i + i2
    TypeError: unsupported operand type(s) for +: 'int' and 'FileInput'

您只需要input()而不是fileinput() ,目标只是转换用户input

作为提示,您的inputs应如下所示:

num = int(input())s = str(input())

如果您仍然遇到问题,则GitHub上有一个很好的解决方案

不需要导入文件输入,其余文件输入。 在python中,您不能混合使用两种不同的变量类型,因此i2必须为整数。

而是按照注释“将整数,双精度和字符串保存到变量中”中的说明指定变量i2,d2,s2输入。 在蟒蛇float来代替double ,因为它是在其他汇编编程语言中使用。

例如。 s2 = str(fileinput.input()) -> s2 = str(input())s2 = input()因为input()默认已为字符串。

还要注意“#在新行上打印双精度变量的总和 。”

暂无
暂无

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

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