简体   繁体   English

如何在 python 中使用 int() 从文本转换 raw_input()

[英]How to conver raw_input() from a text using int() in python

i am learning to code in python.我正在学习在 python 中编码。 I am learning how to use numbers as string data from raw_input and convert these numbers to integers then use them to do number manipulations such as multiplications.我正在学习如何将数字用作 raw_input 中的字符串数据并将这些数字转换为整数,然后使用它们进行数字运算,例如乘法。 Below my code is the error i am getting.我的代码下面是我得到的错误。 Any light on this will be very welcomed.对此的任何启示都将受到欢迎。 Thanks谢谢

python

num = raw_input("what is your favourite number?")
num= int(num) #convert num from text into a number using int() and double it.
print("Double my favourite number is ") +(num*2)

python This is the error i am getting python这是我得到的错误

python

TypeError: cannot concatenate 'str' and 'int' objects on line 3 in main.py TypeError:无法在 main.py 的第 3 行连接“str”和“int”对象

python

You're doing fine converting user input from a str to an int您将用户输入从str转换为int做得很好

Your only problem is that you're trying to add an int to the return value of print() :您唯一的问题是您正在尝试将int添加到print()的返回值:

print("Double my favourite number is ") +(num*2)

# is the same as:
print("Double my favourite number is ")
None + (num * 2)  # because print() will return None

To solve this, a few options:为了解决这个问题,有几个选择:

Fix the parenthesis for print to completely surround the str and the int and convert the int back into a str before "adding" (concatenating) to the str :修复print的括号以完全包围strint并在“添加”(连接)到str之前将int转换回str

print("Double my favourite number is " + str(num * 2))

You can also use interpolation via f-strings for the same/similar purpose, which will automatically call str() on interpolated values (the num * 2 ).您还可以通过 f-strings 使用插值来实现相同/相似的目的,这将自动调用str()插值值( num * 2 )。

print(f"Double my favourite number is {num * 2}")

You can print using , instead of + to append values, also consider using f-string :您可以使用,而不是+来打印 append 值,还可以考虑使用f-string

print("Double my favourite number is ", num*2)

Or:或者:

print(f"Double my favourite number is {num*2}")

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

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