Sure! Here's an example of a number guessing game written in Python:
import random
def guess_number(num):
guess = int(input("猜一个数字:"))
if guess == num:
print("恭喜你,猜对了!")
elif guess < num:
print("猜的数字太小了!")
guess_number(num)
else:
print("猜的数字太大了!")
guess_number(num)
# 生成一个1到100之间的随机数作为答案
answer = random.randint(1, 100)
guess_number(answer)
This program generates a random number between 1 and 100 and asks the user to guess it. If the guess is correct, it prints a congratulatory message. If the guess is too small, it prompts the user to guess again with a larger number. If the guess is too large, it prompts the user to guess again with a smaller number.
To run this code, you can save it in a file with a .py
extension (e.g., guessing_game.py
) and then run it from the command line using python guessing_game.py
. The program will then ask you to input a number and provide feedback based on your guess.