繁体   English   中英

使用print语句在Python中显示变量值?

[英]Display Variable value in Python using print Statement?

我创建了一个Python程序,该程序可以猜测程序员想到的数字。 一切都在工作文件中,但是我不知道如何在打印语句中使用猜测,以及打印语句显示数字的方式。 我尝试添加单词“ guess”,但是它不起作用。 我是C程序员,并且是第一次使用Python,所以我无法弄清楚。

hi = 100
lo = 0
guessed = False 

print ("Please think of a number between 0 and 100!")

while not guessed:
    guess = (hi + lo)/2
print ("Is your secret number " + //Here i need to Display the guessed Number + "?")
user_inp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too"
                     "low. Enter 'c' to indicate I guessed correctly: ")

if user_inp == 'c':
    guessed = True
elif user_inp == 'h':
    hi = guess
elif user_inp == 'l':
    lo = guess
else:
    print ("Sorry, I did not understand your input.")

print ("Game over. Your secret number was: " + //Here i need to display final number saved in guess.)

只需将其转换为字符串即可。

print ("Game over. Your secret number was: " + str(guess))

您也可以使用字符串格式。

print("Game over. Your secret number was {}".format(guess))

或者,由于您来自C背景,因此采用了老式的字符串格式。

print("Game over. Your secret number was %d." % guess)

在您的印刷声明中尝试此操作,让我知道它是否有效。

str(guess)

Python具有非常好的字符串格式,当您需要插入多个变量时,它很方便:

message = "Game over after {n} guesses.  Your number was {g} (pooh... got it in {n} times)".format(g=guess, n=number)
print(message)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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