Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert strings and variables into print statements?

Tags:

python

I am trying to program something that will display the variable that I wrote earlier in a print statement but whenever I run the code it doesn't display the variable, it just says "None".

My code:

sidewalkclosed = True
raining = True
xPos = 400
yPos = 400
print("Your robot is located at",print(yPos),"on the y axis and",print(xPos),"on the x 
axis.")
like image 224
Killjoy Avatar asked Nov 01 '25 01:11

Killjoy


2 Answers

Try this.

sidewalkclosed = True
raining = True
xPos = 400
yPos = 400
print("Your robot is located at",yPos,"on the y axis and",xPos,"on the x 
axis.")
#### or ####
print(f"Your robot is located at {yPos} on the y axis and {xPos} on the x 
axis.")
# More Ways
#### or ####
print("Your robot is located at {} on the y axis and {} on the x axis.".format(yPos,xPos))

#### or ####
print("Your robot is located at %d on the y axis and %d on the x axis." % (yPos,xPos))
# Here %d (Or %i) for integer and for string type you can use %s.
# And for float you can use (%f,%e,%g) and more.

ERROR

Here you got None Instead of 400 and 400 this is because the print function returns None.


Execution Of Your Code.


print("Your robot is located at",print(yPos),"on the y axis and",print(xPos),"on the x 
axis.")

OUTPUT From Your Code

400
400
Your robot is located at None on the y axis and None on the x axis.

In this code when the print function read the input he got print(yPos) and print(xPos) He runs those two print functions and capture the returning value Which is None.

like image 116
Sharim09 Avatar answered Nov 02 '25 16:11

Sharim09


I would recommend using f strings -

print(f"Your robot is located at {yPos} on the y axis and {xPos} on the x axis")
like image 29
Manu Manjunath Avatar answered Nov 02 '25 14:11

Manu Manjunath