liveBook · Manning

Boolean context

As explained in Python Workout: 50 ten-minute exercises

A Python evaluation context in which an object's truth value determines conditional or logical behavior.

Python uses an object's truth value when an expression appears in a conditional or logical position. For user input, an empty string is false, so `if not city_name` means “if the city name is empty.” section 4.9

Stopping on empty input

A rainfall collector can repeatedly ask for a city and stop when the user submits an empty response: ```python while True: city_name = input("City: ") if not city_name: break mm_rain = int(input("Enter mm rain: ")) rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain ``` The `not` operator reverses the string's Boolean value: a nonempty city name continues the loop, while an empty one exits it. section 4.9

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines empty strings as false and demonstrates `not` in a loop, without expanding beyond string truth testing.
Examples
Demonstrates an empty city name terminating a rainfall loop and a nonempty name updating a dictionary.
What it assumes
Assumes familiarity with Python conditionals, loops, strings, input, and dictionaries.
What you can do after
Apply Boolean context to detect empty input and choose whether a loop continues or exits.
How it connects
Connects Boolean context with conditionals, logical negation, loops, strings, user input, and dictionaries.

Also explained in

Compare how 2 books explain boolean context →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.