【ATBS with Python】Q&A Chap2 If-else and Flow Control

Automate The Boring Stuff with Python

Practice Questions



Chap2 If-else and Flow Control

  1. What are the two values of the Boolean data type? How do you write them?

True and False


  1. What are the three Boolean operators?
    and, or ,not

  1. Write out the truth tables of each Boolean operator (that is, every possible combination of Boolean values for the operator and what they evaluate to).
andTrue and TrueTrue
True and FalseFalse
False and TrueFalse
False and FalseFalse
orTrue or TrueTrue
True or FalseTrue
False or TrueTrue
False and FalseFalse
notnot TrueFalse
not FalseTrue

4. What do the following expressions evaluate to?

(5 > 4) and (3 == 5) : False
not (5 > 4) : False
(5 > 4) or (3 == 5) : True
not ((5 > 4) or (3 == 5)) : False
(True and True) and (True == False) : False
(not False) or (not True) :True

  1. What are the six comparison operators?
    ==, !=, <, >, <=, >=

  1. What is the difference between the equal to operator and the assignment operator?

The equal to operator asks whether two values are the same as each other.

The assignment operator puts the value on the right into the variable on the left


  1. Explain what a condition is and where you would use one.

A condition is a statement or expression that evaluates to either true or false, often used to control the flow of a program. Conditions are commonly used in if statements, loops, and switch cases to determine which code should run based on specific criteria.


  1. Identify the three blocks in this code:
spam = 0
if spam == 10:
    print('eggs')
    if spam > 5:
        print('bacon')
    else:
        print('ham')
    print('spam')
print('Done')
  • Block 1: Outer if Statement
if spam == 10:
    print('eggs')
    if spam > 5:
        print('bacon')
    else:
        print('ham')
    print('spam')

This is the outermost block, controlled by the condition spam == 10. It includes all indented lines beneath it.

  • Block 2: Inner if-else Statement
if spam > 5:
    print('bacon')
else:
    print('ham')

Nested within the first block, this if-else structure checks the condition spam > 5. The indented lines under each clause form sub-blocks within this block.

  • Block 3: Unconditional print Statement
print('Done')

This line is outside all conditional blocks and executes regardless of the conditions above. It is not indented, marking it as separate from the other blocks.


  1. Write code that prints Hello if 1 is stored in spam, prints Howdy if 2 is stored in spam, and prints Greetings! if anything else is stored in spam.
if spam == 1:
    print('Hello')
elif spam == 2:
    print('Howdy')
else: print('Greetings!')
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值