**
Exercises
**
1.
Many programming languages have sign available as a built-in function. Python doesn’t, but we can define our own!
In the cell below, define a function called sign which takes a numerical argument and returns -1 if it’s negative, 1 if it’s positive, and 0 if it’s 0.
# Your code goes here. Define a function called 'sign'
def sign(num):
if num > 0:
num = 1
elif num < 0:
num = -1
else:
num = 0
return num
# Check your answer
q1.check()
Correct
We’ve decided to add “logging” to our to_smash function from the previous exercise.
def to_smash(total_candies):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
print("Splitting", total_candies, "candies")
return total_candies % 3
to_smash(91)
Splitting 91 candies
1
What happens if we call it with total_candies = 1?
to_smash(1)
Splitting 1 candies
1
That isn’t great grammar!
Modify the definition in the cell below to correct the grammar of our print statement. (If there’s only one candy, we should use the singular “candy” instead of the plural “candies”)
def to_smash(total_candies):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
print("Splitting", total_candies, "candy" if total_candies == 1 else "candies")
return total_candies % 3
to_smash(91)
to_smash(1)
Splitting 91 candies
Splitting 1 candy
1
- 🌶️
In the main lesson we talked about deciding whether we’re prepared for the weather. I sai

本文总结了Python中布尔值的使用,并通过实际编程练习来讲解条件表达式的应用,包括自定义sign函数、语法修正、逻辑判断优化等。通过一系列问题解决,加深对Python逻辑表达式和条件判断的理解。
6068

被折叠的 条评论
为什么被折叠?



