Issue
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
Solution
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))
Answered By - 3kt Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.