user3437460 user3437460 - 3 months ago 7
Python Question

How to print an incremented int identifier in a string in Python

In Java, If I want to print an incremented int variable, I can do it as:

int age = scn.nextInt();
System.out.println("You are " + age + " years old going on " + (age+1));


Output:

21
You are 21 years old going on 22


Is it possible to do the same in Python?

I tried the following, and none of them work.

age = input("How old are you?")
print("You are " + age + " years old going on " + str(age+1))
print("You are " + age + " years old going on {}".format(age+1))
print("You are " , age , " years old going on " , str(age+1))
print("You are %d years old going on %d" %(age, age+1))
print("You are " + str(age) + " years old going on " + str(age+1))


I have already tried the solutions provided in these links:

Print Combining Strings and Numbers

Concatenating string and integer in python

Converting integer to string in Python?

TypeError: Can't convert 'int' object to str implicitly

3kt 3kt
Answer

You need to convert the input to an int :

>>> age = int(input("How old are you?"))

And then the following work :

print("You are " , age , " years old going on " , str(age+1))
print("You are %d years old going on %d" %(age, age+1))
print("You are " + str(age) + " years old going on " + str(age+1))