I just learnt that there is no quotation for integer in Python, but why is it needed in this case:
character_name = "Tom"
age = "50"
print("There once was a man named " + character_name + ",")
print("he was " + age + " years old.")
I just learnt that there is no quotation for integer in Python, but why is it needed in this case:
character_name = "Tom"
age = "50"
print("There once was a man named " + character_name + ",")
print("he was " + age + " years old.")
Using quotes to a digit, makes him become a string
when it was an int
(or float
) so it changes its values, you cannot do numerical operation on it anymore.
What you may need is the string representation of a number when concatenating it with other strings, here you may do
print("he was " + str(age) + " years old.")
Or, let print do it, by giving several parameters, and each one will be given its string representation
print("he was", age, "years old.")
In resume, don't add quotes to a number when assigning it because it won't be a number anymore, handle it differently when you need but not as its beginning
You do not really need to do it if you use the format()
method in Python 3, ie.:
character_name = "Tom"
age = 50
print("There once was a man named {}, he was {} years old.".format(character_name), age)
This is better in case you need to use the variable age
in some equation later in the code.
when you use 2 strings and a “+” you concate them but when you use 2 numbers and a “+” you summarize them so if you use one string and one number and a “+” it gives you an error so you convert your number to a string
Valid Example 1:
age = 30 name = “John” new_string = name + str(age)
Valid Example 2:
age = “30” name = “John” new_string = age + name
invalid Example:
age = 30 name = “John” new_string = name + age #Throws an issue