用 Python 写一个猜数字游戏并运行它

简介: 用 Python 写一个猜数字游戏并运行它

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.

相关文章
|
1月前
|
存储 NoSQL Redis
在Python Web开发过程中,为什么Redis运行速度快
【5月更文挑战第15天】Redis在Python Web开发中运行速度快,原因包括:1) 丰富数据类型满足多样化需求;2) 简单数据模型提升查询效率;3) 单线程模型结合非阻塞I/O实现高效处理;4) 持久化机制保证数据安全;5) 二进制协议与管道技术优化网络通信。这些因素共同确保Redis能处理大量请求并保持高性能。
53 1
|
20天前
|
Linux 数据库管理 Python
CentOS7编译安装Python3.10(含OpenSSL1.1.1安装),创建虚拟环境,运行Django项目(含sqlite版本报错)
CentOS7编译安装Python3.10(含OpenSSL1.1.1安装),创建虚拟环境,运行Django项目(含sqlite版本报错)
123 4
|
1月前
|
数据可视化 Python
六种酷炫Python运行进度条
六种酷炫Python运行进度条
|
1天前
|
Java API 开发工具
如何将python应用编译到android运行
【6月更文挑战第27天】本文介绍在Ubuntu 20上搭建Android开发环境,包括安装JRE/JDK,设置环境变量,添加i386架构,安装依赖和编译工具。并通过`p4a`命令行工具进行apk构建和清理。
20 6
如何将python应用编译到android运行
|
13天前
|
Shell Python
GitHub星标破千Star!Python游戏编程的初学者指南
Python 是一种高级程序设计语言,因其简洁、易读及可扩展性日渐成为程序设计领域备受推崇的语言。 目前的编程书籍大多分为两种类型。第一种,与其说是教编程的书,倒不如说是在教“游戏制作软件”,或教授使用一种呆板的语言,使得编程“简单”到不再是编程。而第二种,它们就像是教数学课一样教编程:所有的原理和概念都以小的应用程序的方式呈现给读者。
|
14天前
|
JavaScript 前端开发 Linux
pipx — 在隔离环境中安装和运行 Python 应用程序
pipx — 在隔离环境中安装和运行 Python 应用程序
|
14天前
|
Python
【Python的魅力】:利用Pygame实现游戏坦克大战——含完整源码
【Python的魅力】:利用Pygame实现游戏坦克大战——含完整源码
|
19天前
|
算法 数据挖掘 开发者
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
|
1月前
|
数据采集 数据挖掘 关系型数据库
Python游戏篇:细节之大型游戏爆炸效果(附代码)_“python大型游戏代码”
Python游戏篇:细节之大型游戏爆炸效果(附代码)_“python大型游戏代码”
Python游戏篇:细节之大型游戏爆炸效果(附代码)_“python大型游戏代码”
|
23天前
|
算法 JavaScript 前端开发
【经典算法】LCR187:破冰游戏(约瑟夫问题,Java/C/Python3/JavaScript实现含注释说明,Easy)
【经典算法】LCR187:破冰游戏(约瑟夫问题,Java/C/Python3/JavaScript实现含注释说明,Easy)
21 1