Python编程技巧与问题解析

29、请向虚拟助手询问‘用一个单一条件重写此语句’。语句为:x是一个正的一位数。

可以向虚拟助手表述为“Rewrite this statement with a single conditional: x is a positive single-digit number.”,对应的单一条件语句可以是:

if 0 < x and x < 10:
    print("x is a positive single-digit number")

或者更简洁的:

if 0 < x < 10:
    print("x is a positive single-digit number")

30、查看虚拟助手能否简化以下不必要的复杂代码:if 0 < x: if x < 10: print(‘x is a positive single - digit number.’)

可以使用逻辑运算符 and 来简化嵌套条件语句,简化后的代码为:

if 0 < x and x < 10:
    print('x is a positive single-digit number.')

此外,Python 还提供了更简洁的写法:

if 0 < x < 10:
    print('x is a positive single-digit number.')

31、下面的递归函数有一个错误,请指出哪里出错了以及如何修复,并对修复后的代码进行测试。函数代码如下:def countdown_by_two(n): if n == 0: print(‘Blastoff!’) else: print(n) countdown_by_two(n-2) countdown_by_two(6)

错误分析

这段递归函数对于输入为偶数时可以正常工作,但是当输入为奇数时会出现问题。因为当输入为奇数时,不断减2最终不会得到0,而是得到一个负数,这样会导致无限递归,最终引发 RecursionError

修复方案

我们需要修改终止条件,使得当 n 小于等于0时都能终止递归。修改后的代码如下:

def countdown_by_two(n):
    if n <= 0:
        print('Blastoff!')
    else:
        print(n)
        countdown_by_two(n - 2)

countdown_by_two(6)
countdown_by_two(7)

测试结果说明

  • 当调用 countdown_by_two(6) 时,输出为 6 4 2 Blastoff! 。代码会先打印出6,然后递归调用自身并传入 n - 2 即4,接着依次打印4和2,当 n 减到0时,打印 Blastoff!
  • 当调用 countdown_by_two(7) 时,输出为 7 5 3 1 Blastoff! 。代码会先打印出7,然后递归调用自身并传入 n - 2 即5,接着依次打印5、3、1,当 n 减到 -1 时,由于 n <= 0 条件满足,打印 Blastoff! ,避免了无限递归。

32、使用整除和取模运算符计算自1970年1月1日以来的天数以及当前一天中的小时、分钟和秒数。已知当前时间戳为1709908595.7334914 。

以下是解决该问题的Python代码:

from time import time

now = 1709908595.7334914

# 计算总秒数
total_seconds = int(now)

# 计算天数
days = total_seconds // (24 * 60 * 60)

# 计算剩余秒数
remaining_seconds = total_seconds % (24 * 60 * 60)

# 计算小时数
hours = remaining_seconds // (60 * 60)

# 计算剩余秒数
remaining_seconds %= (60 * 60)

# 计算分钟数
minutes = remaining_seconds // 60

# 计算秒数
seconds = remaining_seconds % 60

print(f'自1970年1月1日以来的天数: {days
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值