gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:55:21 25 4
gpt4 key购买 nike

我创建了一个 Python 程序,可以猜测程序员脑子里想的数字。一切都是工作文件,但我不知道如何以打印语句显示数字的方式在打印语句中使用猜测。我尝试添加“猜测”一词,但它不起作用。我是 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)

关于python - 使用 print 语句在 Python 中显示变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22742367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com