16、Python 决策与循环练习解决方案

Python 决策与循环练习解决方案

1. 决策练习解决方案

决策练习主要围绕根据不同条件进行判断并输出相应结果,以下是部分典型练习的解决方案。

1.1 判断奇偶性

判断用户输入的整数是奇数还是偶数,代码如下:

# Determine and display whether an integer entered by the user is even or odd.
# Read the integer from the user
num = int(input("Enter an integer: "))
# Determine whether it is even or odd by using the
# modulus (remainder) operator
if num % 2 == 1:
    print(num, "is odd.")
else:
    print(num, "is even.")

操作步骤:
1. 程序提示用户输入一个整数。
2. 程序接收输入并将其转换为整数类型。
3. 使用取模运算符 % 判断该数除以 2 的余数,若余数为 1 则为奇数,否则为偶数。
4. 输出判断结果。

1.2 判断元音或辅音

判断用户输入的字母是元音还是辅音,代码如下:

# Determine if a letter is a vowel or a consonant.
# Read a letter from the user
letter = input("Enter a letter: ")
# Classify the letter and report the result
if letter == "a" or letter == "e" or \
    letter == "i" or letter == "o" or \
    letter == "u":
    print("It’s a vowel.")
elif letter == "y":
    print("Sometimes it’s a vowel... Sometimes it’s a consonant.")
else:
    print("It’s a consonant.")

操作步骤:
1. 程序提示用户输入一个字母。
2. 程序接收输入的字母。
3. 通过条件判断该字母是否为元音字母( a , e , i , o , u ),若是则输出是元音;若为 y 则输出特殊情况;否则输出是辅音。

1.3 根据边数命名形状

根据用户输入的多边形边数输出其名称,代码如下:

# Report the name of a shape from its number of sides.
# Read the number of sides from the user
nsides = int(input("Enter the number of sides: "))
# Determine the name, leaving it empty if an unsupported number of sides was entered
name = ""
if nsides == 3:
    name = "triangle"
elif nsides == 4:
    name = "quadrilateral"
elif nsides == 5:
    name = "pentagon"
elif nsides == 6:
    name = "hexagon"
elif nsides == 7:
    name = "heptagon"
elif nsides == 8:
    name = "octagon"
elif nsides == 9:
    name = "nonagon"
elif nsides == 10:
    name = "decagon"
# Display an error message or the name of the polygon
if name == "":
    print("That number of sides is not supported by this program.")
else:
    print("That’s a", name)

操作步骤:
1. 程序提示用户输入多边形的边数。
2. 程序接收输入并将其转换为整数类型。
3. 根据边数判断多边形的名称,若边数不在支持范围内则名称为空。
4. 若名称为空则输出错误信息,否则输出多边形的名称。

1.4 根据月份输出天数

根据用户输入的月份输出该月的天数,代码如下:

# Display the number of days in a month.
# Read the month name from the user
month = input("Enter the name of a month: ")
# Compute the number of days in the month
days = 31
if month == "April" or month == "June" or \
    month == "September" or month == "November":
    days = 30
elif month == "February":
    days = "28 or 29"
# Display the result
print(month, "has", days, "days in it.")

操作步骤:
1. 程序提示用户输入月份名称。
2. 程序接收输入的月份名称。
3. 先假设该月有 31 天,然后根据月份判断是否需要更新天数。若为 4 月、6 月、9 月、11 月则更新为 30 天;若为 2 月则更新为 "28 or 29"
4. 输出该月的天数。

1.5 三角形分类

根据用户输入的三角形三条边的长度对三角形进行分类,代码如下:

# Classify a triangle based on the lengths of its sides.
# Read the side lengths from the user
side1 = float(input("Enter the length of side 1: "))
side2 = float(input("Enter the length of side 2: "))
side3 = float(input("Enter the length of side 3: "))
# Determine the triangle’s type
if side1 == side2 and side2 == side3:
    tri_type = "equilateral"
elif side1 == side2 or side2 == side3 or \
    side3 == side1:
    tri_type = "isosceles"
else:
    tri_type = "scalene"
# Display the triangle’s type
print("That’s a", tri_type, "triangle")

操作步骤:
1. 程序提示用户依次输入三角形三条边的长度。
2. 程序接收输入并将其转换为浮点数类型。
3. 根据三条边的长度关系判断三角形的类型,若三边相等则为等边三角形;若有两边相等则为等腰三角形;否则为不等边三角形。
4. 输出三角形的类型。

以下是这些决策练习的总结表格:
| 练习名称 | 功能 | 输入 | 输出 |
| ---- | ---- | ---- | ---- |
| 判断奇偶性 | 判断整数奇偶性 | 整数 | 奇数或偶数 |
| 判断元音或辅音 | 判断字母是元音还是辅音 | 字母 | 元音、辅音或特殊情况 |
| 根据边数命名形状 | 根据边数输出多边形名称 | 边数 | 多边形名称或错误信息 |
| 根据月份输出天数 | 根据月份输出该月天数 | 月份名称 | 天数 |
| 三角形分类 | 根据边长对三角形分类 | 三条边的长度 | 三角形类型 |

2. 循环练习解决方案

循环练习主要涉及使用循环结构处理重复操作,以下是部分典型练习的解决方案。

2.1 无便士计算

计算购买多个物品的总费用,现金交易时将费用四舍五入到最接近的镍币(加拿大已逐步淘汰便士),代码如下:

# Compute the total due when several items are purchased. The amount payable for cash
# transactions is rounded to the closest nickel because pennies have been phased out in Canada.
PENNIES_PER_NICKEL = 5
NICKEL = 0.05
# Track the total cost for all of the items
total = 0.00
# Read the price of the first item as a string
line = input("Enter the price of the item (blank to quit): ")
# Continue reading items until a blank line is entered
while line != "":
    # Add the cost of the item to the total (after converting it to a floating-point number)
    total = total + float(line)
    # Read the cost of the next item
    line = input("Enter the price of the item (blank to quit): ")
# Display the exact total payable
print("The exact amount payable is %.02f" % total)
# Compute the number of pennies that would be left if the total was paid using nickels
rounding_indicator = total * 100 % PENNIES_PER_NICKEL
if rounding_indicator < PENNIES_PER_NICKEL / 2:
    # If the number of pennies left is less than 2.5 then we round down by subtracting that
    # number of pennies from the total
    cash_total = total - rounding_indicator / 100
else:
    # Otherwise we add a nickel and then subtract that number of pennies
    cash_total = total + NICKEL - rounding_indicator / 100
# Display amount due when paying with cash
print("The cash amount payable is %.02f" % cash_total)

操作步骤:
1. 程序提示用户输入物品价格,输入空白行则退出。
2. 程序接收输入的价格并将其转换为浮点数类型,累加到总费用中。
3. 循环重复步骤 1 和 2 直到用户输入空白行。
4. 输出精确的总费用。
5. 计算总费用使用镍币支付时剩余的便士数。
6. 根据剩余便士数进行四舍五入,若剩余便士数小于 2.5 则向下取整,否则向上取整。
7. 输出现金支付时的总费用。

2.2 计算多边形周长

根据用户输入的多边形顶点坐标计算多边形的周长,代码如下:

# Compute the perimeter of a polygon constructed from points entered by the user. A blank line
# will be entered for the x-coordinate to indicate that all of the points have been entered.
from math import sqrt
# Store the perimeter of the polygon
perimeter = 0
# Read the coordinate of the first point
first_x = float(input("Enter the first x-coordinate: "))
first_y = float(input("Enter the first y-coordinate: "))
# Provide initial values for prev x and prev y
prev_x = first_x
prev_y = first_y
# Read the remaining coordinates
line = input("Enter the next x-coordinate (blank to quit): ")
while line != "":
    # Convert the x-coordinate to a number and read the y coordinate
    x = float(line)
    y = float(input("Enter the next y-coordinate: "))
    # Compute the distance to the previous point and add it to the perimeter
    dist = sqrt((prev_x - x) ** 2 + (prev_y - y) ** 2)
    perimeter = perimeter + dist
    # Set up prev x and prev y for the next loop iteration
    prev_x = x
    prev_y = y
    # Read the next x-coordinate
    line = input("Enter the next x-coordinate (blank to quit): ")
# Compute the distance from the last point to the first point and add it to the perimeter
dist = sqrt((first_x - x) ** 2 + (first_y - y) ** 2)
perimeter = perimeter + dist
# Display the result
print("The perimeter of that polygon is", perimeter)

操作步骤:
1. 程序提示用户输入第一个顶点的 x 坐标和 y 坐标。
2. 程序接收输入并将其转换为浮点数类型,记录第一个顶点的坐标。
3. 程序提示用户输入下一个顶点的 x 坐标,输入空白行则退出。
4. 若输入不为空白行,则接收输入的 x 坐标并转换为浮点数类型,再提示用户输入对应的 y 坐标。
5. 计算当前顶点与前一个顶点的距离,并累加到周长中。
6. 更新前一个顶点的坐标为当前顶点的坐标。
7. 循环重复步骤 3 - 6 直到用户输入空白行。
8. 计算最后一个顶点与第一个顶点的距离,并累加到周长中。
9. 输出多边形的周长。

以下是这些循环练习的总结表格:
| 练习名称 | 功能 | 输入 | 输出 |
| ---- | ---- | ---- | ---- |
| 无便士计算 | 计算购买物品总费用并四舍五入 | 物品价格(可多个) | 精确总费用和现金支付总费用 |
| 计算多边形周长 | 根据顶点坐标计算多边形周长 | 顶点坐标(可多个) | 多边形周长 |

通过这些决策和循环练习,可以加深对 Python 中条件判断和循环结构的理解和应用。后续还会有更多有趣的练习和应用等待探索。

mermaid 流程图 - 无便士计算流程:

graph TD;
    A[开始] --> B[初始化总费用为 0];
    B --> C[输入物品价格];
    C --> D{价格是否为空};
    D -- 否 --> E[累加费用];
    E --> C;
    D -- 是 --> F[输出精确总费用];
    F --> G[计算剩余便士数];
    G --> H{剩余便士数 < 2.5};
    H -- 是 --> I[向下取整];
    H -- 否 --> J[向上取整];
    I --> K[输出现金支付总费用];
    J --> K;
    K --> L[结束];

mermaid 流程图 - 计算多边形周长流程:

graph TD;
    A[开始] --> B[输入第一个顶点坐标];
    B --> C[初始化周长为 0];
    C --> D[输入下一个顶点 x 坐标];
    D --> E{坐标是否为空};
    E -- 否 --> F[输入 y 坐标];
    F --> G[计算距离并累加周长];
    G --> H[更新前一个顶点坐标];
    H --> D;
    E -- 是 --> I[计算最后一个顶点与第一个顶点的距离并累加周长];
    I --> J[输出多边形周长];
    J --> K[结束];

Python 决策与循环练习解决方案

3. 更多决策练习解决方案
3.1 音符到频率转换

将用户输入的音符名称转换为其对应的频率,代码如下:

# Convert the name of a note to its frequency.
C4_FREQ = 261.63
D4_FREQ = 293.66
E4_FREQ = 329.63
F4_FREQ = 349.23
G4_FREQ = 392.00
A4_FREQ = 440.00
B4_FREQ = 493.88
# Read the note name from the user
name = input("Enter the two character note name, such as C4: ")
# Store the note and its octave in separate variables
note = name[0]
octave = int(name[1])
# Get the frequency of the note, assuming it is in the fourth octave
if note == "C":
    freq = C4_FREQ
elif note == "D":
    freq = D4_FREQ
elif note == "E":
    freq = E4_FREQ
elif note == "F":
    freq = F4_FREQ
elif note == "G":
    freq = G4_FREQ
elif note == "A":
    freq = A4_FREQ
elif note == "B":
    freq = B4_FREQ
# Now adjust the frequency to bring it into the correct octave
freq = freq / 2 ** (4 - octave)
# Display the result
print("The frequency of", name, "is", freq)

操作步骤:
1. 程序提示用户输入两个字符的音符名称,如 C4。
2. 程序接收输入,将音符和八度分离存储。
3. 根据音符确定其在第四八度的频率。
4. 根据实际八度调整频率。
5. 输出音符对应的频率。

3.2 频率到音符转换

将用户输入的频率转换为对应的音符名称,代码如下:

# Convert the frequency to the name of a note.
C4_FREQ = 261.63
D4_FREQ = 293.66
E4_FREQ = 329.63
F4_FREQ = 349.23
G4_FREQ = 392.00
A4_FREQ = 440.00
B4_FREQ = 493.88
LIMIT = 1
# Read the frequency from the user
freq = float(input("Enter a frequency (Hz): "))
# Determine the note that corresponds to the entered frequency. Set note equal to the empty
# string if there isn’t a match.
if freq >= C4_FREQ - LIMIT and freq <= C4_FREQ + LIMIT:
    note = "C4"
elif freq >= D4_FREQ - LIMIT and freq <= D4_FREQ + LIMIT:
    note = "D4"
elif freq >= E4_FREQ - LIMIT and freq <= E4_FREQ + LIMIT:
    note = "E4"
elif freq >= F4_FREQ - LIMIT and freq <= F4_FREQ + LIMIT:
    note = "F4"
elif freq >= G4_FREQ - LIMIT and freq <= G4_FREQ + LIMIT:
    note = "G4"
elif freq >= A4_FREQ - LIMIT and freq <= A4_FREQ + LIMIT:
    note = "A4"
elif freq >= B4_FREQ - LIMIT and freq <= B4_FREQ + LIMIT:
    note = "B4"
else:
    note = ""
# Display the result, or an appropriate error message
if note == "":
    print("There is no note that corresponds to that frequency.")
else:
    print("That frequency is", note)

操作步骤:
1. 程序提示用户输入频率(Hz)。
2. 程序接收输入并转换为浮点数类型。
3. 判断频率是否在已知音符频率的误差范围内,若在则确定对应的音符名称,否则名称为空。
4. 若名称为空则输出错误信息,否则输出对应的音符名称。

3.3 根据日期确定季节

根据用户输入的月份和日期确定对应的季节,代码如下:

# Determine and display the season associated with a date.
# Read the date from the user
month = input("Enter the name of the month: ")
day = int(input("Enter the day number: "))
# Determine the season
if month == "January" or month == "February":
    season = "Winter"
elif month == "March":
    if day < 20:
        season = "Winter"
    else:
        season = "Spring"
elif month == "April" or month == "May":
    season = "Spring"
elif month == "June":
    if day < 21:
        season = "Spring"
    else:
        season = "Summer"
elif month == "July" or month == "August":
    season = "Summer"
elif month == "September":
    if day < 22:
        season = "Summer"
    else:
        season = "Fall"
elif month == "October" or month == "November":
    season = "Fall"
elif month == "December":
    if day < 21:
        season = "Fall"
    else:
        season = "Winter"
# Display the result
print(month, day, "is in", season)

操作步骤:
1. 程序提示用户输入月份名称和日期。
2. 程序接收输入,将日期转换为整数类型。
3. 根据月份和日期确定对应的季节。
4. 输出日期所在的季节。

3.4 根据年份确定中国生肖

根据用户输入的年份确定对应的中国生肖,代码如下:

# Determine the animal associated with a year according to the Chinese zodiac.
# Read a year from the user
year = int(input("Enter a year: "))
# Determine the animal associated with that year
if year % 12 == 8:
    animal = "Dragon"
elif year % 12 == 9:
    animal = "Snake"
elif year % 12 == 10:
    animal = "Horse"
elif year % 12 == 11:
    animal = "Sheep"
elif year % 12 == 0:
    animal = "Monkey"
elif year % 12 == 1:
    animal = "Rooster"
elif year % 12 == 2:
    animal = "Dog"
elif year % 12 == 3:
    animal = "Pig"
elif year % 12 == 4:
    animal = "Rat"
elif year % 12 == 5:
    animal = "Ox"
elif year % 12 == 6:
    animal = "Tiger"
elif year % 12 == 7:
    animal = "Hare"
# Report the result
print("%d is the year of the %s." % (year, animal))

操作步骤:
1. 程序提示用户输入年份。
2. 程序接收输入并转换为整数类型。
3. 根据年份除以 12 的余数确定对应的生肖。
4. 输出该年份对应的生肖。

以下是这些决策练习的总结表格:
| 练习名称 | 功能 | 输入 | 输出 |
| ---- | ---- | ---- | ---- |
| 音符到频率转换 | 将音符名称转换为频率 | 音符名称 | 频率 |
| 频率到音符转换 | 将频率转换为音符名称 | 频率 | 音符名称或错误信息 |
| 根据日期确定季节 | 根据日期确定季节 | 月份和日期 | 季节 |
| 根据年份确定中国生肖 | 根据年份确定生肖 | 年份 | 生肖 |

4. 更多循环练习解决方案
4.1 判断字符串是否为回文

判断用户输入的字符串是否为回文,代码如下:

# Determine whether or not a string entered by the user is a palindrome.
# Read the string from the user
line = input("Enter a string: ")
# Assume that it is a palindrome until we can prove otherwise
is_palindrome = True
# Check the characters, starting from the ends. Continue until the middle is reached or we have
# determined that the string is not a palindrome.
i = 0
while i < len(line) / 2 and is_palindrome:
    # If the characters do not match then mark that the string is not a palindrome
    if line[i] != line[len(line) - i - 1]:
        is_palindrome = False
    # Move to the next character
    i = i + 1
# Display a meaningful output message
if is_palindrome:
    print(line, "is a palindrome")
else:
    print(line, "is not a palindrome")

操作步骤:
1. 程序提示用户输入一个字符串。
2. 程序接收输入的字符串,假设其为回文。
3. 从字符串两端开始比较字符,若不匹配则标记为非回文。
4. 移动到下一对字符继续比较,直到到达字符串中间或确定不是回文。
5. 输出判断结果。

4.2 显示乘法表

显示 1 到 10 的乘法表,代码如下:

# Display a multiplication table for 1 times 1 through 10 times 10.
MIN = 1
MAX = 10
# Display the top row of labels
print("    ", end="")
for i in range(MIN, MAX + 1):
    print("%4d" % i, end="")
print()
# Display the table
for i in range(MIN, MAX + 1):
    print("%4d" % i, end="")
    for j in range(MIN, MAX + 1):
        print("%4d" % (i * j), end="")
    print()

操作步骤:
1. 确定乘法表的范围为 1 到 10。
2. 显示乘法表的顶部标签行。
3. 逐行显示乘法表,每行包含当前行号和该行的乘法结果。

4.3 计算最大公约数

计算两个正整数的最大公约数,代码如下:

# Compute the greatest common divisor of two positive integers using a while loop.
# Read two positive integers from the user
n = int(input("Enter a positive integer: "))
m = int(input("Enter a positive integer: "))
# Initialize d to the smaller of n and m
d = min(n, m)
# Use a while loop to find the greatest common divisor of n and m
while n % d != 0 or m % d != 0:
    d = d - 1
# Report the result
print("The greatest common divisor of", n, "and", m, "is", d)

操作步骤:
1. 程序提示用户输入两个正整数。
2. 程序接收输入并将其转换为整数类型,初始化 d 为两个数中的较小值。
3. 使用 while 循环,当 n m 不能同时被 d 整除时, d 减 1。
4. 输出两个数的最大公约数。

4.4 十进制转二进制

将用户输入的十进制数转换为二进制数,代码如下:

# Convert a number from decimal (base 10) to binary (base 2).
NEW_BASE = 2
# Read the number to convert from the user
num = int(input("Enter a non-negative integer: "))
# Generate the binary representation of num, storing it in result
result = ""
q = num
# Perform the body of the loop once
r = q % NEW_BASE
result = str(r) + result
q = q // NEW_BASE
# Keep on looping until q is 0
while q > 0:
    r = q % NEW_BASE
    result = str(r) + result
    q = q // NEW_BASE
# Display the result
print(num, "in decimal is", result, "in binary.")

操作步骤:
1. 程序提示用户输入一个非负整数。
2. 程序接收输入并将其转换为整数类型。
3. 初始化结果字符串为空,使用 while 循环,每次取余数并添加到结果字符串的前面,然后将商作为新的被除数。
4. 输出十进制数对应的二进制数。

以下是这些循环练习的总结表格:
| 练习名称 | 功能 | 输入 | 输出 |
| ---- | ---- | ---- | ---- |
| 判断字符串是否为回文 | 判断字符串是否为回文 | 字符串 | 是否为回文的判断结果 |
| 显示乘法表 | 显示 1 到 10 的乘法表 | 无 | 乘法表 |
| 计算最大公约数 | 计算两个正整数的最大公约数 | 两个正整数 | 最大公约数 |
| 十进制转二进制 | 将十进制数转换为二进制数 | 非负整数 | 二进制数 |

通过这些丰富的决策和循环练习,我们可以更深入地掌握 Python 编程中的条件判断和循环结构,提高编程能力和解决实际问题的能力。

mermaid 流程图 - 判断字符串是否为回文流程:

graph TD;
    A[开始] --> B[输入字符串];
    B --> C[假设为回文];
    C --> D[初始化索引 i 为 0];
    D --> E{i < 字符串长度 / 2 且为回文};
    E -- 是 --> F{字符是否匹配};
    F -- 否 --> G[标记为非回文];
    F -- 是 --> H[i 加 1];
    H --> E;
    E -- 否 --> I{是否为回文};
    I -- 是 --> J[输出是回文];
    I -- 否 --> K[输出不是回文];
    J --> L[结束];
    K --> L;

mermaid 流程图 - 十进制转二进制流程:

graph TD;
    A[开始] --> B[输入非负整数];
    B --> C[初始化结果字符串为空];
    C --> D[取余数添加到结果字符串前];
    D --> E[更新商];
    E --> F{商是否为 0};
    F -- 否 --> D;
    F -- 是 --> G[输出二进制数];
    G --> H[结束];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值