az89 az89 - 1 year ago 106
Python Question

input nested inside print statement

Fairly simple question here. I was working on constructing an example of the hello world program which would say hello to a user upon input of their name without using any variables. I have

print('What is your name?')

print('Hello, ' +str(input()) + ', nice to meet you!')

which gives the desired result. Why does the input statement execute ''before'' the print statement despite being nested inside of it? Thanks!

Answer Source

I think, you are not aware of precedence of operators. Here you are using + operator.

print('Hello, ' +str(input()) + ', nice to meet you!')

Here, different operand expressions are made ready, before print is executed. Since str(input()) is a function expression, it must be evaluated first, for the string concatenation to take place.

In other scenarios, such as factorial(sum(2, 3)) will result into factorial(5), as sum(2, 3) will be executed first. In short, the rule of thumb is that inner most expressions are evaluated first from left to right.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download