3

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.")
mac13k
  • 2,423
  • 23
  • 34
Ann
  • 31
  • 1
  • 2
  • 2
    You are casting the integer to a string to be able to print it, meaning `50` becomes `"50"`. – Jan Jun 20 '20 at 08:52
  • 3
    Does this answer your question? [How can I concatenate str and int objects?](https://stackoverflow.com/questions/25675943/how-can-i-concatenate-str-and-int-objects) – sushanth Jun 20 '20 at 08:52
  • 1
    Precisely the case given in the above link. `+` is mathematical addition for numerical types, but concatenation for string types. Given that you want to join non-numeric strings, you'll need to convert the integer to a string first for python to understand what `+` should do – roganjosh Jun 20 '20 at 08:54
  • There's no integer in you statements, just string. "+" operator here just to concate strings, so you need to use str(age), not age if your age is integer. – Jason Yang Jun 20 '20 at 09:21
  • 1
    do like this: `print(f"he was { age } years old.")` then you can leave it integer – Peyman Majidi Jun 20 '20 at 09:56
  • when using `print` you can separate values with comma, example : `print("He was ", age, " years old.")` – Lwi Jun 20 '20 at 12:40

3 Answers3

3

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

azro
  • 53,056
  • 7
  • 34
  • 70
0

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.

mac13k
  • 2,423
  • 23
  • 34
0

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

ayaz
  • 22
  • 8