简体   繁体   中英

Why isn't the code I wrote down working properly?

total_price = 0
sneakers = 36.00

total_price += sneakers

print("Total price is" + " " + str(total_price))

print("Total price is" + " " , total_price) << This one doesn`t work properly. 

Those two statements work like this

Total price is 36.0

('Total price is ', 36.0)

Why is the first and the second different?

use this line for second print

print("Total price is"+" ", total_price, sep='')

since print default to sep=' ' so add extra space while if using + you are concatenating text text in this case (same parameter to printf)

sep is a like a flag passed to print to tell it what character separate different parameters passed to it

This might have to do specifically on python 2. The print syntax on python 2 is

print ...

rather than print(...) in python 3.

So the first one have to do with string concatenation. In your first line of code

"Total price is" + " " + str(total_price)

This will result in a new string of "Total price is" , and " " , and str(total_price) combined. (ie the resulting string is "Total price is 36.0" ). It is equivalent to

x = "Total price is" + " " + str(total_price)
print x

Note that if you insert only a variable between () it will not become a tuple, since tuple needs 2 or more variables. So (x) == x

The second one

("Total price is" + " " , total_price)

is NOT a string concatenation. You used a comma to separate 2 variables. Hence, you inserted two variables and created a tuple, hence results in ('Total price is ', 36.0) .

To make it clear it is equivalent to:

x = ("Total price is" + " ", total_price) #create a tuple
print x

Note that on python 3, this two will print the same output. Since print act more as a function print(...) with arguments.

So, it is not not working properly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM