学习编程,无论C还是PY都有一些常见的练习程序。比如“Hello world."可以作为初学者所接触的第一个程序,用来认识语言的输入输出。而猜数程序也是大家比较熟悉的。
作为初学者猜数程序写了许多次,最后在多次修改后完成一个比较满意的版本。
好了不罗嗦,上代码:
#python
import random
def guess_game():
secret_numbder = random.randint(1,100)
#secret_number保存1-100之间的随机数
attempt = 0
#attempt保存用户猜数次数
print("Welcome to the guess game!\n")
print("I'm thinking of a number beetween 1 and 100.")
while True:
user_input = input("Enter a number or 'q' to quit: ")
#user_input用来接收用户的输入的字符(串)
if user_input == 'q':
print(f"game over,the answer is {secret_number}.")
break
#break当用户输入字母q时保证退出
try:
guess = int(user_input)
#guess把用户输入的字符(串)转换为数字格式
attempt += 1
#更新attempt的值
if guess < secret_number:
print("too low,try again.")
elif guess > secret_number:
print("too high,try again.")
else:
print("Congratulation! You guessed the number.\n")
print(f"You guessed {secret_number} in {attempt} times.")
break
except ValueError:
#try...except用来处理异常,避免用户输入一些非数字格式的字符
print("Please enter a valid integer.")
guess_game()
还有一点要注意,程序最好不要有猜数次数限制,不然下一轮游戏会保存上次猜数次数的值,换句话说,猜数次数的值在游戏中是不断更新的。另外要注意一定在适当的地方使用break退出程序,避免进入死循环!