7 Logic and Computational Thinking with Python

A Little More Logical | Brendan Shea, PhD

Embark on an exciting journey through the world of Python programming, where logic and computational thinking converge to create powerful and innovative solutions. In this chapter, we’ll explore the fascinating history of how logic gave birth to computers, from Aristotle’s pioneering work on reasoning to Alan Turing’s groundbreaking contributions to computer science. You’ll learn the fundamental concepts of computational thinking, including syntax, semantics, and algorithms, and how they form the building blocks of effective programming. Through hands-on examples featuring beloved characters like WALL-E, Bender, and the Doctor, you’ll discover how to harness the power of Python to solve problems, automate tasks, and bring your ideas to life. Whether you’re an aspiring programmer, a curious thinker, or simply eager to understand the logical underpinnings of our digital world, this chapter will equip you with the tools and mindset to dive into the exciting realm of Python programming.

Learning Outcomes: By the end of this chapter, you will be able to:

Understand the historical context of how logic and reasoning laid the foundations for modern computing, from Aristotle’s work on syllogisms to Alan Turing’s contributions to computer science.

Explain the key concepts of computational thinking, including syntax, semantics, and algorithms, and how they apply to Python programming.

Use Python’s basic data types (integers, floats, strings, and booleans) and perform operations and comparisons on them.

Create and manipulate Python lists to store and access collections of data.

Implement conditional statements (if, elif, else) to control the flow of a program based on specific conditions.

Utilize loops (for and while) to automate repetitive tasks and iterate over sequences of data.

Employ Python’s input and print functions to interact with users and display output.

Apply the concepts learned to solve practical programming problems and create simple Python scripts.

Keywords: Logic, Computational thinking, Syntax, Semantics, Algorithm, Python, Data types, Variables, Integers, Floats, Strings, Booleans, Lists, Conditional statements, If, Elif, Else, Loops, For loop, While loop, Input, Print, Formatted strings, Comparison operators, Logical operators, Arithmetic operators, Alan Turing, Turing machine, Halting problem, Church-Turing thesis, Artificial intelligence

How Logic Gave Birth to Computers

The story of how logic led to the development of computers and computer programming is a fascinating journey that spans over two millennia. It all began with the ancient Greek philosopher Aristotle, who lived from 384 to 322 BCE.

Aristotle was a pioneering thinker who laid the foundations for the study of logic. He developed a system of reasoning called categorical logic, which focused on the logical relations between categories (using “All”, “No” or “Some”). A famous example of a categorical syllogism is:

All men are mortal.

Socrates is a man.

Therefore, Socrates is mortal.

Aristotle’s work on logic was the first written attempt to systematically analyze and codify the principles of valid reasoning.

For centuries, Aristotle’s ideas on logic remained influential, but it wasn’t until the 19th century that the next major breakthrough occurred. In 1847, British mathematician George Boole published a book called “The Mathematical Analysis of Logic,” in which he introduced a new form of algebraic logic. Boole’s system used mathematical symbols to represent logical operations, such as AND, OR, and NOT. This marked the beginning of what we now call Boolean algebra, a fundamental concept in computer science.

In the early 20th century, philosophers and mathematicians like Bertrand Russell and Alfred North Whitehead further developed formal logic systems. Their work culminated in the “Principia Mathematica,” a three-volume treatise that attempted to derive all of mathematics from a set of logical axioms. Although the project was ultimately shown to have limitations by Kurt Gödel’s incompleteness theorems, it demonstrated the power and potential of formal logic.

The next key figure in this story is Alan Turing, a British mathematician and computer scientist (more on him in the “Minds that Mattered” section below. In the 1930s, Turing developed the concept of a universal computing machine, now known as the Turing machine. A Turing machine is a theoretical device that can perform any computation that can be done by an algorithm. Turing’s work laid the theoretical foundation for modern computers and showed that machines could be programmed to carry out complex logical operations.

During World War II, Turing and other mathematicians worked on breaking German military codes. This led to the development of the first electronic programmable computers, such as the Colossus machine used by the British to decrypt German messages. After the war, computer science began to develop rapidly, building on the ideas of logic and computation that had been developed over the previous decades.

In the 1940s and 1950s, pioneers like John von Neumann and Claude Shannon helped establish the field of computer architecture and information theory. They showed how Boolean logic could be implemented using electronic circuits, paving the way for the development of the first general-purpose computers.

The first high-level programming languages, such as FORTRAN and LISP, emerged in the 1950s. These languages used logical and mathematical concepts to express computations in a way that was closer to human reasoning than the low-level machine code used by early computers. The development of these languages marked the beginning of modern computer programming. In the 1970s, the first modern languages (such as C) emerged. Python, which we’ll be learning about later, is a C-type language.

Since then, the field of computer science has grown exponentially, but its foundations in logic remain crucial. From databases to artificial intelligence, many of the key concepts and techniques used in computer science today can be traced back to the ideas of Aristotle, Boole, Turing, and other pioneers who explored the power of logical reasoning.

Key Concepts of Computations Thinking

Later in this chapter, you’ll be learning basic ideas of computer programming using Python. There are plenty of practical benefits to this (Python is used in many jobs, by people who aren’t professional programmers), but it can also teach some valuable skills about logic/reasoning.

At the heart of computer programming lies computational thinking. It’s a problem-solving approach that involves breaking down complex problems into smaller, manageable parts, and then creating step-by-step solutions (algorithms) to solve them. This process helps develop logical thinking skills that are valuable not only in programming but in everyday life as well.

Syntax and Semantics

A key part of computational thinking (and of formal logic) involves the use formal languages with strict rules about what is, and what it is not allowed. This helps eliminate the ambiguities inherent in nautural languages like English, Spanish, or Chinese.

So,f for example, Let’s imagine you have a cute cartoon robot friend named Robo. Robo loves to help with tasks but needs clear, step-by-step instructions to perform them effectively. This means that, when giving instructions to Robo, you need to use a language that Robo understands.

In both computer programming and formal logic, this formal language is defined by its syntax and semantics. Syntax refers to the structure and rules of the language, while semantics refers to the meaning behind the instructions.

For example, in Python, you can print a message to Robo like this:

print(“Hello, Robo!”)

The syntax here includes the use of the print function, parentheses (), and quotation marks “”. The semantics is that this line of code will display the message “Hello, Robo!” on the screen.

When we make mistakes in programs (called bugs), these can either be syntax errors (where we didn’t follow the “rules of the language) or semantic errors (where we gave the computer a valid command, but it wasn’t what we “intedned” to do). Syntax errors will generally cause the computer progam to crash or throw as “exception.” Semantic errors, by contrast, mean the computer program will “run” perfectly fine–it just will be makign mistakes.

Algorithms

The ultimate goal of using languages with strick rules of syntax is to allow us to write algorithsms that will solve problems. Here, an algorithm is a set of step-by-step instructions to solve a problem or accomplish a task. Let’s say you want Robo to count the number of red apples in a basket. The algorithm could be:

Set a variable count to 0

For each apple in the basket:

If the apple is red, increase count by 1

Print the final value of count

In Python, this algorithm could be implemented as:

count = 0
for apple in basket:
if apple.color == “red”:
count += 1
print(“Number of red apples:”, count)

In the rest of this chapter, we’ll explore how we can use basic Python programming to implement some simple programs of our own.

An Intro to Python and Colab

This chapter is written using the programming language Python, and is delivered using Google Colab, which lets you write and run Python code for free (so long as you have a Google account).

Python is a high-level, general-purpose programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability and allows you to express concepts in fewer lines of code compared to other programming languages. Python is widely used in various domains, including web development, data analysis, artificial intelligence, scientific computing, and more.

Colab, short for “Colaboratory,” is a free cloud-based Jupyter notebook environment provided by Google. It allows you to write, run, and share Python code directly in your web browser without the need for any local setup or installation.

This chapter you are reading is a Google Colab document you can access here [LINK]. (Note: If prompted, agree to “trust” the notebook. I promise nothing bad will happen to your computer).

If you want to create your own Colab notebook, follow these steps:

Go to the Colab website: https://colab.research.google.com/

Click on “New Notebook” to create a new notebook or “Upload” to upload an existing notebook from your computer.

Once your notebook is created, you’ll see a cell where you can start writing Python code.

To execute a code cell, click on the cell and press Shift+Enter or click the play button on the left side of the cell.

The output of the code will be displayed below the cell.

Here’s a simple example to get you started (you can simply “run” this cell).

print(“Hello, Robo!”)
print(“Welcome to the world of Python programming!”)

Hello, Robo!
Welcome to the world of Python programming!

You Try It: Printing

In the code cell below, try to print a message of your choice and then “run” the cell. For example, print(“Hello World”) will print the message “Hello World”.

# You Try It: Printing
# Type your code in this cell!

Introduction to Python Variables and Data Types

Welcome, aspiring programmers! In this guide, we’ll explore the fundamental concepts of variables, data types, and assignment statements in Python. These concepts are essential building blocks for creating programs that can store, manipulate, and process data. Let’s dive in and see how the robots from Wall-E can help us understand these concepts!

Variables

In programming, a variable is like a container that holds a value. Just like how Wall-E stores important items he finds during his cleanup tasks, variables in Python allow us to store different types of data, such as numbers, text, or Boolean values (true or false).

Think of a variable as a labeled box. You can put something inside the box (a value) and give the box a name (the variable name). Whenever you want to use the value inside the box, you simply refer to it by its name.

For example, let’s say we want to store Wall-E’s favorite plant:

# Example of variable assignment
favorite_plant = “Green Leaf”

In this case, favorite_plant is the variable name, and “Green Leaf” is the value stored inside the variable. The # at the top represents a comment that is ignored by computer.

Now, we can print this variable to the screen as follows:

# pringint a variable
print(“Wall-E’s favorite plant is: “, favorite_plant)

Wall-E’s favorite plant is: Green Leaf

Data Types

Data types define the kind of data that a variable can hold. Python has several built-in data types, but let’s focus on four commonly used ones: integers (int), floating-point numbers (float), Boolean values (bool), and strings (str).

Integers (int)

Integers are whole numbers, positive or negative, without any decimal points. They are used to represent quantities, counts, or discrete values.

Example:

# Integer variables
cube_length = 10
cube_height = 5
cube_depth = 3
cube_volume = cube_length * cube_height * cube_depth
print(“The volume of the cube is:”, cube_volume)

The volume of the cube is: 150

Here we declare 3 integer variables, and then use these to calculate the value of a new integer variable.

Floats (float)

Floats are decimal numbers used to represent continuous values or measurements. They are essential for calculations that require precision.

Example:

# Float variables
wall_e_weight = 135.5
eve_weight = 72.3
total_weight = wall_e_weight + eve_weight

print(“The total weight of Wall-E and Eve is:”, total_weight)

The total weight of Wall-E and Eve is: 207.8

In this example, we declare two float variables representing the weights of Wall-E and Eve. We then calculate the total weight by adding these variables together.

Booleans (bool)

Booleans represent truth values, either True or False. They are often used in conditional statements and logical operations.

Example:

# Boolean variables
wall_e_operational = True
eve_operational = False
is_both_operational = wall_e_operational and eve_operational

print(“Is Wall-E operational?”, wall_e_operational)
print(“Is Eve operational?”, eve_operational)
print(“Are both robots operational?”, is_both_operational)

Is Wall-E operational? True
Is Eve operational? False
Are both robots operational? False

Here, we define two boolean variables indicating the operational status of Wall-E and Eve. We then print the individual statuses and use the and operator to check if both robots are operational.

Strings (str)

Strings are sequences of characters used to represent text. They are enclosed in either single quotes (”) or double quotes (“”).

Example:

# String variables
wall_e_greeting = “Wall-E says: ‘Eeeee-va!'”
eve_response = ‘Eve replies: “Directive?”‘
dialogue = wall_e_greeting + \n + eve_response

print(dialogue)

Wall-E says: ‘Eeeee-va!’
Eve replies: “Directive?”

In this example, we create two string variables representing a dialogue between Wall-E and Eve. We concatenate the strings using the + operator and print the resulting dialogue.

Here, the “\n” character prints a newline (basically, it hints “enter.”).

You Try It: Variables

In the code cell below, create variables of the following types, and print each of them.

An integer variable (any whole number)

A floating point variable (with a decimal)

A boolean variabale (with the the value of either True or False).

A string variable (characters that are enclosed in single- or double quotes).

# You Try It: Variables
# Type your code in this cell!

Getting to Know the Print Function

We’ve already see the print() function a few times. This is a fundamental tool in Python used to display output on the console. It allows you to communicate information to the user or debug your code. Let’s explore the print() function using examples featuring Bender from Futurama.

The basic syntax of the print() function is as follows:

# Basic printing
print(“Hello, meatbags!”)

Hello, meatbags!

In this example, the text “Hello, meatbags!” is passed as an argument to the print() function. The function then displays the text on the

Concetenating Strings

You can concatenate (join) multiple strings together using the + operator within the print() function.

name = “Bender”
print(“Bite my shiny metal “ + name + “!”)

Bite my shiny metal Bender!

Here, we define a variable name with the value “Bender”. Inside the print() function, we concatenate three strings: “Bite my shiny metal “, the value of the name variable, and “!”. The resulting string is then displayed on the console.

Printing with f-strings (Formatted String Literals)

Python 3.6 introduced f-strings, which provide a more concise and readable way to include variables within strings.

# Example: f-strings
beer_count = 99
print(f”I’m {name}, baby! I can drink {beer_count} beers without shutting down.”)

I’m Bender, baby! I can drink 99 beers without shutting down.

In this example, we use an f-string by prefixing the string with the letter f. Inside the string, we place the variables name and beer_count within curly braces {}. Python automatically replaces the variables with their corresponding values when the print() function is called.

Printing Multiple Items with Commas

You can print multiple items by separating them with commas within the print() function.

# Example: Printing multiple items with commas
print(“I’m”, name, “, baby!”)
print(“I can drink”, beer_count, “beers without shutting down.”)

I’m Bender , baby!
I can drink 99 beers without shutting down.

Here, we pass multiple items to the print() function: strings and variables. By default, the print() function separates these items with spaces when displaying them on the console.

You Try It: Printing with f-strings

Create variables that hold your name and age. Then show how you can use a print statement to print out these variables. (For example, “My name is X and I am Y years old.”)

# You Try it: Priting with f-strings
# Type your code in this cell!

Getting Input from the User

In Python, you can get input from the user using the input() function. This function allows you to prompt the user to enter data from the console and retrieve that data in your program.

The basic syntax of the input() function is as follows:

user_input = input(“Enter something: “)

In this example, the input() function displays the prompt “Enter something: ” on the console and waits for the user to enter data. Once the user presses the Enter key, the entered data is stored in the user_input variable as a string.

For example, let’s say we would like to give Bender some input:

# Example: Getting input
name = input(“Bender: Hey, meatbag! What’s your name?”)
print(f”Bender: Nice to meet you, {name}. Wanna grab a beer?”)

Bender: Hey, meatbag! What’s your name?Brendan
Bender: Nice to meet you, Brendan. Wanna grab a beer?

In this example, Bender prompts the user to enter their name using the input() function. The entered name is stored in the name variable. Bender then uses an f-string to greet the user by their name and asks if they want to grab a beer.

Casting Input

By default, the input() function returns the user’s input as a string. However, you can cast (convert) the input to a different data type using type casting functions like int(), float(), or bool().

For example:

number = 7
print(“Bender: I’m thinking of a number between 1 and 10.”)

# Example: Casting input to an integer
guess = int(input(“Enter your guess: “))
print(f”Bender: Your guess is {guess}. I was thinking of {number}.”)

Bender: I’m thinking of a number between 1 and 10.
Enter your guess: 4
Bender: Your guess is 4. I was thinking of 7.

In this example, Bender asks the user to guess a number. The input() function is used to get the user’s guess, and the int() function is used to cast the input to an integer. The guess is then stored in the guess variable, and Bender responds with the user’s guess.

You can also cast input to other data types, such as float() for decimal numbers or bool() for boolean values.

# Example: Casting input to a float or bool
height = float(input(“Enter your height in meters: “))
is_robot = bool(input(“Are you a robot? (True/False): “))

# Print results
print(f”Your height is {height} meters.”)
print(f”Are you a robot? {is_robot})

Enter your height in meters: 2.3
Are you a robot? (True/False): False
Your height is 2.3 meters.
Are you a robot? True

You Try It: Getting Input

Use the input function to ask the user their age (in years). Then calculate their age in days (multiplying by 365) and print this out.

# You Try It: Getting Input
# Type your code in this cell!

Conditional Statements

Conditional statements in Python allow you to execute different blocks of code based on certain conditions. They help you control the flow of your program and make decisions based on specific criteria.

If Statement

The if statement is used to execute a block of code if a specified condition is true. The general format is:

if condition:
# do something

Note that you must have a : after the if, and that you must indent the “body” of the conditional. For example:

# Example Conditionals
battery_level = 75
if battery_level > 50:
print(“R2-D2: Beep beep! Battery level is sufficient.”)

R2-D2: Beep beep! Battery level is sufficient.

In this example, if the battery_level is greater than 50, R2-D2 will print a message indicating that the battery level is sufficient.

If-Else Statement

The if-else statement allows you to specify an alternative block of code to execute if the condition in the if statement is false.

# Example: if and else
battery_level = 30
if battery_level > 50:
print(“R2-D2: Beep beep! Battery level is sufficient.”)
else:
print(“R2-D2: Beep beep! Battery level is low.”)

R2-D2: Beep beep! Battery level is low.

If-Elif-Else Statement

Finally, we can use if with elif (“else if”) to check for multiple possible conditions.

# Example: if with multiple elifs
battery_level = 30
if battery_level > 50:
print(“R2-D2: Beep beep! Battery level is sufficient.”)
elif battery_level > 20:
print(“R2-D2: Beep beep! Battery level is low.”)
else:
print(“R2-D2: Beep beep! Battery level is critically low.”)

R2-D2: Beep beep! Battery level is low.

You Try It: Conditional Statements

Using the above code block as an example, create an if-elif-else code block that allows R2-D2 to respond to the amount of “damage” he has sustained. (Suppose damage is a number between 0 and 100, representing what “percent” is damaged.

# You Try It: COnditional Statements
# Type your code in this cell!

ond

Operators and Expressions

In this section, we’ll explore the various operators and expressions in Python that allow you to perform calculations, make comparisons, and combine logical conditions. Understanding these operators and expressions is essential for manipulating data and making decisions in your programs.

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations on numeric values. Python provides the following arithmetic operators:

Addition (+): Adds two values together.

Subtraction (): Subtracts one value from another.

Multiplication (*): Multiplies two values.

Division (/): Divides one value by another and returns the quotient as a floating-point number.

Floor Division (//): Divides one value by another and returns the quotient as an integer, discarding the decimal part.

Modulo (%): Returns the remainder of a division operation.

Exponentiation (**): Raises a value to the power of another.

Let’s consider an example where WALL-E performs some arithmetic calculations:

battery_level = 80
charging_time = 30
total_battery = battery_level + charging_time
print(f”WALL-E’s total battery level is {total_battery}%”)

distance_traveled = 100
time_taken = 5
speed = distance_traveled / time_taken
print(f”WALL-E’s speed is {speed} units per second”)

In this example, we use the addition operator (+) to calculate WALL-E’s total battery level by adding the current battery level and the charging time. We also use the division operator (/) to calculate WALL-E’s speed by dividing the distance traveled by the time taken.

Comparison Operators

Comparison operators are used to compare two values and return a Boolean result (True or False). Python provides the following comparison operators:

Equal to (==): Returns True if two values are equal.

Not equal to (!=): Returns True if two values are not equal.

Greater than (>): Returns True if the left value is greater than the right value.

Less than (<): Returns True if the left value is less than the right value.

Greater than or equal to (>=): Returns True if the left value is greater than or equal to the right value.

Less than or equal to (<=): Returns True if the left value is less than or equal to the right value.

Let’s consider an example where HAL compares some values:

temperature = 25
threshold = 30

if temperature > threshold:
print(“Warning! Temperature exceeds the threshold.”)
else:
print(“Temperature is within the normal range.”)

In this example, we use the greater than operator (>) to compare the temperature value with the threshold value. If the temperature is greater than the threshold, HAL prints a warning message; otherwise, it prints a message indicating that the temperature is within the normal range.

Logical Operators

Logical operators are used to combine multiple conditions and return a Boolean result based on the logical evaluation. Python provides the following logical operators:

Logical AND (and): Returns True if both conditions are true.

Logical OR (or): Returns True if at least one of the conditions is true.

Logical NOT (not): Returns the opposite Boolean value of a condition.

Let’s consider an example where Bender makes a decision based on logical conditions:

battery_level = 50
has_internet_connection = True

if battery_level > 20 and has_internet_connection:
print(“Bender is ready to surf the web!”)
else:
print(“Bender needs to charge or check the internet connection.”)

In this example, we use the logical AND operator (and) to combine two conditions: battery_level > 20 and has_internet_connection. If both conditions are true, Bender prints a message indicating that it is ready to surf the web. Otherwise, it prints a message suggesting that it needs to charge or check the internet connection.

Let’s put these concepts into practice with a small program:

# Exercise: Robot Power Checker
print(“Welcome to the Robot Power Checker!”)
battery_percentage = float(input(“Enter the battery percentage: “))
solar_panels_active = input(“Are the solar panels active? (yes/no): “)

if battery_percentage >= 50 or solar_panels_active == “yes”:
print(“The robot has sufficient power to operate.”)
else:
print(“The robot needs to conserve energy.”)

In this program, we prompt the user to enter the battery percentage and whether the solar panels are active. We then use the logical OR operator (or) to check if either the battery percentage is greater than or equal to 50 or the solar panels are active. Based on the condition, we print a message indicating whether the robot has sufficient power or needs to conserve energy.

You Try It: Complex Conditions

Copy the code from the “Robot Power Checker” to the code cell below. Then, add a third input, asking whether the robot is carrying a spare battery pack. Adjust the rest of the code accordingingly (for example, if they hava a spare battery pack, they have sufficient power.)

# You Try It: Complex Conditions
# Type your code in this cell! (Begin by copying code)

Lists and For Loops

Lists in Python are used to store multiple items in a single variable. They allow you to organize and manipulate collections of data.

Creating a List

To create a list in Python, you enclose a comma-separated sequence of elements in square brackets []. For example:

# list of famous robots
famous_robots = [“R2-D2”, “C-3PO”, “HAL9000”]
print(famous_robots)

[‘R2-D2’, ‘C-3PO’, ‘HAL9000’]

In this example, we create a list called famous_robots that contains the names of some robots.

Accessing List Elements

You can access individual elements of a list using their index. Python uses zero-based indexing, meaning the first element has an index of 0.

# print the first robot
print(famous_robots[0])

# print the second robot
print(famous_robots[1])

# print the last robot
print(famous_robots[1])

R2-D2
C-3PO
HAL9000

If you look closely, you notice we can use “negative indexing” to start at the back of the list (so -1 means “the last item.”).

For Loop

The for loop is used to iterate over a sequence of elements, such as a list. It allows you to perform a specific action for each element in the list.

The basic syntax is:

for element in list:
# Code to be executed for each element

Example:

# Loop through robots
for robot in famous_robots:
print(robot)

R2-D2
C-3PO
HAL9000

In this simple example, we loop through the robots and print their name. We can also can combine lists with conditionals.

# Example: combining for loop and if
for robot in famous_robots:
if robot == “HAL9000”:
print(f”I’m scared of {robot})
else:
print(f”{robot} seems friendly”)

R2-D2 seems friendly
C-3PO seems friendly
I’m scared of HAL9000

Here, we loop through the list of robots, and check whether each is eqaul to HAL9000 (who scares us).

You Try It: Lists and For Loops

Create a list of your five favorite foods. Then use a for-loop to iterate through these foods and print something like “X is one of my favorite foods!.”

# You Try It: Lists and For Loops
# Your code goes here

Using For Loops with Range

In Python, the range() function is used to generate a sequence of numbers. It is commonly used in for loops to control the number of iterations.

The syntax is

range(start, stop, step)

start: The starting number of the sequence (inclusive). If omitted, it defaults to 0.

stop: The ending number of the sequence (exclusive). This is a required argument.

step: The increment between each number in the sequence. If omitted, it defaults to 1.

While this may seem a little complex, in practice it’s actually pretty intuitive:

# Example: Eve counts 0 to 9
for i in range(10):
print(f”Eve has found {i} plants.”)

Eve has found 0 plants.
Eve has found 1 plants.
Eve has found 2 plants.
Eve has found 3 plants.
Eve has found 4 plants.
Eve has found 5 plants.
Eve has found 6 plants.
Eve has found 7 plants.
Eve has found 8 plants.
Eve has found 9 plants.

In this example, the range(10) function generates a sequence of numbers from 0 to 10 (exclusive). The for loop iterates over each number in the sequence, and the value of i is used to print the number of plants Eve has found.

Nested Loops

Nested loops are loops inside other loops. They allow you to perform iterations within iterations, enabling you to work with multi-dimensional data or perform complex operations.

doctor_incarnations = [“Ninth”, “Tenth”, “Eleventh”]
tardis_rooms = [“Console Room”, “Library”, “Swimming Pool”]

for doctor in doctor_incarnations:
print(f”The {doctor} Doctor enters the TARDIS.”)
for room in tardis_rooms:
print(f”The Doctor visits the {room}.”)
print(“The Doctor sets off on a new adventure!”)
print()

The Ninth Doctor enters the TARDIS.
The Doctor visits the Console Room.
The Doctor visits the Library.
The Doctor visits the Swimming Pool.
The Doctor sets off on a new adventure!

The Tenth Doctor enters the TARDIS.
The Doctor visits the Console Room.
The Doctor visits the Library.
The Doctor visits the Swimming Pool.
The Doctor sets off on a new adventure!

The Eleventh Doctor enters the TARDIS.
The Doctor visits the Console Room.
The Doctor visits the Library.
The Doctor visits the Swimming Pool.
The Doctor sets off on a new adventure!

In this example, we have two lists: doctor_incarnations and tardis_rooms. We use nested for loops to iterate over each Doctor incarnation and each room in the TARDIS. The outer loop iterates over the Doctors, while the inner loop iterates over the rooms. For each Doctor, we print a message indicating that they enter the TARDIS, and then we use the inner loop to print a message for each room the Doctor visits. Finally, we print a message about the Doctor setting off on a new adventure and add an empty line for readability.

Certainly! Let’s explore the world of while loops and their syntax and use cases, featuring some new robot friends.

While Loops

In this section, we’ll delve into the realm of while loops in Python. While loops are like the persistent determination of our robot friends, allowing them to repeat a block of code as long as a specified condition is true. They provide a way to handle repetitive tasks that depend on certain conditions being met.

The basic syntax of a while loop in Python is as follows:

while condition:
# Code block to be executed while the condition is true

Let’s break down each part of the syntax:

while: This keyword indicates the start of a while loop.

condition: This is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code block inside the loop is executed. If the condition is false, the loop is terminated, and the program continues with the next statement after the loop.

:: This colon indicates the end of the while loop header and the start of the code block.

Code block: This is the block of code that is executed repeatedly as long as the condition remains true. It is indented to indicate that it belongs to the while loop.

Now, let’s see how our robot friend, Robby the Robot, uses a while loop to collect samples on a distant planet:

# Robby the Robot’s Sample Collection
num_samples_needed = 5
num_samples_collected = 0

print(“Robby the Robot is collecting samples on the planet.”)
while num_samples_collected < num_samples_needed:
print(f”Collecting sample #{num_samples_collected + 1})
# Code to collect the sample goes here
num_samples_collected += 1

print(“Robby the Robot has collected all the required samples.”)

Robby the Robot is collecting samples on the planet.
Collecting sample #1
Collecting sample #2
Collecting sample #3
Collecting sample #4
Collecting sample #5
Robby the Robot has collected all the required samples.

In this example, Robby the Robot needs to collect a specific number of num_samples_needed on a distant planet. The while loop continues to execute as long as the number of num_samples_collected is less than num_samples_needed. Inside the loop, Robby prints a message indicating the sample number he is collecting and increments the num_samples_collected count. The loop repeats until Robby has collected all the required samples.

Infinite Loops and Break Statement

Sometimes, we may want a while loop to continue running indefinitely until a specific condition is met. This is known as an infinite loop. However, it’s crucial to provide a way to exit the loop when needed. The break statement allows us to terminate the loop prematurely. Let’s see how Bender from “Futurama” uses an infinite loop to consume drinks at a party:

# Bender’s Drink Consumption
drinks_consumed = 0

print(“Bender is ready to party!”)
while True:
print(f”Bender consumes drink #{drinks_consumed + 1})
# Code to consume the drink goes here
drinks_consumed += 1

if drinks_consumed >= 10:
print(“Bender has had enough drinks. Time to take a break!”)
break

print(“Party’s over. Bender is shutting down.”)

In this example, Bender starts consuming drinks at a party. The while loop is set to True, creating an infinite loop. Inside the loop, Bender prints a message indicating the drink number he is consuming and increments the drinks_consumed count. However, to prevent Bender from consuming drinks indefinitely, we use an if statement to check if drinks_consumed has reached a certain limit (in this case, 10). If the condition is met, the break statement is executed, terminating the loop. Finally, Bender acknowledges that the party is over.

You Try It: While Loops

Write a program that repeatedly asks the user for their name unti they enter a name that is exactly 7 characters long. You’ll need to use a while loop and the len(str) function (which gives the length of a string).

# You Try It: While Loops
# Code goes here

Minds that Mattered: Alan Turing

Alan Turing (1912-1954) was an English mathematician, computer scientist, logician, cryptanalyst, and theoretical biologist. Born in London, Turing made significant contributions to the fields of computer science, artificial intelligence, and theoretical biology. He is widely considered to be the father of theoretical computer science and artificial intelligence.

Turing studied mathematics at King’s College, Cambridge, and received his Ph.D. from Princeton University in 1938. During World War II, he worked at Bletchley Park, the center of Allied code-breaking efforts, where he played a crucial role in breaking the German Enigma code. His work at Bletchley Park helped to shorten the war and save countless lives.

After the war, Turing continued his research in computer science and artificial intelligence. He worked on the design of early computers, including the Manchester Baby, one of the first stored-program computers. Turing also made significant contributions to the field of mathematical biology, developing models of morphogenesis and pattern formation in living organisms.

Despite his groundbreaking work, Turing faced significant personal challenges during his lifetime. In 1952, he was prosecuted for homosexual acts, which were then criminal offenses in the United Kingdom. He died by suicide in 1954, at the age of 41. In 2009, the British government issued a posthumous apology for Turing’s treatment, and in 2013, he was granted a royal pardon.

Key Ideas

One of Turing’s most significant contributions to computer science was his development of the concept of a Turing machine. A Turing machine is a theoretical device that consists of an infinite tape divided into cells, a read-write head that can move along the tape, and a set of rules that determine the machine’s behavior based on the symbols it reads from the tape. Turing showed that a Turing machine could perform any computation that could be carried out by an algorithm. This idea formed the basis for the Church-Turing thesis, which states that any computable function can be computed by a Turing machine. The concept of a Turing machine has become a fundamental tool in the study of computation and has helped to establish the theoretical foundations of computer science.

Another of Turing’s key contributions was his work on the halting problem. The halting problem asks whether there exists an algorithm that can determine, for any given program and input, whether the program will eventually halt or continue running forever. Turing proved that there is no general algorithm that can solve the halting problem for all possible programs and inputs. This result has important implications for the limits of computation and the boundaries of what can be achieved by algorithms. It shows that there are certain problems that cannot be solved by any computer program, no matter how powerful or sophisticated. The halting problem is an example of an undecidable problem, a type of problem that cannot be solved by any algorithm. Turing’s work on the halting problem helped to establish the field of computability theory, which studies the limits of what can be computed by algorithms and the classification of problems as decidable or undecidable.

Turing also made significant contributions to the philosophy of artificial intelligence. In his 1950 paper “Computing Machinery and Intelligence,” Turing proposed an experimental test, now known as the Turing test, to determine whether a machine could exhibit intelligent behavior indistinguishable from that of a human. In the Turing test, a human interrogator engages in a conversation with both a human and a machine, communicating through a text-only interface. If the interrogator cannot reliably distinguish between the human and the machine, the machine is said to have passed the test and can be considered intelligent. While the Turing test has been the subject of much debate and criticism, it has become an important touchstone in the philosophy of artificial intelligence. It raises fundamental questions about the nature of intelligence, the relationship between intelligence and consciousness, and the possibility of creating machines that can think and reason like humans. Turing’s work on the Turing test and the philosophy of artificial intelligence has helped to shape the field of AI and has inspired ongoing research into the nature of intelligence and the potential for creating intelligent machines.

Influence

Turing’s work has had a profound and lasting influence on the fields of computer science, artificial intelligence, and beyond. His contributions to the theoretical foundations of computing, including the concept of a Turing machine and the Church-Turing thesis, have become cornerstones of computer science education and research.

Turing’s work on the halting problem and the limits of computation has had significant implications for the development of algorithms and the study of computational complexity. His results have helped to establish the boundaries of what can be achieved by computers and have inspired ongoing research into the classification of problems as tractable or intractable.

In the field of artificial intelligence, Turing’s ideas have been hugely influential. The Turing test has become a standard benchmark for evaluating the performance of AI systems, and his work on machine learning and neural networks has laid the foundation for modern AI research. Today, researchers continue to build on Turing’s ideas in their efforts to create intelligent machines that can perceive, reason, and learn like humans.

Beyond his technical contributions, Turing’s life and legacy have also had a significant cultural impact. His work at Bletchley Park during World War II has been celebrated in books, films, and television shows, and his status as a pioneering figure in computer science has made him an icon in the tech industry. At the same time, Turing’s persecution for his homosexuality has made him a symbol of the ongoing struggle for LGBTQ+ rights and a reminder of the need for greater diversity and inclusion in science and technology.

Discussion Questions

How did Turing’s work on the theoretical foundations of computing, including the concept of a Turing machine and the Church-Turing thesis, help to establish computer science as a distinct academic discipline?

What are some examples of undecidable problems in computer science, and how do they relate to Turing’s work on the halting problem and the limits of computation?

How has the Turing test influenced research in artificial intelligence, and what are some of the key criticisms and limitations of the test as a measure of machine intelligence?

In what ways has Turing’s work on machine learning and neural networks laid the foundation for modern AI research, and what are some of the key challenges and opportunities in this field today?

How has Turing’s life and legacy influenced popular culture and public perceptions of computer science and artificial intelligence, and what lessons can we draw from his experiences as a gay man in science and technology?

Glossary

Term

Definition

Turing machine

A theoretical computing device that consists of an infinite tape, a read-write head, and a set of rules for performing computations.

Church-Turing thesis

The hypothesis that any computable function can be computed by a Turing machine, implying that Turing machines are a universal model of computation.

Halting problem

The problem of determining whether a given program will eventually halt or run forever, which Turing proved to be undecidable.

Computability theory

The study of the limits of computation and the classification of problems as decidable or undecidable.

Turing test

An experimental test proposed by Turing to evaluate whether a machine can exhibit intelligent behavior indistinguishable from that of a human.

Machine learning

A subfield of artificial intelligence that focuses on the development of algorithms and statistical models that enable computers to learn from data.

Neural networks

A type of machine learning model inspired by the structure and function of the human brain, consisting of interconnected nodes that process and transmit information.

Bletchley Park

The estate in England where Turing and other mathematicians worked to break German codes during World War II, including the Enigma code.

Enigma

A series of electro-mechanical rotor cipher machines used by the German military during World War II to encrypt messages, which Turing helped to decrypt at Bletchley Park.

Table: Basic Python

Python Command

Description

voltage = 12.5

Assign the float value 12.5 to a variable voltage.

robot_name = “Rusty”

Assign the string value “Rusty” to a variable robot_name.

is_active = True

Assign the boolean value True to a variable is_active.

print(“Beep boop!”)

Print the string “Beep boop!” to the console.

print(voltage)

Print the value of the variable voltage to the console.

user_input = input(“Enter a command: “)

Prompt the user to enter a command and assign the input to a variable user_input.

if voltage > 10:

Start an if statement that executes the indented code block if voltage is greater than 10.

else:

Start an else block that executes if the preceding if condition is false.

elif voltage < 5:

Start an elif (else if) block that executes if the preceding if condition is false and voltage is less than 5.

robot_parts = [“arm”, “leg”, “sensor”]

Create a list called robot_parts containing the strings “arm”, “leg”, and “sensor”.

robot_parts[1]

Access the second element of the list robot_parts (index 1).

print(f”Hello, my name is {robot_name}!”)

Print a formatted string that includes the value of the variable robot_name.

height = “5.2”

Assign the string value “5.2” to a variable height.

height_float = float(height)

Cast the string value of height to a float and assign it to a variable height_float.

num_sensors = 4

Assign the integer value 4 to a variable num_sensors.

num_sensors_str = str(num_sensors)

Cast the integer value of num_sensors to a string and assign it to a variable num_sensors_str.

voltage == 12.5

Check if voltage is equal to 12.5.

robot_name != “Clank”

Check if robot_name is not equal to “Clank”.

is_active and voltage > 10

Check if both is_active is True and voltage is greater than 10.

is_active or voltage < 5

Check if either is_active is True or voltage is less than 5.

not is_active

Check if is_active is False.

for part in robot_parts:

Start a for loop that iterates over each element in the list robot_parts.

for i in range(num_sensors):

Start a for loop that iterates over the numbers 0, 1, 2, and 3 (assuming num_sensors is 4).

while voltage > 0:

Start a while loop that continues executing the indented code block as long as voltage is greater than 0.

print(f”Number of sensors: {num_sensors}”)

Print a formatted string that includes the value of the variable num_sensors.

Want to Learn More?

Here are some popular websites for learning Python programming.

Python.org – The official Python website, offering a wealth of resources, documentation, and tutorials for all levels of Python programmers. (https://www.python.org/)

Codecademy – An interactive learning platform that offers free and paid courses on Python programming, with hands-on exercises and projects. (https://www.codecademy.com/learn/learn-python-3)

Coursera – A leading online learning platform featuring Python courses from top universities and institutions worldwide. (https://www.coursera.org/courses?query=python)

edX – Another popular online learning platform with a variety of Python courses, including those from MIT and Harvard. (https://www.edx.org/learn/python)

Udemy – A vast online course marketplace with numerous Python courses for beginners and advanced learners alike. (https://www.udemy.com/topic/python/)

learnpython.org – A free, interactive Python tutorial that covers the basics of Python programming in a hands-on, easy-to-follow manner. (https://www.learnpython.org/)

Python for Everybody – A free online course series by Dr. Charles Severance, offering a gentle introduction to Python programming. (https://www.py4e.com/)

Automate the Boring Stuff with Python – A free online book that teaches practical Python programming for automating everyday tasks. (https://automatetheboringstuff.com/)

Real Python – A comprehensive website with Python tutorials, articles, and guides for all skill levels, focusing on real-world applications. (https://realpython.com/)

Google’s Python Class – A free, self-paced Python course by Google, designed for people with a little bit of programming experience. (https://developers.google.com/edu/python)

 

License

Icon for the Creative Commons Attribution-NonCommercial 4.0 International License

A Little More Logical Copyright © 2024 by Brendan SHea is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License, except where otherwise noted.

Share This Book