簡體   English   中英

為什么不使用 print 卻打印字符串?

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

這是我用來學習的 Python 書中的示例程序。 message +=行表示什么? 即使我們從未在那里使用過打印,它如何打印該語句?

這按預期工作並返回$number is too high$number is too low 但是,即使沒有print語句,它又是如何做到的呢?

message += str(guess) +....在這里做什么,因為我們已經在開頭聲明 message 為空字符串( 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")

我嘗試在我的其他腳本之一中使用上述程序中的消息,但它不像在上述程序中那樣打印語句。

input()的調用在其提示中包含message

字符串的添加將它們連接到 Python 中。 "ab" + "cd"產生"abcd" 同樣, message += "stuff""stuff" " 添加到變量早期值的末尾。 如果它之前是空字符串,則"" + "stuff"僅生成"stuff"

運算符+=是一個增量賦值; a += ba = a + b的縮寫。 (有些人也不喜歡較長的表達式,因為它在數學上是不可信的,除非至少有一個值為零;但是=在 Python 的其他任何地方也沒有它的數學語義。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM