How to insert strings and variables into print statements?

Viewed 88

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.")
4 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.

I would recommend using f strings -

print(f"Your robot is located at {yPos} on the y axis and {xPos} on the x axis")

you have put print() inside print() for some reason just change it to

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