简体   繁体   中英

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.

I tried converting it into integer using int() and converting it to a string using str() then integer using 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 :

As a hint, your inputs should look like this:

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

If you still are having trouble, there is a good solution on 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.

Instead, specify your variable i2,d2,s2 inputs as mentioned in comment "save an integer, double, and String to your variables". In python float is used instead double as it's used in other compiled programming languages.

Eg. s2 = str(fileinput.input()) -> s2 = str(input()) or s2 = input() as input() is already string by default.

Also take note of "# Print the sum of the double variables on a new line."

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