14 Basic Python Exercises with Solutions
The article presents fourteen basic Python programming exercises—including grade classification, a basketball safety algorithm, series summation, shopping‑card combinations, a number‑guessing game, string handling, a recursive duck‑count problem, complex‑number extraction, expression evaluation, number formatting, and others—each accompanied by complete code examples and sample outputs.
1. Grade Classification
Input a percentage score and output grade A‑E using if statements, with validation for unreasonable scores.
<code>a = eval(input('请输入成绩:'))
if a < 0 or a > 100 or a % 1 != 0:
print('您输入的成绩不合理,请检查后重新输入')
elif 90 <= a <= 100:
print('成绩等级:A')
elif 80 <= a <= 89:
print('成绩等级:B')
elif 70 <= a <= 79:
print('成绩等级:C')
elif 60 <= a <= 69:
print('成绩等级:D')
else:
print('成绩等级:E')</code>2. Basketball Safety Algorithm
Determine whether a lead in a basketball game is "safe" based on remaining time, lead points, and ball possession.
<code>grade = eval(input('请输入领先分数:'))
time = eval(input('请输入剩余时间:'))
t = grade - 3
w = input('目前是否为领先队控球(Y or N):')
if w == 'Y' or w == 'y':
g = (t + 0.5) ** 2
else:
g = (t - 0.5) ** 2
if g < 0:
g = 0
if g > time:
print('领先是“安全”的')
else:
print('领先是“不安全”的')
</code>3. Series Sum y = 1+3‑1+3‑1+…+(2n‑1)‑1
Find the maximum n such that y < 3 and the corresponding y value.
<code>x = 1
y = 0
while y < 3:
y = y + 1/(2*x-1)
x = x + 1
print('y<3时的最大n值为{}'.format(x-1))
print('与(1)的n值对应的y值为{}'.format(y-1/(2*x-1)))
</code>4. Shopping Card Combination
Find all ways to spend exactly 100 元 on shampoo (15 元), soap (2 元), and toothbrushes (5 元).
<code>money = 100
n = money // 15
for i in range(n, -1, -1):
m = (money - i*15) // 5
for j in range(m, -1, -1):
k = (money - i*15 - j*5) // 2
if (money - i*15 - j*5) % 2 == 0:
print('可选择的购买组合: 购买洗发水 {} 瓶,香皂 {} 块,牙刷 {}个。'.format(i, j, k))
</code>5. Number Guessing Game
Generate a random integer between 1 and 100; the user has up to 7 attempts to guess it, receiving "High", "Low", or "You won!" feedback, with an option to replay.
<code>chose = 'y'
while chose == 'Y' or chose == 'y':
import random
num = random.randint(1, 100)
def judge(b):
return 1 if b == num else 0
for i in range(1, 8):
b = eval(input('请输入您第{}次所猜的整数:'.format(i)))
if judge(b) == 1:
print('You won !')
break
elif b > num:
print('high')
else:
print('low')
if judge(b) == 0:
print('You lost !')
chose = input('请输入Y(y)继续进行游戏,N(n)退出游戏:')
while chose not in ('Y','y','N','n'):
print('输入有误,请重新输入Y(y)继续进行游戏,N(n)退出游戏:', end='')
chose = input()
</code>6. Ten‑Character String with Index Access
Create a 10‑character string and output the n‑th character, defaulting to the last character for out‑of‑range indices, using try / except .
<code>n = int(input('请输入数字n:'))
a = 'pengyuanyu'
try:
print(a[n-1])
except:
print(a[9])
</code>7. Function for Max, Min, and Average
Read a space‑separated list of numbers and print the maximum, minimum, and average using NumPy.
<code>import numpy as py
x = input('请输入一组数并用空格隔开:')
def f(x):
lis = list(x.split(' '))
for i in range(len(lis)):
lis[i] = eval(lis[i])
print('该组数值的最大值为:', max(lis))
print('该组数值的最小值为:', min(lis))
print('该组数值的平均值为:', py.mean(lis))
f(x)
</code>8. Duck‑Counting Recursion
Calculate the initial number of ducks when after seven villages only two remain, using a recursive function.
<code>def f(n):
if n == 8:
return 2
else:
sum = f(n+1)*2 + 2
return sum
print('一共有{}只鸭子'.format(f(1)))
</code>9. Complex Number Parts
Assign the complex number 2.3103‑1.3410‑3j to variable A and extract its real and imaginary parts.
<code>A = complex(2.3e3, -1.34e-3)
print(A.real)
print(A.imag)
</code>10. Expression Evaluation
Compute the value of a trigonometric expression involving math.sin and math.e .
<code>import math
z1 = (2 * (math.sin(math.pi * 85 / 180))) / (1 + math.e**2)
print(z1)
</code>11. String Operations
Given a 10‑character string, output its length, a sub‑string taking every second character, the reversed string, and a new string combining parts of the original and reversed strings.
<code>A = input()
print(len(A))
B = A[::3]
print(B)
C = A[::-1]
print(C)
D = A[:3] + C[-5:]
print(D)
</code>12. Number Formatting
Format the number 0.002178 as scientific notation, a float with four decimal places, and a percentage, all centered in a width of 10 with * padding.
<code>x = 0.002178
print('x对应的科学表示法形式为:'.center(10, '*'), ('%e' % x).center(10, '*'))
print('x具有4位小数精度的浮点数形式为:'.center(10, '*'), ('{0:.4f}'.format(x)).center(10, '*'))
print('x百分数形式为:'.center(10, '*'), ('{0:.2f}%'.format(x*100)).center(10, '*'))
</code>13. Weekday Lookup
Input a number 1‑7 and output the corresponding weekday name.
<code>n = int(input('输入一个1~7的数字:'))
if n == 1:
print('您输入的是星期一')
elif n == 2:
print('您输入的是星期二')
elif n == 3:
print('您输入的是星期三')
elif n == 4:
print('您输入的是星期四')
elif n == 5:
print('您输入的是星期五')
elif n == 6:
print('您输入的是星期六')
elif n == 7:
print('您输入的是星期日')
</code>14. Four‑Digit Number Encryption
Multiply each digit of a four‑digit integer by 7, keep only the unit digit, and form a new encrypted number.
<code>n = int(input('任意输入1个4位数:'))
if 1000 <= n <= 9999:
a = n % 10
b = (n // 10) % 10
c = (n // 100) % 10
d = (n // 1000) % 10
a = a * 7 % 10
b = b * 7 % 10
c = c * 7 % 10
d = d * 7 % 10
n = 1000*d + 100*c + 10*b + a
print(n)
else:
print('您输入的数字不符合要求,请输入一个四位数字')
</code>This collection of exercises covers fundamental Python concepts such as conditional statements, loops, functions, recursion, string manipulation, numeric formatting, and basic I/O, providing ready‑to‑run code and example outputs for each problem.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.