简体   繁体   English

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

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

I'm trying to solve day 1 of 30 Days of Code by Hackerrank and tried converting the fileinput.input into integer. 我正在尝试解决Hackerrank的30天代码的第1天,并尝试将fileinput.input转换为整数。

I tried converting it into integer using int() and converting it to a string using str() then integer using int() . 我尝试使用int()将其转换为整数,并使用str()将其转换为字符串,然后使用int()将其转换为整数。 Both methods don't seem to work. 两种方法似乎都不起作用。

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

I expected it to be: 我期望它是:

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

but it returned: 但它返回:

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

You just need input() not fileinput() , the goal is just to convert user input : 您只需要input()而不是fileinput() ,目标只是转换用户input

As a hint, your inputs should look like this: 作为提示,您的inputs应如下所示:

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

If you still are having trouble, there is a good solution on GitHub. 如果您仍然遇到问题,则GitHub上有一个很好的解决方案

import fileinput and the rest fileinputs are not needed. 不需要导入文件输入,其余文件输入。 In python you can not mix two different variable types, thus i2 needs to be an integer. 在python中,您不能混合使用两种不同的变量类型,因此i2必须为整数。

Instead, specify your variable i2,d2,s2 inputs as mentioned in comment "save an integer, double, and String to your variables". 而是按照注释“将整数,双精度和字符串保存到变量中”中的说明指定变量i2,d2,s2输入。 In python float is used instead double as it's used in other compiled programming languages. 在蟒蛇float来代替double ,因为它是在其他汇编编程语言中使用。

Eg. 例如。 s2 = str(fileinput.input()) -> s2 = str(input()) or s2 = input() as input() is already string by default. s2 = str(fileinput.input()) -> s2 = str(input())s2 = input()因为input()默认已为字符串。

Also take note of "# Print the sum of the double variables on a new line." 还要注意“#在新行上打印双精度变量的总和 。”

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

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