Python
Introduction to Programming
with Python
Adapted from: https://homes.cs.washington.edu/~stepp/bridge/2007/python.ppt
Programming basics
code or source code: The sequence of instructions in a program.
syntax: The set of legal structures and commands that can be used
in a particular programming language.
output: The messages printed to the user by a program.
console: The text box onto which output is printed.
Some source code editors pop up the console as an external window,
and others contain their own console window.
2
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class
Python is instead directly interpreted into machine instructions.
interpret
source code output
Hello.py
3
Online Python Tutor
http://www.pythontutor.com/visualize.html#mode=edit
4
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication,
division
% modulus, a.k.a. remainder
precedence: Order in which operations are computed.
* / % ** have a higher precedence than + -
1 + 3 * 4 is 13
Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16
5
Integer division
When we divide integers with /
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
More examples:
35 / 5 is 7 (Python 2.X)
84 / 10 is 8 (Python 2.X)
156 // 100 is 1 (Python 3.X)
The % operator computes the remainder from a division of integers.
3 43
4 ) 14 5 ) 218
12 20
2 18
15
3
6
Real numbers
Python can also manipulate real numbers.
Examples: 6.022 -15.9997 42.0 2.143e17
The operators + - * / % ** ( ) all work for real numbers.
The / produces an exact answer: 15.0 / 2.0 is 7.5
The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -
When integers and reals are mixed, the result is a real number.
Example: 1 / 2.0 is 0.5
7
Variables
variable: A named piece of memory that can store a value.
Usage:
Compute an expression's result,
store that result into a variable,
and use that variable later in the program.
assignment statement: Stores a value into a variable.
Syntax:
name = value
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
A variable that has been given a value can be used in expressions.
x + 4 is 9
8
print
print() : Produces text output on the console.
Syntax:
print(“Message”)
print(Expression)
Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print(Item1, Item2, ..., ItemN)
Prints several messages and/or expressions on the same line.
Examples:
print('Hello, world!')
age = 45
print('You have', 65 - age, 'years until retirement')
Output:
Hello, world!
You have 20 years until retirement
9
input
input : Reads a number from user input.
You can assign (store) the result of input into a variable.
Example:
age = int(input("How old are you? "))
print("Your age is", age)
print("You have", 65 - age, "years until retirement")
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
10
Repetition (loops)
and Selection (if/else)
11
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
for variableName in groupOfValues:
statements
We indent the statements to be repeated with tabs or spaces.
variableName gives a name to each value, so you can refer to it in the statements.
groupOfValues can be a range of integers, specified with the range function.
Example:
for x in range(1, 6):
print(x, "squared is", x * x)
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
12
range
The range function specifies a range of integers:
range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
It can also accept a third value specifying the change between values.
range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
Example:
for x in range(5, 0, -1):
print (x)
print (“Blastoff!”)
Output:
5
4
3
2
1
Blastoff!
13
Cumulative loops
Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print ("sum of first 10 squares is", sum)
Output:
sum of first 10 squares is 385
14
if
if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
Syntax:
if condition:
statements
Example:
gpa = 3.4
if gpa > 3.0:
print ("Your application is accepted.“)
15
if/else
if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
Syntax:
if condition:
statements
else:
statements
Example:
gpa = 1.4
if gpa > 2.0:
print ("Welcome to Mars University!”)
else:
print ("Your application is denied.”)
Multiple conditions can be chained with elif ("else if"):
if condition:
statements
elif condition:
statements
else:
statements
16
while
while loop: Executes a group of statements as long as a condition is True.
good for indefinite loops (repeat an unknown number of times)
Syntax:
while condition:
statements
Example:
number = 1
while number < 200:
print (number, end = “ ”)
number = number * 2
Output:
1 2 4 8 16 32 64 128
17
Logic
Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
Logical expressions can be combined with logical operators:
Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False
18
Text and File Processing
19
Strings
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
A string can represent characters by preceding them with a backslash.
\t tab character
\n new line character
\" quotation mark character
\\ backslash character
Example: "Hello\tthere\nHow are you?"
20
Indexes
Characters in a string are numbered with indexes starting at 0:
Example:
name = "P. Diddy"
index 0 1 2 3 4 5 6 7
characte P . D i d d y
r
Accessing an individual character of a string:
variableName [ index ]
Example:
print(name, "starts with", name[0])
Output:
P. Diddy starts with P
21
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print (big_name, "has", length, "characters”)
Output:
MARTIN DOUGLAS STEPP has 20 characters
22
Text processing
text processing: Examining, editing, formatting text.
often uses loops that examine the characters of a string one by one
A for loop can examine each character in a string in sequence.
Example:
for c in "booyah":
print (c)
Output:
b
o
o
y
a
h
23
File processing
Many programs handle data, which often comes from files.
Reading the entire contents of a file:
variableName = open("filename").read()
Example:
file_text = open("bankaccount.txt").read()
24
Line-by-line processing
Reading a file line-by-line:
for line in open("filename").readlines():
statements
Example:
count = 0
for line in open("bankaccount.txt").readlines():
count = count + 1
print ("The file contains", count, "lines.”)
25
Dictionaries
26
Dictionaries
Dictionary: Dictionaries are lookup tables.
They map from a “key” to a “value”.
To create a dictionary use {}
Examples:
symbol_to_name = {}
Symbol_to_name[‘H’] = ‘Hydrogen’
<Or>
symbol_to_name = {
"H": "hydrogen",
"He": "helium",
"Li": "lithium",
"C": "carbon",
"O": "oxygen",
"N": "nitrogen"
}
Duplicate keys are not allowed
Duplicate values are just fine
27
Dictionaries
There is no order like in ‘strings’. So Symbol_to_name[0] will give an error
Keys can be any immutable value: numbers, strings, tuples,
atomic_number_to_name = {
1: "hydrogen"
6: "carbon",
7: "nitrogen"
8: "oxygen",
}
One key can have multiple values too (Like synonyms in English)
Synonyms = {}
Synonyms[‘mutable’] = [‘Changeable’, ‘vulnerable’,…]
Dictionaries
Getting the value for a given key
Example:
print (symbol_to_name["C"])
Output:
'carbon'
Testing if the key exists (“in” only checks the keys, not the values.)
Example:
print ("O" in symbol_to_name)
print ("U" in symbol_to_name)
Output:
True
False
Example:
print ("oxygen" in symbol_to_name)
Output:
False
Resources
30
Resources
Python:
https://www.w3schools.com/python/
http://learnpythonthehardway.org/book/
http://python-future.org/compatible_idioms.html
Regular Expression:
https://www.summet.com/diveintopython3/regular-expressions.html
http://regexr.com
Beautiful Soup:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
https://
codeburst.io/web-scraping-101-with-python-beautiful-soup-bb617be
1f486
31