i am learning to code in 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. 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
TypeError: cannot concatenate 'str' and 'int' objects on line 3 in main.py
python
CodePudding user response:
You can print using , instead of to append values, also consider using f-string:
print("Double my favourite number is ", num*2)
Or:
print(f"Double my favourite number is {num*2}")
CodePudding user response:
You're doing fine converting user input from a str to an int
Your only problem is that you're trying to add an int to the return value of 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("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).
print(f"Double my favourite number is {num * 2}")
