Home > Software engineering >  How to enter variable in printed statement?
How to enter variable in printed statement?

Time:08-12

I am going through the python crash course book and I have a question. I apologize if its been asked before. As I work with variables why wont the variable print in my sentence?

car = 'Audi'
print("Is car == 'subaru? I predict True.")
print(car == 'subaru')

print("\nIs car == 'audi'? I predict True")
print(car == car.title())

print("Is car == 'porsche'? I predict false")
car = car.replace('Audi', 'porsche')
print(car == 'porsche')
print(car.title())
print('How much was your (car.title)? I bet it was expensive')
print(" My 'car.title'?")

Prints out the following:

Is car == 'subaru? I predict True.
False

Is car == 'audi'? I predict True
True
Is car == 'porsche'? I predict false
True
Porsche
How much was your (car.title)? I bet it was expensive
 My 'car.title'?

Why does it say car.title instead of porsche? Do I have to define what car is again? I'd appreciate any help that could be offered. Im dedicated to learning the language this time!

CodePudding user response:

Try using:

print("My" ,car.title(), "?")

When you use the string and variable at the same time it should be separated with comma.

CodePudding user response:

Why does it say car.title instead of porsche?

Because car.title is inside the quotation marks.

If I create a variable called name:

name = 'John'

And then I print this:

print('Hello name')

I will get the output "Hello name", because name is inside the quotes.

There are many ways to fix that. The easiest is to put the variable name outside the quotes:

print('Hello', name)

CodePudding user response:

Python take the sentence as string without executing it. If you want to see the execution inside a string, you should use f-string.

For instance, you can change the last line of your code as:

print(f" My {car.title}?")

Then, this line of code will run the command inside the {} and then replace the result into the string (sentence).

  • Related