πŸ–₯️
Berkeley CS61A: Notes
  • 🌍Hello, World!
  • πŸ’­Learn to Think Like Your Computer
  • Building Blocks
    • ❗Expressions in Python
      • ℹ️Mathematical Statements
      • 🀫Variables
      • πŸ‘Data Types in Python
    • 🚧Introduction to Functions
      • πŸƒβ€β™€οΈHow Python Executes a Function Call
      • 🚱Functions that Don't Return Anything
    • 🌊Control Flow
      • ⁉️What is an if statement?
      • πŸ’ΎWhat is a Loop?
      • 🚨What are Logical Operators?
        • πŸ˜–Logical Operators, Seemingly Illogical Behavior
      • 🚰How Does Control Flow?
    • ⚑Higher-Order Functions
      • ⏸️What are Higher-Order Functions Used For?
      • πŸ‘†Self-Reference
    • πŸ‘ΎEnvironments and Scope
      • πŸ–ŠοΈHow to Make Environment Diagrams
  • STRUCTURES OF DATA
    • ➰Recursion
      • πŸ«€Anatomy of Recursion
      • β›½Recursive Leap of Faith
    • πŸŽ„Tree Recursion
      • ⬇️The Use It/Lose It Principle
    • πŸ“€Iterables
      • βœ‚οΈList Slicing
      • πŸ’€Deep Lists
      • πŸŒ‹Iterable Functions
      • πŸ’½List Comprehensions
    • πŸ™ˆAbstraction
    • Trees
    • Linked Lists
    • Iterators and Generators
    • Efficiency
  • Extra Topics
    • 🎭Errors and their Types
      • 🏹Error vs Exception
      • πŸ”™What is Backtracing?
    • 🚑How the Terminal and the File are Different
    • 🍬Decorators
  • Debugging Tools
    • πŸ–¨οΈDebugging with Print Statements
    • πŸ›Debugging with the Debugger
Powered by GitBook
On this page

Was this helpful?

  1. Building Blocks
  2. Control Flow

What is an if statement?

Conditional execution.

PreviousControl FlowNextWhat is a Loop?

Last updated 3 years ago

Was this helpful?

As it stands right now, we've seen Python as a series of statements that we execute one after another. However, we may wish to, on occasion, conditionally execute a piece of code. For example, if a variable a is set to 1, we want to print "Hello!", print "World!" if it is set to 2, or print "Bye" otherwise. We can do so through if statements.

if (a == 1):
    print("Hello!")
elif (a == 2):
    print("World!")
else:
    print("Bye")

In an if-else block, Python will only ever execute one suite of statements.

Something fascinating happens in if-statements. Not only does Python not run the statements for which the condition is not True, it does not even execute them β€”Β errors are ignored. Consider the following:

a = 1
if (a == 1):
    print("Hello!")
else:
    print(1/0)

This code does not error, because Python never ends up reading the else-block β€”Β the condition is True, and the if suite is executed instead.

Evaluating if Statement Conditions

In our section on , we had talked about truth-y and false-y values. If conditions basd on such values check for their truthiness or falsiness by the same design. For example

if a:
    print("Hello")
else:
    print("World")

Setting a=1 would print Hello, while setting a=0 would print World.

🌊
⁉️
Data Types