for循环语句练习题
计算 1 到 100 的总和
题目描述
编写程序,使用 for 循环计算 1 到 100(包含 100)所有整数的总和。
输出示例
1到100的总和是: 5050
实现代码
# 初始化总和变量为0
total = 0# 使用for循环遍历1到100的所有整数(包含100)
for num in range(1, 101):# 将每个数字累加到总和中total += num# 输出结果
print(f"1到100的总和是: {total}")
统计字符
题目描述
编写一个程序,统计字符串中各种字符的数量(字母、数字、空格、其他字符)。
输入示例
请输入一个字符串: Hello World 123!
输出示例
统计结果:
字母: 10
数字: 3
空格: 2
其他字符: 1
实现代码
# 统计字符
text = input("请输入一个字符串: ")letters = 0
digits = 0
spaces = 0
others = 0for char in text:if char.isalpha():letters += 1elif char.isdigit():digits += 1elif char.isspace():spaces += 1else:others += 1print("统计结果:")
print(f"字母: {letters}")
print(f"数字: {digits}")
print(f"空格: {spaces}")
print(f"其他字符: {others}")水仙花数查找
题目描述
编写程序找出所有的水仙花数(三位数100-999,其各位数字立方和等于该数本身)。
例如:
153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
370 = 3³ + 7³ + 0³ = 27 + 343 + 0 = 370
输出示例
水仙花数有:
153 = 1³ + 5³ + 3³
370 = 3³ + 7³ + 0³
371 = 3³ + 7³ + 1³
407 = 4³ + 0³ + 7³
共有4个水仙花数
实现代码
# 水仙花数查找
print("水仙花数有:")
count = 0
for num in range(100, 1000):# 分解各位数字hundreds = num // 100tens = (num // 10) % 10units = num % 10# 检查是否为水仙花数if hundreds ** 3 + tens ** 3 + units ** 3 == num:print(f"{num} = {hundreds}³ + {tens}³ + {units}³")count += 1print(f"共有{count}个水仙花数")