簡體   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