GGC

3. Introduction to Python

3.1. Programming Basics

Computers are programmable machines that process information by manipulating data. As the data can represent any real world information, and programs can be readily changed, computers are capable of solving many kinds of problems.

3.1.1. Programming Languages and Environments

There are many different programming languages for programmers to choose from. Each language has its own advantages and disadvantages, and new languages gain popularity while older ones slowly lose ground. In this book, we use the Python 3 programming language. It is popular in both academia and industry, and was designed with education in mind.

3.1.2. PythonTutor

PythonTutor is an environment for creating very short and simple Python programs and visualizing their execution. This enables beginners to visually see the data as it gets manipulated by the instructions.

Example 1 - A Simple Program

Use the Next button to step through the program below and watch the data get created and modified. Notice how the arrows move to indicate what instruction the program execution is on.

3.1.3. Comments

Program files can contain source code and comments. Comments are not instructions for the computer to follow, but instead notes for programmers to read. Comments in Python start with a pound sign (#). Anything following the pound sign that is on the same line as the pound sign will not be executed. Often, at the very beginning of a program, comments are used to indicate the author and other information. Comments are also used to explain tricky sections of code or disable code from executing.

# This line is not Python code, it is a comment.

score = 9001 # over 9000!!!

# The next line of code is disabled because is starts with a #.
# score = 8000

3.2. Data Types

Programming is all about information processing. Information is categorized by data types. Four basic data types we will be considering are int , float , bool , and str . Int consists of integers , which are whole numbers written without a decimal point. This includes positive and negative whole numbers as well as zero. Float consists of floating-point numbers , which are numbers that are written with a decimal point. Bool consists of Boolean values (named after the mathematician George Boole). The only Boolean values are True and False. Str consists of strings , which are sequences of text characters including punctuation, symbols, and whitespace. Every value in Python has a corresponding data type. The table below shows examples of ints, floats, and strings.

Table 1. Basic Data Types
Data Type Example Values

int

2, -2, 0, 834529

float

3.14, -2.3333, 7.0

bool

True, False

str

"Hello World!", 'Coconut', "0", '4 + 6'

Strings and Quotation Marks

Strings are always surrounded by quotation marks. Python allows either single (') or double (") quotation marks. Some strings may look like numbers, but as long as they are surrounded by quotation marks, they are treated like text.

3.3. Variables

Variables are (virtual) boxes that store values for reuse later. A variable has a name and a current value. Each variable can only hold one value at a time. Variables are assigned a value using the single equal sign (=). As Python executes one line at a time, variables come into existence on the line where they are first assigned. Each variable only stores the most recent value assigned to it.

Example 2 - Basic Variables and Data Types

Use the Next button to step through the program below and watch the variables get created.

Variable Names

Variables can have complex names like player1_score . In general, never start a variable name with a number and never use spaces in variable names.

3.4. Operators and Expressions

Example 3 - Numerical Operators and Expressions

Try to predict the variable names, values, and data types in the the code below.

Expression Evaluation

When Python encounters a line with an expression, it always evaluates the expression first. Consider the following line of code:

x = (3 + 4) * 2

Python first calculates the value of the expression to the right of the equal sign by using the standard order of operations starting inside the parentheses. The value given by the above expression is calculated to be equal to 14. Then, Python creates the variable x and assigns the value 14 to this variable. The variable only stores the calculated value, not the entire expression that generated that value.

Example 4 - Boolean Operators and Expressions

Note how each expression returns a Boolean value. These are called Boolean expressions .

3.5. Strings and Printing

Besides creating and storing values in variables, we can also output text on a screen by calling the print() function.

Example 5 - Strings and print()

Try to predict the printed output. Look at the small window in the top-right as you use the Next button.

3.6. If Statements

A block of code is a collection of lines of code that are either all executed (in sequential order) or all skipped. Blocks always start with a colon (:) on the previous line and require every line in the block to be indented the same amount using tabs or spaces. One way in which Python can execute or skip over a block involves using an if command and a Boolean expression. If the expression is true, then the block executes. Othewise, the block is skipped.

Example 6 - If Statements
  • Notice that all un-indented lines and the second block execute, while the first block does not execute.

  • Which blocks execute if age = 22? What about if age = 15?

When you want to force exactly 1 of 2 blocks to execute (as opposed to just skipping a block), you can use the else command in addition to the if command. If the expression following the if command is true, then the first block executes. Otherwise, the second block executes.

Example 7 - If-Else Statements
  • No matter how you change the scores, only 1 print() function executes.

  • Try making the scores the same.

In order to force exactly 1 of more than 2 blocks to execute, you can use the elif command in addition to the if and else commands. Each elif command must be followed by a Boolean expression. When using if and elif commands, each expression is checked in sequential order, and the block following the first true expression executes. If none of the expressions are true, the block following the else command is executed.

Example 8 - If-Elif-Else Statements
  • Even though several of the Boolean expressions are true when temp = 83, only the block after the first such expression executes.

  • Try several different values of temp and see what is printed.

3.7. While Statements

Python can execute a block repeatedly using a while statement and a Boolean expression. The block repeats until the Boolean expression is false.

Example 9 - While Statements

What numbers do you think will print? Notice that, without line 3, the loop would run forever.

The += operator increases the value of the variable written to the left of the operator by the value written to the right of the operator.

3.8. Lists and Loops

When you need to consider many values at once, use a list.

Example 10 - List Indexing

Try index -2.

When you want to consider every value in a list, use a for loop.

Example 11 - For Loops With Indices
  • What does the variable i represent?

  • What line creates the variable i?

  • What line modifies it?

The range() function returns a sequence of numbers. The sequence starts at the value given by the first argument, increments by 1, and ends at one less than the value given by the second argument. For example, range(2,5) returns 2,3,4. If only one argument is given, that argument is considered the second argument and the first argument is set to 0 by default. For example, range(4) returns 0,1,2,3.
Example 12 - For Loops Without Indices
  • What line creates the variable x?

  • What line modifies it?

Example 13 - Summing with Loops
  • What line creates the variable g?

  • What line modifies it?

3.9. List Appending and Slicing

We can append to lists with the concatenation operator (+). We can also slice a list using the bracket notation and two indices separated by a colon (:). The first index specifies the starting point of the slice while the second index specifies the stopping point of the slice + 1.

Example 14 - List Appending and Slicing

Try to predict the variable names, values, and data types in the code below. Use the Next button to check your answers.

3.10. Defining Custom Functions

In the examples above we have called several functions like print() and len(). You can define your own functions using def . A function definition includes zero or more parameter variables . The values of those parameter variables are referred to as the arguments of the function.

Example 15 - Defining Functions
  • What line creates the variables a and b?

  • When does that line execute?

  • How many times?

  • Where do the variables a and b get their values from?

3.11. Exercises

  1. Given the following Python code, what is the value and data type of each variable?

    a = 6 + 8
    large = a // 4
    b = 22 // 3
    c = 22 % 3
    d = False or True
    e = True and False
    sheep = (True or (b > 10))
  2. Given the following Python code, determine the printed output.

    print("Hello World!")
    a = "The answer is"
    b = 6 * 7
    print(a, b)
    print(False, "Hobbit", 1, "Ring")
  3. For the following code, determine the value of the variable letter when the score is 92, 84 and 59.

    score = #an interger between 0 and 100
    if score >= 90:
    	letter = 'A'
    elif score >= 80:
    	letter = 'B'
    elif score >= 70:
    	letter = 'C'
    elif score >= 60:
    	letter = 'D'
    else:
    	letter = 'F'
  4. For the following code, determine the value of the variable ans for each case given below.

    if outside == False:
    	if (n >= 2 and n <= 20):
    		return ans = True
    	else:
    		return ans = False
    else:
    	if (n <= 2 or n >= 20):
    		return ans = True
    	else:
    		return ans = False
    1. n = 3, outside = False

    2. n = 15, outside = False

    3. n = 15, outside = True

    4. n = 12, outside = True

  5. What will this code print out?

    while count > 0:
    	print("Welcome")
    	count -= 1
  6. Write Python code to satisfy the following conditions. Then test your code on the values of the variables given.

    1. Given an int n, return the absolute diffrence between n and 10, except return triple the absolute dfference if n is over 10. It should return 1 when n=9. It should return 33 when n=21. What will the code return when n=7 or n=35?

    2. We have a loud talking robot. The "hour" parameter is the current hour time in the range 0 to 23. We are in trouble if the robot is talking and the hour is before 6 or after 21. Return True if we are in trouble. It should return True when the robot is talking and the hour is 8. It should return False when the robot is not talking and the hour is 8. What does it return if the robot is talking and the hour is 9?

  7. What will the following code print out?

    numbers = [1, 3, 5, 7, 10]
    sq = 0
    for val in numbers:
    	sq = val * val
    	print(sq)
  8. What will the following code print out?

    for i in range(1, 20, 2):
    	print(i)
  9. Use the following definition of the function front3() to find the output of the program for the list [1, 3, 5, 7].

    def front3(nums):
    	i = 0
    	while (i < len(nums) and i < 5):
    		if nums[i] == 3:
    			return True
    		i += 1
    	return False
  10. Write a function that takes, as input, two lists of integers, a and b, both of length 3, and returns, as output, a new list of length 2 containing the last elements of a and b. For example, if a = [1, 2, 3] and b = [10, 20, 30], then the function should return the list [3, 30].