Programming fundamentalsLesson 2 of 7 in the course Decisions

Python If and If-Else: Conditions, Branches, and Indentation

5 flashcards · 4 quiz questions · 5 match pairs · 5 fill-in sentences · English

Lesson progress
0 / 5

Your progress is kept in this browser only.Sign up to save it

Summary

Programs often need to choose what to do based on information, just as people decide whether to take an umbrella depending on the weather. In this lesson, you will learn how Python uses if and if-else statements to make decisions.

A condition is an expression that evaluates to either True or False. An if statement uses a condition to decide whether its indented body of statements should run.

All flashcards

What is a condition?
A condition is an expression that evaluates to `True` or `False`. Its result determines which statements a decision structure executes.
What are the parts of an if statement?
An if statement consists of the `if` keyword, a condition, a colon, and an indented body of statements.
How can a Boolean variable be used in an if statement?
Use it directly as the condition, such as `if is_raining:`. This is clearer than comparing it with `True`.
What does an else branch do?
It provides an alternative body that runs when the matching if condition is false. The `else` keyword aligns with `if`, while its body is indented.
What temperature formulas are used for Fahrenheit and Celsius?
Convert Fahrenheit to Celsius with (F−32)×59(F - 32) \times \frac{5}{9}. Convert Celsius to Fahrenheit with C×95+32C \times \frac{9}{5} + 32.

Quiz questions

  1. In Python, what kind of value does a condition evaluate to?Answer: A Boolean value
  2. When an `if` condition is false and there is no `else` branch, what happens to the `if` body?Answer: Python skips it and continues after the `if` statement.
  3. How is `else` aligned relative to its matching `if` statement?Answer: At the same indentation level
  4. In an `if-else` structure, how many of its two branch bodies run for a given condition result?Answer: Exactly one branch body

Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.

All Programming fundamentals lessons