简体   繁体   中英

Why is a string printed although print isn't used?

This is an example program from the Python book that I am using to learn. What does the message += line signify? And how does it print that statement even though we've never used a print there?

This works as expected and returns $number is too high or $number is too low . But how does it do so even without print statement?

And what does message += str(guess) +.... do here, given that we've declared message as an empty string in the beginning ( message = "" )?

import random # We cover random numbers in the
rng = random.Random() 

number = rng.randrange(1, 1000) 

guesses = 0
message = ""

while True:
    guess = int(input(message + "\nGuess my number between 1 and 1000:")) 
    guesses += 1
    if guess > number:
        message += str(guess) + " is too high.\n" 
    elif guess < number:
        message += str(guess) + " is too low.\n" 
    else:
        break
input("\n\nGreat, you got it in "+str(guesses)+" guesses!\n\n")

I tried using message like in the above program in one of my other scripts and it doesn't print statement like it does in the above program.

The call to input() includes message in its prompt.

Addition of strings concatenates them in Python. "ab" + "cd" produces "abcd" . Similarly, message += "stuff" adds "stuff" to the end of the variable's earlier value. If it was the empty string before, "" + "stuff" produces simply "stuff" .

The operator += is an increment assignment; a += b is short for a = a + b . (Some people also dislike the longer expression because it is mathematically implausible unless at least one of the values is zero; but = does not have its mathematical semantics anywhere else in Python, either.)

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