PYTHON
Words
Characters
Grammar Language
Stories
Sentences
Syntax
CWI
Guido van Rossum
Textbook 1: Al Sweigart, “Automate the Boring Stuff with Python”,1stEdition, No
Starch Press, 2015.
Textbook 2: Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”,
2nd Edition,Green Tea Press, 2015.
MODULE 1
Python Flow Functions
Basics Control
Entering Expressions into the Interactive Boolean Values, Comparison def Statements with Parameters,
Shell, The Integer, Floating-Point and Operators, Boolean Operators , Mixing return Statements, The None Value,
String Data Types….. Boolean and Comparison Operators…. Keyword Arguments and print()…
Python
Basics
Entering Expressions into the Interactive Shell, The Integer, Floating-Point,
and String Data Types, String Concatenation and Replication, Storing Values
in Variables, Your First Program, Dissecting Your Program
Entering Expressions into the Interactive Shell
• You run the interactive shell by launching IDLE
• The ** operator is evaluated first;
• the *, /, //, and % operators are evaluated next, from left to right;
• the + and - operators are evaluated last (also from left to right).
The Integer, Floating-Point, and String Data Types
• Remember that expressions are just values combined with operators, and they always
evaluate down to a single value.
• A data type is a category for values, and every value belongs to exactly one data type.
• If you ever see the error message SyntaxError: EOL while scanning string literal, you
probably forgot the final single quote character at the end of the string
String Concatenation and Replication
• The meaning of an operator may change based on the data types of the values next to it.
• However, when + is used on two string values, it joins the strings as the string
concatenation operator.
>>> 'Alice' + 'Bob’
'AliceBob’
>>> 'Alice' + 42
?
>>> 'Alice' * 5
?
>>> 'Alice' * 'Bob’
?
Storing Values in Variables
• A variable is like a box in the computer’s memory where you can store a single value.
Assignment Statements
• You’ll store values in variables with an assignment statement.
• An assignment statement consists of a variable name, an equal sign (called the assignment
operator), and the value to be stored.
spam = 42,
• When a variable is assigned a new value , the old value is
forgotten.
• This is called overwriting the variable.
Storing Values in Variables cont….
Variable Names
• You can name a variable anything as long as it obeys the following three rules:
1. It can be only one word.
2. It can use only letters, numbers, and the underscore (_) character.
3. It can’t begin with a number.
Valid variable names Invalid variable names
balance current-balance (hyphens are not allowed)
currentBalance current balance (spaces are not allowed)
current_balance 4account (can’t begin with a number)
_spam 42 (can’t begin with a number)
SPAM total_$um (special characters like $ are not allowed)
account4 'hello' (special characters like ' are not allowed)
*Variable names are case-sensitive
Your First Program
• While the interactive shell is good for running Python instructions one at a time, to write
entire Python programs, you’ll type the instructions into the file editor.
• The file editor lets you type in many instructions, save the file, and run the program.
# This program says hello and asks for my name.
print('Hello world! ')
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
End
of
Chapter 1
Flow Control
Boolean Values, Comparison Operators, Boolean Operators,
Mixing Boolean and Comparison Operators, Elements of Flow Control,
Program Execution, Flow Control Statements, Importing Modules , Ending a
Program Early with sys.exit()
Boolean Values
• Boolean data type has only two values: True and False.
• When typed as Python code, the Boolean values True and False lack the quotes you place
around strings, and they always start with a capital T or F, with the rest of the word in
lowercase.
• Boolean values are used in expressions and can be stored in variables.
• If you don’t use the proper case or you try to use True and False for variable names ,
Python will give you an error message.
Operator Meaning
Comparison Operators == Equal to
!= Not equal to
• Comparison operators compare
< Less than
two values and evaluate down to
> Greater than
a single Boolean value.
<= Less than or equal to
>= Greater than or equal to
Comparison Operators cont…
• The == and != operators can actually • The <, >, <=, and >= operators, on the
work with values of any data type. other hand, work properly only with
>>> 'hello' == 'hello' integer and floating-point values.
True >>> 42 < 100
>>> 'hello' == 'Hello' True
False >>> 42 > 100
>>> 'dog' != 'cat' False
True >>> 42 < 42
>>> True == True False
True >>> penCount = 42
>>> True != False >>> penCount <= 42
True True
>>> 42 == 42.0 >>> myAge = 29
True >>> myAge >= 10
>>> 42 == '42' True
False
Boolean Operators
• The three Boolean operators (and, or, and not) are used to compare Boolean values. Like
comparison operators, they evaluate these expressions down to a Boolean value.
Binary Boolean Operators
• The and and or operators always take two Boolean values (or expressions), so they’re
considered binary operators.
• The and operator evaluates an expression to True if both Boolean values are True;
otherwise, it evaluates to False.
• On the other hand, the or operator evaluates an expression to True if either of the two
Boolean values is True. If both are False, it evaluates to False.
The not Operator
• Unlike and and or, the not operator operates on only one Boolean value (or expression).
The not operator simply evaluates to the opposite Boolean value.
Mixing Boolean and Comparison Operators
• the and, or, and not operators are called Boolean operators because they always operate
on the Boolean values True and False.
• While expressions like 4 < 5 aren’t Boolean values, they are expressions that evaluate
down to Boolean values.
>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
• The computer will evaluate the left expression first, and then it will evaluate the right
expression.
Elements of Flow Control
• Flow control statements often start with a part called the condition, and all are followed
by a block of code called the clause.
Conditions
• condition is just a more specific name in the context of flow control statements.
Conditions always evaluate down to a Boolean value, True or False.
Blocks of Code
• Lines of Python code can be grouped together in blocks. You can tell when a block
begins and ends from the indentation of the lines of code.
• There are three rules for blocks.
1. Blocks begin when the indentation increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing
block’s indentation.
Code on page number 38
Flow Control Statements
if Statements
• An if statement’s clause will execute if the statement’s condition is True. The clause is
skipped if the condition isFalse.
• In Python, an if statement consists of the following:
• The if keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the if clause)
Flow chart on page number 39
else Statements
• An if clause can optionally be followed by an else statement. The else clause is executed
only when the if statement’s condition is False.
• An else statement doesn’t have a condition, and in code, an else statement always
consists of the following:
• The else keyword
• A colon
• Starting on the next line, an indented block of code (called the else clause)
Flow chart on page number 40
elif Statements
• The elif statement is an “else if” statement that always follows an if or another elif
statement.
• It provides another condition that is checked only if any of the previous conditions were
False.
• In code, an elif statement always consists of the following:
• The elif keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif clause)
Flow chart on page number 41 and 42
while Loop Statements
• The code in a while clause will be executed as long as the while statement’s condition is
True.
• In code, a while statement always consists of the following:
• The while keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the while clause)
name = ''
Flow chart on page number 47
while name != 'your name’:
An Annoying while Loop print('Please type your name.’)
name = input()
print('Thank you!')
break Statements
• There is a shortcut to getting the program execution to break out of a while loop’s clause
early.
• If the execution reaches a break statement, it immediately exits the while loop’s clause.
• In code, a break statement simply contains the break keyword.
while True:
print('Please type your name.’)
name = input()
if name == 'your name’:
break
print('Thank you!')
• Flow chart on page number 50
continue Statements
• When the program execution reaches a continue statement, the program execution
immediately jumps back to the start of the loop and re-evaluates the loop’s condition.
while True:
print('Who are you?’)
name = input()
if name != 'Joe’:
continue
print('Hello, Joe. What is the password? (It is a fish.)’)
password = input()
if password == 'swordfish’:
break
print('Access granted.')
• There are some values in other data types that conditions will consider equivalent to True
and False. When used in conditions, 0, 0.0, and '' (the empty string) are considered False,
while all other values are considered True.
for Loops and the range() Function
• In code, a for statement looks something like for i in range(5): and always includes the
following:
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)
The Starting, Stopping, and Stepping Arguments to range()
Start (inclusive) End (exclusive) Start (inclusive) End (exclusive)
for i in range(12, 16): for i in range(0, 10, 2):
print(i) print(i) Step size
Importing Modules
• All Python programs can call a basic set of functions called built-in functions, including the
print(), input(), and len().
• Python also comes with a set of modules called the standard library. Each module is a
Python program that contains a related group of functions that can be embedded in your
programs.
• For example, the math module has mathematics related functions, the random module
has random number–related functions, and so on.
• Before you can use the functions in a module, you must import the module with an
import statement.
• In code, an import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas
Ending a Program Early with sys.exit()
• you can cause the program to terminate, or exit, by calling the sys.exit() function. Since
this function is in the sys module, you have to import sys before your program can use it.
import sys
while True:
print('Type exit to exit.’)
response = input()
if response == 'exit’:
sys.exit()
print('You typed ' + response + '.')
End
of
Chapter 2
Functions
def Statements with Parameters, Return Values
and return Statements,The None Value, Keyword Arguments and print(), Local and Global
Scope, The global Statement, Exception Handling, A Short Program: Guess the Number
Functions
• A function is like a mini-program within a program.
def hello():
print('Howdy!’)
print('Howdy!!!’)
print('Hello there.')
• A function call is just the function’s name followed by parentheses, possibly with some
number of arguments in between the parentheses.
• When the program execution reaches these calls, it will jump to the top line in the
function and begin executing the code there.
• When it reaches the end of the function, the execution returns to the line that called the
function and continues moving through the code as before.
def Statements with Parameters
• You can also define your own functions that accept arguments.
def hello(name):
print('Hello ' + name)
hello('Alice’)
hello('Bob’)
• One special thing to note about parameters is that the value stored in a parameter is
forgotten when the function returns.
Return Values and return Statements
• In general, the value that a function call evaluates to is called the return value of the
function.
• When creating a function using the def statement, you can specify what the return value
should be with a return statement.
• return statement consists of the following:
• The return keyword
• The value or expression that the function should return
• When an expression is used with a return statement, the return value is what this
expression evaluates to.
Example Code for magic8ball on page number 64
The None Value
• In Python there is a value called None, which represents the absence of a value. None is
the only value of the NoneType data type.
• The print() function displays text on the screen, but it doesn’t need to return anything in
the same way len() or input() does.
• all function calls need to evaluate to a return.
>>> spam = print('Hello!')
Hello!
>>> None == spam
True
• Behind the scenes, Python adds return None to the end of any function definition with no
return statement.value, print() returns None.
• Also, if you use a return statement without a value (that is, just the return keyword by
itself), then None is returned.
Keyword Arguments and print()
• Most arguments are identified by their position in the function call.
• The function call random.randint(1, 10) will return a random integer between 1 and 10,
because the first argument is the low end of the range and the second argument is the
high end (while random.randint(10, 1) causes an error).
• the print() function has the optional parameters end and sep to specify what should be
printed at the end of its arguments and between its arguments (separating them),
respectively.
>>> print('cats', 'dogs', 'mice’)
print('Hello') print('Hello', end='') cats dogs mice
print('World’) print('World’)
Output: Output:
Hello HelloWorld
World >>> print('cats', 'dogs', 'mice', sep=',')
cats,dogs,mice
Local and Global Scope
• Parameters and variables that are assigned in a called function are said to exist in that
function’s local scope. Variables that are assigned outside all functions are said to exist in
the global scope.
• A variable must be one or the other; it cannot be both local and global.
• When a scope is destroyed, all the values stored in the scope’s variables are forgotten.
There is only one global scope, and it is created when your program begins.
• When your program terminates, the global scope is destroyed, and all its variables are
forgotten.
• Scopes matter for several reasons:
• Code in the global scope cannot use any local variables.
• However, a local scope can access global variables.
• Code in a function’s local scope cannot use variables in any other local scope.
• You can use the same name for different variables if they are in different scopes.
That is, there can be a local variable named spam and a global variable also named spam.
Local and Global Scope cont….
• Local Variables Cannot Be Used in the Global Scope
Example on page number 67
• Local Scopes Cannot Use Variables in Other Local Scopes
Example on page number 68
• Global Variables Can Be Read from a Local Scope
Example on page number 69
• Local and Global Variables with the Same Name
Example on page number 69
The global Statement
• If you need to modify a global variable from within a function, use the global statement.
• If you have a line such as global val at the top of a function, it tells Python, “In this
function, eggs refers to the global variable, so don’t create a local variable with this
name.”
def spam():
global val
val = 'spam’
val = 'global’
spam()
print(val)
Output:
spam
The global Statement cotn….
• There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions),
then it is always a global variable.
2. If there is a global statement for that variable in a function, it is a global variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is
a local variable.
4. But if the variable is not used in an assignment statement, it is a global variable.
• In a function, a variable will either always be global or always be local.
Exception Handling
• Right now, getting an error, or exception, in your Python program means the entire
program will crash. You don’t want this to happen in real-world programs.
• Instead, you want the program to detect errors, handle them, and then continue to run.
• Errors can be handled with try and except
def spam(divideBy): statements.
return 42 / divideBy • The code that could potentially have an error is put
print(spam(2)) in a try clause.
print(spam(12)) • The program execution moves to the start of a
print(spam(0)) following except clause if an error happens.
print(spam(1)) • once the execution jumps to the code in the except
clause, it does not return to the try clause.
• Instead, it just continues moving down as normal.
A Short Program: Guess the Number
Code on page number 74
Practice Project on page number 77
End of
Chapter 3