Python编程实例合集

54、展示歌曲《十二天的圣诞节》的完整歌词。

以下是实现展示歌曲《十二天的圣诞节》完整歌词的Python代码:

from int_ordinal import intToOrdinal

## Display one verse of The Twelve Days of Christmas
# @param n the verse to display
# @return (None)
def displayVerse(n):
    print("On the", intToOrdinal(n), "day of Christmas")
    print("my true love sent to me:")
    if n >= 12:
        print("Twelve drummers drumming,")
    if n >= 11:
        print("Eleven pipers piping,")
    if n >= 10:
        print("Ten lords a - leaping,")
    if n >= 9:
        print("Nine ladies dancing,")
    if n >= 8:
        print("Eight maids a - milking,")
    if n >= 7:
        print("Seven swans a - swimming,")
    if n >= 6:
        print("Six geese a - laying,")
    if n >= 5:
        print("Five golden rings,")
    if n >= 4:
        print("Four calling birds,")
    if n >= 3:
        print("Three French hens,")
    if n >= 2:
        print("Two turtle doves,")
    if n >= 1:
        if n > 1:
            print("And a partridge in a pear tree.")
        else:
            print("A partridge in a pear tree.")
    print()

# Call the function 12 times to display all verses
for i in range(1, 13):
    displayVerse(i)

这段代码定义了一个 displayVerse 函数,用于显示歌曲的某一特定 verse(节)。然后通过一个循环调用该函数 12 次,从第 1 节到第 12 节,从而展示出完整的歌词。需要注意的是,代码中使用了 int_ordinal 模块里的 intToOrdinal 函数,你需要确保这个模块和函数是可用的,它的作用是将整数转换为对应的序数词(如 1 转换为“first”)。

55、在特定宽度内居中显示一串字符。

以下是实现该功能的代码:

# Center a string of characters within a certain width.
WIDTH = 80

# Create a new string that will be centered within a given width when it is printed.
# @param s the string that will be centered
# @param width the width in which the string will be centered
# @return a new copy of s that contains the leading spaces needed to center s
def center(s, width):
    # If the string is too long to center, then the original string is returned
    if width < len(s):
        return s
    # Compute the number of spaces needed and generate the result
    spaces = (width - len(s)) // 2
    result = " " * spaces + s
    return result

# Demonstrate the center function
def main():
    print(center("A Famous Story", WIDTH))
    print(center("by:", WIDTH))
    print(center("Someone Famous", WIDTH))
    print()
    print("Once upon a time...")

# Call the main function
main()

该代码定义了一个 center 函数,用于将字符串 s 在指定宽度 width 内居中显示。如果字符串长度超过宽度,则返回原字符串;否则,计算需要的空格数并添加到字符串前面。最后,通过 main 函数演示了该功能。

56、判断用户输入的字符串是否为整数。

要实现判断用户输入的字符串是否为整数的功能,可以编写一个 isInteger 函数。以下是实现该功能的Python代码:

# 定义 isInteger 函数
def isInteger(s):
    # 去除字符串首尾的空白字符
    s = s.strip()
    # 如果字符串为空,不是有效的整数
    if len(s) == 0:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值