0

I would like to understand why one program of mine is giving error and one not where as I am applying same concept for both of them.

The program that is giving error:

greeting = "test"
age = 24
print( greeting + age)

Which is true and it should give error because of incompatible variable types being concatenated. But this same behavior I was expecting from the below code as well where as it is giving proper result. Why is it so?

print("Please enter your name: ")
myname = input()
print("Your name is " + myname)

print("Please enter your age: ")
myage = input()
print("Your age is: " + myage)

print("Final Outcome is:")
print(myage + " " + myname)
10
  • The second program has only strings involved. You have the right idea that incompatible types can lead to an error. Commented May 12, 2018 at 4:06
  • input can only return a string because you type characters. It returns '24', not 24. Commented May 12, 2018 at 4:07
  • Do you have python 2 or 3? Because raw_input() in Python 2.x and input() in Python 3.x Commented May 12, 2018 at 4:07
  • Does it mean that value in myage variable is a string variable? Commented May 12, 2018 at 4:08
  • input() reads input as strings only. Commented May 12, 2018 at 4:08

2 Answers 2

2

By default the input function in Python returns a string type. So when you enter the age, it is not being returned to your program as an int but rather a string. So:

print("Your age is: " + myage)

Actually looks like:

print("Your age is: " + "24")
Sign up to request clarification or add additional context in comments.

2 Comments

Great. Thanks for the help. (y)
@GurmeetKaur, if you believe that this, or the other answers, answers your question, please click the green check mark on the left.
0

input() returns a string, even if the user enters a number.

3 Comments

Thanks for the reply. Now, if I want to convert it into numeric value. What should I do? I know about str() which converts numeric to string but how to do vice versa?
for example int(input())
Great. Thank you for the help xhancar. (y)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.