Question:
How do you include variables into python strings?
Matthew
2013-03-25 10:57:58 UTC
Here is my code:

#exponents.py
#Finds powers.

a=input("Type in a base number.")
b=input("Type in an exponent.")
print("Would you like to calculate", a "to the power of", b "? 1 is yes and 5 is no.")
answer=raw_input()
if(answer<2):
print a**b
if(answer>4):
print("OK! No powers for you! :P")

I am new to Python and when I try to run the program, it says that there is an invalid syntax at the brackets(Not in the actual code). I think it has to do with the variables. Also, I am on Python 2.


print("Would you like to calculate", a "to the power of["], b "? 1 is yes and 5 is no.")
Three answers:
oops
2013-03-25 11:26:07 UTC
You can use string substitution, like this:



    print("Would you like to calculate %s to the power of %s? 1 is yes and 5 is no" % (a, b))



Or you can use concatenation. Just be sure you convert your variables to strings:



    print("Would you like to calculate" + str(a) + " to the power of " + str(b) + "? 1 is yes and 5 is no")
griglik
2016-11-05 17:30:43 UTC
Chris, your answer is nice yet i think it to be incorrect. no longer all languages behave like this. i'm sorry yet there's no hassle-free answer. Strings in python are products. So once you assign an merchandise you're easily assigning a pointer to the article and not shifting the archives. interior the assertion First = "pie" you're coming up a string "pie" someplace in memory. you're then making the variable First element to that string. Now the compicated bit 2d = First The variable 2d isn't pointing to the variable First. What you're doing is make 2d element to the archives that First is pointing at. this is the string "pie". Now you alter First First = "Sir Francis Bacon" returned you're coming up a string in memory someplace and making the variable First element to it. yet via fact the variable 2d continues to be pointing to the string "pie" it is going to no longer substitute. in case you probably did no longer have the variable 2d, the string "pie" could be lost in memory and could purely be released by ability of rubbish series via fact the rubbish collector could notice that there have been no hyperlinks to it. i'm sorry if this is purely too lots so which you would be able to appreciate. have relaxing.
yahooogle
2013-03-25 11:28:37 UTC
invalid syntax occurred at print statement.due to string not properly handle.



use following



print("Would you like to calculate"+str(a)+"to the power of["+str(b)+"]? 1 is yes and 5 is no.")



to concat variable of type integer by casting into string .


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...