pyhton学习总结:Booleans and Conditionals

**

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

  1. 🌶️
    In the main lesson we talked about deciding whether we’re prepared for the weather. I said th
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值