跳到主要内容

Hello World与基础练习

动手写代码,巩固基础知识

第一个程序

Hello World

# hello.py
print("Hello, World!")
print("你好,世界!")
print("开始我的编程之旅!")

运行:

python hello.py

为什么是Hello World

  • 编程界的传统(源于1978年《C程序设计语言》)
  • 验证环境配置正确
  • 最简单的起点

基础练习题

练习1:个人信息

# 输出你的个人信息
name = "你的名字"
age = 20
city = "你的城市"
hobby = "你的爱好"

print(f"大家好,我是{name}")
print(f"今年{age}岁,来自{city}")
print(f"我的爱好是{hobby}")

练习2:简单计算

# 计算两个数的和、差、积、商
a = 15
b = 4

print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} × {b} = {a * b}")
print(f"{a} ÷ {b} = {a / b:.2f}")
print(f"{a} 整除 {b} = {a // b}")
print(f"{a} 取余 {b} = {a % b}")

练习3:用户输入

# 获取用户输入并问候
name = input("请输入你的名字:")
print(f"你好,{name}!欢迎学习Python!")

练习4:温度转换

# 摄氏度转华氏度
celsius = float(input("请输入摄氏温度:"))
fahrenheit = celsius * 9/5 + 32
print(f"{celsius}°C = {fahrenheit}°F")

练习5:判断奇偶

# 判断一个数是奇数还是偶数
num = int(input("请输入一个整数:"))

if num % 2 == 0:
print(f"{num}是偶数")
else:
print(f"{num}是奇数")

条件判断练习

练习6:成绩等级

score = int(input("请输入分数(0-100):"))

if score >= 90:
grade = "优秀 A"
elif score >= 80:
grade = "良好 B"
elif score >= 70:
grade = "中等 C"
elif score >= 60:
grade = "及格 D"
else:
grade = "不及格 F"

print(f"成绩等级:{grade}")

练习7:闰年判断

year = int(input("请输入年份:"))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year}年是闰年")
else:
print(f"{year}年不是闰年")

练习8:三角形判断

a = float(input("边a:"))
b = float(input("边b:"))
c = float(input("边c:"))

if a + b > c and a + c > b and b + c > a:
print("可以构成三角形")
if a == b == c:
print("这是等边三角形")
elif a == b or b == c or a == c:
print("这是等腰三角形")
else:
print("这是普通三角形")
else:
print("不能构成三角形")

循环练习

练习9:九九乘法表

for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print()

输出:

1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
...

练习10:求和

# 计算1到100的和
total = 0
for i in range(1, 101):
total += i
print(f"1到100的和是:{total}") # 5050

# 一行代码
print(sum(range(1, 101)))

练习11:阶乘

n = int(input("请输入n:"))
factorial = 1

for i in range(1, n + 1):
factorial *= i

print(f"{n}! = {factorial}")

练习12:斐波那契数列

n = int(input("输出前n个斐波那契数:"))

a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
print()

练习13:打印图形

# 直角三角形
n = 5
for i in range(1, n + 1):
print("*" * i)

# 倒三角
for i in range(n, 0, -1):
print("*" * i)

# 金字塔
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))

函数练习

练习14:判断质数

def is_prime(n):
"""判断是否为质数"""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# 测试
for i in range(1, 20):
if is_prime(i):
print(i, end=" ")
# 2 3 5 7 11 13 17 19

练习15:最大公约数

def gcd(a, b):
"""求最大公约数(辗转相除法)"""
while b:
a, b = b, a % b
return a

print(gcd(48, 18)) # 6

练习16:回文判断

def is_palindrome(s):
"""判断是否为回文"""
s = s.lower().replace(" ", "")
return s == s[::-1]

print(is_palindrome("level")) # True
print(is_palindrome("hello")) # False
print(is_palindrome("A man a plan a canal Panama")) # True

列表练习

练习17:列表操作

# 创建学生成绩列表
scores = [85, 92, 78, 95, 88, 76, 90]

# 统计
print(f"总人数:{len(scores)}")
print(f"最高分:{max(scores)}")
print(f"最低分:{min(scores)}")
print(f"平均分:{sum(scores)/len(scores):.2f}")

# 排序
sorted_scores = sorted(scores, reverse=True)
print(f"排名:{sorted_scores}")

# 筛选及格
passed = [s for s in scores if s >= 60]
print(f"及格人数:{len(passed)}")

练习18:去重排序

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# 去重并排序
unique_sorted = sorted(set(numbers))
print(unique_sorted) # [1, 2, 3, 4, 5, 6, 9]

字典练习

练习19:词频统计

text = "apple banana apple cherry banana apple"
words = text.split()

# 统计词频
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1

print(word_count) # {'apple': 3, 'banana': 2, 'cherry': 1}

# 或用Counter
from collections import Counter
print(Counter(words))

练习20:学生管理

students = {
"001": {"name": "张三", "score": 85},
"002": {"name": "李四", "score": 92},
"003": {"name": "王五", "score": 78}
}

# 遍历
for sid, info in students.items():
print(f"{sid}: {info['name']} - {info['score']}分")

# 找最高分
top = max(students.items(), key=lambda x: x[1]["score"])
print(f"最高分:{top[1]['name']}")

综合练习

练习21:石头剪刀布

import random

choices = ["石头", "剪刀", "布"]

while True:
user = input("请出拳(石头/剪刀/布)或输入q退出:")
if user == "q":
break
if user not in choices:
print("无效输入")
continue

computer = random.choice(choices)
print(f"电脑出:{computer}")

if user == computer:
print("平局!")
elif (user == "石头" and computer == "剪刀") or \
(user == "剪刀" and computer == "布") or \
(user == "布" and computer == "石头"):
print("你赢了!")
else:
print("你输了!")

练习22:简单通讯录

contacts = {}

while True:
print("\n===== 通讯录 =====")
print("1. 添加联系人")
print("2. 查找联系人")
print("3. 显示所有")
print("4. 删除联系人")
print("5. 退出")

choice = input("请选择:")

if choice == "1":
name = input("姓名:")
phone = input("电话:")
contacts[name] = phone
print("添加成功!")
elif choice == "2":
name = input("输入姓名:")
if name in contacts:
print(f"{name}: {contacts[name]}")
else:
print("未找到")
elif choice == "3":
for name, phone in contacts.items():
print(f"{name}: {phone}")
elif choice == "4":
name = input("输入姓名:")
if name in contacts:
del contacts[name]
print("删除成功!")
else:
print("未找到")
elif choice == "5":
print("再见!")
break

本章小结

通过这些练习,你应该掌握了:

  1. 基础语法:变量、输入输出、运算符
  2. 条件判断:if-elif-else
  3. 循环:for、while
  4. 函数:定义和调用
  5. 数据结构:列表、字典
  6. 综合应用:小程序开发

下一步

做完基础练习,下一章开发一个完整的计算器项目。

→ 继续阅读:26-计算器项目实战