python3 try-catch def function



假设您正在编写控制速度的软件吊扇的#。用户修改风扇的转速#拉绳子。拉动绳子会增加风扇的=#speed乘以1,除非它已经达到最大速度。如果#它已经达到了最大速度,它改变了速度#回到0。#编写一个名为pullString的函数。pullString应该取两个参数:当前速度和最大速度#整数。pullString应该返回新的风扇转速#根据上面的推理。

#You may assume that the input will be integers. You should
#also assume that the fan's speed *can* equal the maximum
#speed, but it *cannot* exceed the maximum speed. You may
#thus assume that you will never be given a currentSpeed
#higher than maxSpeed.

#Write your function here!

#to fix this problem here are my answer:
def pullString(current_speed,maximum_speed):
try:
if maximum_speed > current_speed:
fan_speed = current_speed+1
return fan_speed
except:
if maximum_speed <= current_speed:
fan_speed = current_speed-current_speed
return fan_speed



print(pullString(2, 5))
print(pullString(4, 5))
print(pullString(7, 7))

#The code below will test your function. It isn't used for
#grading, so you can change or remove it if you'd like. As
#written, these three lines should print 3, 5, and 0.

#the output was 3 and 5 and none #my problem with word None .it should print 3 5 0 not none

输出None的原因是当current_speed=7maximum_speed=7时,try块运行,if maximum_speed > current_speed为假。这将导致不返回任何内容(不运行expect块),因此输出将是None

你可以想到的一个解决方案是首先提高当前的速度,如果超过最大速度,则将其赋值为0。

def pullString(current_speed,maximum_speed):
current_speed += 1
if (current_speed==maximum_speed+1):
current_speed = 0
return current_speed
print(pullString(2, 5))
print(pullString(4, 5))
print(pullString(7, 7))

另一个更短的解决方案是使用modulo:

def pullString(current_speed,maximum_speed):
return (current_speed+1)%(maximum_speed+1)
print(pullString(2, 5))
print(pullString(4, 5))
print(pullString(7, 7))

最新更新