0

How can I print out the following sentence

"The temperature is 30"

such that 30 is changeable? In other word, I wrote:

temp = 30 
print (The temperature is "+ repr(temp)")


print "The temperature is "+ repr (temp)"

But the system says syntax error.

What is a correct way of writing this?

m00am
  • 5,910
  • 11
  • 53
  • 69
nerd
  • 103
  • 1
  • Welcome to SO. Please add the complete syntax error to your question. Without it we can only guess and the question might get closed as off-topic. Also: Are you sure this is BASIC? This looks an awful lot like Python to me. – m00am Jul 06 '16 at 08:47

1 Answers1

2

Note: I am assuming you are writing a python program here, as your code does not look like basic code at all. The following has been tested using Python3 but might also work on Python2.


Your string delimiters are all over the place. Everything between the double quotes (") will be treated as a string. As a quick fix you have to move double quotes like this:

print ("The temperature is "+ repr(temp))

Then "The temperature is " is a string and the result of repr(temp) is appended to it. Right now "+ repr(temp)" is interpreted as a string and The temperature is are treated as variables, which have not been defined. Hence the error.

For a little more detail, let's walk through this:

temp = 30 # sets an variable to 30 (integer)
text = "this is a string" + str(temp) # convert temp variable to string
                                      # append it to the string and store it
                                      # in the variable named text
print(text) # print the combined text

Note that str and repr do slightly different things:

  • str(x) returns a readable string version of the variable x
  • repr(x) returns an unambiguous string that is often used in interpreters etc.

In general you want to use str for tasks like this. For more information about this take a look at this post.

Community
  • 1
  • 1
m00am
  • 5,910
  • 11
  • 53
  • 69