Python Basics

Getting Started

Python is an immensely popular programming language because it is designed to be readable and easy to use. There are several notebook formats for Python that allow code to be written and executed in blocks, with outputs displayed immediately below each code block. In this class, we will use the free web-based Python notebook application Google Colab.

Problem 0

Follow the instructions on Setting Up Google Colab to create a copy of the Google Colab template notebook for this lab. Type the following into a Code cell in your new notebook.

print("Hello, world!")

Execute the cell with shift+enter. You should see the message printed below the cell.

Hello, world!

You have just executed a single line of Python code!

A Computer Science Tradition

Displaying Hello, world! is the traditional first problem when learning a programming language.

Data Types

Computers represent different types of information as different data types. The data type determines how a value is stored, displayed, and what operations make sense for that value. The three most important Python data types for this course are listed in the following table.

Type

Description

Syntax

Examples

int

integers

numbers without a period

3, 0, -40, 34253472

float

decimals

numbers with a period

3.1415, -0.23, .4, 1.0, 3.

str

text

surrounded by quotation marks

"Hello", "X", "3.1415"

Strings

The str data type represents text. In computer programming, a chunk of text is called a string, as in “a string of characters.” Strings start and end with matching quotation marks and are always treated as text, even if they look like a number. For instance, "Hello, world!" and "3.1415" are both strings.

Strings are usually defined on a single line. A longer string can be defined over multiple lines using triple quotation marks.

# Display a string that takes up at most one line.
print("Peter Piper picked a peck of pickled peppers")

# Display a string that takes up several lines, including a few blank lines.
print("""A peck of pickled peppers...

(pause for dramatic effect)

Peter Piper picked!
""")
Peter Piper picked a peck of pickled peppers
A peck of pickled peppers...

(pause for dramatic effect)

Peter Piper picked!

Comments

In Python, any text after a # character is called a comment and is completely ignored by the program. In the last example, the line

# Display a string that takes up at most one line.

is a comment. The main purpose of a comment is to describe to the programmer what the code near the comment is supposed to be doing.

Even though comments do not affect the behavior of a program, descriptive comments are extremely important for readable code. Without comments, the human programmer must interpret code using only the syntax of the programming language; with comments, a programmer can see the intention, design, and nuances of a piece of code.

Get in the habit now of writing informative comments for every few lines of code. This will help you organize your thoughts as you design a program and help you pick up where you left off after a break.

Single and Double Quotes

The standard convention is to use double quotes to define strings, such as "Hello!". Single quotes also define strings, for example, 'Hello!', but we recommend always using double quotes.

Integers

The int data type represents integers, that is, whole (non-decimal, non-fractional) numbers. In Python, integers are simply numbers without a decimal point. Use - to indicate a negative number.

print(3)
print(0)
print(-10)
3
0
-10

Decimals

The float data type is used to represent real-valued numbers, including decimals. Not all decimals can be represented perfectly on a computer; irrational numbers like \(\pi\) have infinitely many digits, and even some finite decimals like 0.1 do not have an exact binary representation. Still, float is accurate enough for most standard computations. The word “float” is short for “floating point,” a reference to how the decimal point “floats” between digits when using scientific notation.

\[ 12345.67 = 1.234567 \times 10^{4} \]

Numbers with a decimal point are represented as a float, even if the number equals an integer.

print(1.23)
print(4.0)
print(5.)  # Same as 5.0
print(.6)  # Same as 0.6
print(0.7)
1.23
4.0
5.0
0.6
0.7

Other Data Types

Python has several other built-in data types. For example, complex is used to represent imaginary and complex numbers. We will introduce a few additional data types later on as needed.

Arithmetic

Arithmetic expressions consist of operators, such as + (addition), and operands, the values on either side of an operator. For example, in the expression 2 + 3, the operator is +, and the operands are 2 and 3. Python includes the following arithmetic operators.

Operator

Description

+

addition

-

subtraction

*

multiplication

/

division

//

integer/floor division

%

remainder after integer division

**

exponentiation

Numerical Arithmetic

What an operator does and the data type of the result depend on the data types of the operands.

  • If both operands are of type int, then most arithmetic operators return an int.

  • If one or both operands is a float, then the result is usually a float.

  • Division with / always results in a float.

# An int plus an int is another int.
print(1 + 2)

# An int minus a float is a float.
print(6 - 3.0)

# A float times a float is another float.
print(5.0 * 4.0)
3
3.0
20.0
# An int multiplied by an int is another int.
print(3 * 5)

# An int raised to a nonnegative integer power is another int.
print(3**5)

# A number divided by a number is always a float.
print(3 / 5)
print(6 / 3)
print(6.0 / 3.0)
15
243
0.6
2.0
2.0

Exponentiate with **

There is a ^ operator in Python, but it performs a bitwise XOR operation, not exponentiation.

The // operator does division then rounds down to an integer. The % operator (called the modulo or mod operator) calculates the remainder of this kind of division.

# 17 divided by 3 is 5 with remainder 2.
print(17 // 3)
print(17 % 3)
5
2

Python follows the conventional order of operations: parentheses, exponentiation, multiplication and division, then addition and subtraction.

print(2 + 3 * 4)  # 2 + (3 x 4) = 2 + 12 = 14.
print((2 + 3) * 4)  # (2 + 3) x 4 = 5 x 4 = 20.
14
20

Quick Check

Consider the expression

\[ \frac{118 + 11 \times 2}{9 - 2}. \]

Which of the following lines of code correctly computes this expression?

1118 + 11 * 2 / 9 - 2
2118 + (11 * 2) / 9 - 2
3118 + (11 * 2) / (9 - 2)
4(118 + 11 * 2) / 9 - 2
5(118 + (11 * 2)) / (9 - 2)
6(118 + 11) * 2 / (9 - 2)
Answer
(118 + (11 * 2)) / (9 - 2)

String Arithmetic

Some arithmetic operators can also be used for non-numerical data types, such as str.

  • When both operands are of type str, the + operator joins the two into a new str.

  • When one operand is a str and the other is an int, the * operator repeats the str.

  • Other arithmetic operations are not defined for strings.

# Join two strings together.
print("Hello, " + "world!")

# Repeat a string a given number of times.
print("Hello" * 3)
Hello, world!
HelloHelloHello
# Subtraction is not defined for strings.
print("Hello, world!" - "world!")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[9], line 2
      1 # Subtraction is not defined for strings.
----> 2 print("Hello, world!" - "world!")

TypeError: unsupported operand type(s) for -: 'str' and 'str'