Review on the Python Programming Language
Review on the Python Programming Language
Objectives
At the end of this module, students are expected to:
1. Review the ins and outs of the Python programming language;
2. Refresh themselves on creating Python programs; and
3. Utilize the Python concept discussed below for the activities in CC3
Topics
1. Introduction to Python
2. Python Data Types, Variables, Expressions and Statements
3. Python Inputs and Outputs
4. Python Sequence Structure
5. Python Decision Control Structure
6. Python Functions
Module Content
What is Python?
1. Python is an interpreted, object-oriented, high-level programming
language.
2. Python’s simple, easy to learn syntax emphasizes readability and therefore
reduces the cost of program maintenance.
3. Python supports modules and packages, which encourages modularity.
Variables
1. To create a variable in Python, you specify the variable name, and then
assign a value to it:
a. <variable name> = <value>
2. Python makes use of “=“ to assign values to variables.
3. There is no need to declare a variable in advance (or assign a data type
to it).
4. Assigning a value to a variable itself declares and initializes the variable
with that value.
5. You cannot declare a variable without assigning it an initial value.
a. a = 3
b. print(a) # Outputs 3
6. Variable assignment works from left to right.
7. Python variable names are case sensitive.
Comments
1. The most common way to write a comment in Python is to begin a new
line in your code with the “#” character.
2. When you run your code, Python ignores lines starting with “#”.
3. Comments that start on a new line are called block comments.
4. You can also write inline comments, which are comments that appear on
the same line as the code they reference.
5. Place a “#” at the end of the line of code, followed by the text in your
comment.
a. # This is a block comment
b. greeting = "Hello World"
c. print(greeting) # This in an inline comment
Data Types
1. There are five main data types that you can make use of in Python.
2. These are:
a. Integer
i. These are zero, positive, negative, whole numbers.
1. x = 10000000
2. print(x) # Outputs 10000000
ii. Integers can also be binary values:
1. binaryVar = 0b1010
2. print(binaryVar) # Binary: Outputs 10
iii. Integers can also be octal values:
1. octalVar = 0o14
2. print(octalVar) # Octal: Outputs 12
iv. Integers can also be hexadecimal values:
1. hexadecimalVar = 0xF
2. print(hexadecimalVar) # Hexadecimal: Outputs 15
b. Floating Point
i. This represents a floating-point number.
ii. They are represented with a decimal point.
1. x = 9.999999999999
2. print(x) # Outputs 9.999999999999
iii. You can also make use of negative values for the floating-
point number.
1. x = -73.435
2. print(x) # Outputs -73.435
c. String
i. Strings are a sequence of bytes representing Unicode
characters.
ii. There are several ways to create a string.
iii. They differ based on the delimiters and whether a string is
single or multiline.
iv. Double Quote Delimiters
1. This makes use of double quotes to define the string.
a. string = "Flying Eagle"
b. print(string) # Outputs Flying Eagle
2. A string delimited with double quotes is helpful for
strings containing single quotes or apostrophes.
a. print("You can place single quotes like 'this'") #
Outputs You can place single quotes like 'this'
v. Single Quote Delimiters
1. This makes use of single quotes to define the string.
a. string = 'Diving Whale'
b. print(string) # Outputs Diving Whale
2. A string delimited with single quotes is helpful for strings
containing double quotes or apostrophes.
a. print('You can place double quotes like "this"') #
Outputs You can place double quotes like "this“
vi. Triple Quote Delimiters
1. This allows you to make multiline strings and assign them
to a variable.
a. string = """This string spans
b. multiple lines
c. with the use of triple quotes"""
d. print (string)
d. Boolean
i. Boolean data types determine the truth value of expressions.
ii. They can either be True or False.
1. booleanVal = True
2. print(booleanVal) # Outputs True
e. Null
i. This type is used to define a null variable or object.
ii. It makes use of the “None” keyword.
iii. We can assign “None” to any variable.
iv. It can also be used in Expressions.
1. emptyVal = None
2. print(emptyVal) # Outputs None
Python Input
1. There are two basic methods in getting user inputs in Python.
2. These are raw_input() and input().
3. The syntax for these are
a. raw_input([prompt])
i. raw_input will wait for the user to enter text and then return
the result as a string.
ii. This is available in Python 2
1. foo = raw_input("Put a message here that asks the user
for input")
b. input([prompt])
i. input will wait for the user to enter text and then return the
result as a string.
ii. This is available in Python 3
1. foo = input("Put a message here that asks the user for
input")
4. Casting – allows you to specify or convert a type of a variable.
a. You can enclose the input method in the int() or float() methods to
convert the input into an integer or float, respectively.
b. Type casting to integer or float is needed if you would like to use the
input of the user in an arithmetic computation.
Python Output
1. The print() statement allows you to print an output in Python.
2. By default, it ends the output by adding a new line.
3. You can change this with the end parameter.
a. print("Hello, ", end="\n")
4. You could pass in other strings in this parameter.
a. print("Hello, ", end="")
b. print("World!")
c. # Hello, World!
Lists
1. A list functions similarly to an array in other languages.
2. In Python, a list is merely an ordered collection of valid Python values.
3. A list can be created by enclosing values, separated by commas, in
square brackets:
a. int_list = [1, 2, 3]
b. string_list = ['abc', 'defghi']
4. A list can be empty:
a. empty_list = []
5. The elements of a list are not restricted to a single data type, which makes
sense given that Python is a dynamic language:
a. mixed_list = [1, 'abc', True, 2.34, None]
6. A list can contain another list as its element:
a. nested_list = [['a', 'b', 'c'], [1, 2, 3]]
7. List Functions:
a. Append object to end of list with List.append(object).
b. Add a new element to list at a specific index with the command
List.insert(index, object)
c. Remove the first occurrence of a value with Lists.remove(value)
d. Get the index in the list of the first item whose value is x using
Lists.index(index)
e. Count length of list using len(List)
f. Count occurrence of any item in list using List.count(value)
g. Reverse the list using List.reverse()
h. Remove and return item at index (defaults to the last item) with
List.pop([index])
Tuples
1. A tuple is like a list except that it is fixed length and immutable.
2. Immutable means the values in the tuple cannot be changed nor the
values be added to or removed from the tuple.
3. Tuples are represented with parentheses instead of square brackets:
a. ip_address = ('10.20.30.40', 8080)
4. The same indexing rules for lists also apply to tuples.
5. A tuple with only one member must be defined (note the comma) this
way:
a. one_member_tuple = ('Only member',)
b. or
c. one_member_tuple = 'Only member', # No brackets
d. or just using tuple syntax
e. one_member_tuple = tuple(['Only member'])
Dictionaries
1. A dictionary in Python is a collection of key-value pairs.
2. The dictionary is surrounded by curly braces.
3. Each pair is separated by a comma and the key and value are separated
by a colon.
4. Here is how you declare a dictionary:
a. state_capitals = {
b. 'Arkansas': 'Little Rock',
c. 'Colorado': 'Denver',
d. 'California': 'Sacramento',
e. 'Georgia': 'Atlanta'
f. }
5. To get a value, refer to it by its key:
a. ca_capital = state_capitals['California']
6. You can add a new value to a dictionary by using this syntax:
a. dictionary_name[key] = value
b. state_capitals[‘Hawaii’] = ‘Honolulu’
7. You can also delete a value from a dictionary using this syntax:
a. del dictionary_name[key]
b. del state_capitals['California']
Special Operators
1. “and” operator – a special operator which allow you to judge if all
arguments in a set are True.
a. The and operator is used to check if two variables are true.
i. x = True
ii. y = True
iii. z = x and y # z = True
b. Both values being compared must be True, otherwise, the result of
the and operator will be False.
i. x = True
ii. y = False
iii. z = x and y # z = False
c. The and operator can also evaluate numerical and string values,
but it behaves differently in these cases.
d. The and operator evaluates to the second argument if and only if
both arguments are True (they don’t contain 0 or an empty string).
e. Otherwise, it evaluates to the first False argument.
2. “or” operator – a special operator which allows you to judge if at least
one argument in a set is True.
a. The or operator is used to check if at least one variable in a set is
True.
i. x = True
ii. y = False
iii. z = x or y # z = True
b. At least one of the values being compared must be True, otherwise,
the result of the or operator will be False.
i. x = False
ii. y = False
iii. z = x or y # z = False
c. The or operator can also evaluate numerical and string values, but
it behaves differently in these cases.
d. The or operator evaluates to the first True argument if and only if at
least one of the arguments is True (they don’t contain 0 or an empty
string).
e. Otherwise, it evaluates to the second argument.
IF Statement
1. The IF statement is one of the most used conditional statements in
programming languages.
a. It checks for a given condition, if the condition is True, then the set
of code present inside the IF block will be executed otherwise not.
b. The IF statement evaluates a Boolean expression and executes the
block of code only when the Boolean expression is True.
c. The syntax for the IF statement is shown below:
i. if condition:
ii. body
d. The IF statement checks the condition. If it evaluates to True, it
executes the body of the IF statement. If it evaluates to False, it skips
the body.
i. if True:
ii. print "It is true!"
iii. >> It is true!
iv. if False:
v. print "This won't get printed.."
e. Always remember that in Python, a positive integer will be treated
as True value and an integer equal to 0 will be treated as False.
i. a = 7
ii. b = 0
iii. if (a):
iv. print(“true”)
ELIF Statement
1. The ELIF statement is used to check additional conditions if the first
condition (usually the IF statement) is evaluated as False.
a. a = 5
b. b = 5
c. if b > a:
d. print("b is greater than a")
e. elif a == b:
f. print("a and b are equal")
2. When adding multiple conditions, it is generally better to use the ELIF
statement instead of adding multiple IF statements.
3. This is because the ELIF statements will not execute if the IF statement is
already found to be True.
4. You can use multiple IF statements instead of using ELIF, but this is
generally not recommended.
ELSE Statement
1. The ELSE statement is used if none of the previous conditions are met.
a. if condition:
b. body
c. else:
d. body
2. The ELSE statement will execute its body only if preceding conditional
statements all evaluate to False, otherwise, it will not be executed.
a. if True:
b. print "It is true!"
c. else:
d. print "This won't get printed.."
e. # Output: It is true!
3. Nested IF-ELSE statements mean that an IF statement or ELIF statement is
present inside another IF or ELIF block.
• if(condition):
• #Statements to execute if condition is true
• if(condition):
• #Statements to execute if condition is true
• #end of nested if
• #end of if
Python Loops
1. The most common term to describe repetition control structures is a loop.
2. Loops have two parts:
a. Condition – The logic that evaluates a condition.
b. Body – This is where the code integral to the loop is located.
WHILE Loops
1. The WHILE statement is a statement in Python that repeatedly executed a
block of statements if a test at the top keeps evaluating to a true value.
2. When the test in the WHILE statement becomes false, control passes to the
statement that follows the WHILE block.
3. The effect of this is that the statements in the WHILE block are executed
repeatedly while the test is true.
4. If the test is false to begin with, the body never runs.
5. The WHILE statement consists of a header line with a test expression, a
body of one or more indented statements, and an optional else that is
executed if control exits the loop without a break statement.
6. The general format of the WHILE statement is as follows:
a. while <test>: # Loop test/condition
b. <statements1> # Loop Body
c. else: # Optional else
d. <statements2> # Runs if didn’t exit loop with break
7. You can place a variable as part of the test in a WHILE loop.
8. This allows you to assign a value that can stop the loop when it is no
longer needed.
9. An example of this is shown here:
a. x = True
b. while x:
c. print("wow!") # prints a single "wow!"
d. x = False
FOR Loop
1. A FOR loop in Python is used for iterating a sequence (a list, a tuple, a
dictionary, a set, or a string).
2. The FOR loop can execute a set of statements, once for each item in a
list, tuple, dictionary, etc.
3. The python FOR loop begins with a header line that specifies an
assignment target, along with the object you want to step through.
4. The header is followed by a block of statements you want to repeat:
a. for <target> in <object>: # Assign object items to target
b. <statements> # Repeated loop body: use target
c. else:
d. <statements> # If we didn't hit a 'break'
Functions
1. Functions in Python provide organized, reusable, and modular code to
perform a set of specific actions.
2. Functions simplify the coding process, prevent redundant logic, and
makes code easier to follow.
3. Python has many built-in functions like print(), input(), len(), etc.
4. You can also create your own functions, called user-defined functions.
User-defined Functions
1. These are functions defined by the user to do more specific jobs.
2. Using the “def” statement is the most common way to define a function in
Python.
3. This type of statement is called a single clause compound statement with
the following syntax:
a. def function_name(parameters):
b. statement(s)
i. function_name - is the identifier of the function.
ii. parameters - is an optional list of identifiers that get bound to
the values supplied as arguments when the function is called.
iii. statement(s) - also known as the function body - are a
nonempty sequence of statements executed each time the
function is called.
4. Here is an example of a user defined function:
a. def greeting():
b. print("Hello and Good day!")
5. You can also set a default value for a function parameter:
a. def greeting(name="User"):
b. print("Hello " + name + "!")
6. Just to be clear on the terminology:
a. Argument (actual parameter): the actual variable being passed to
a function.
b. Parameter (formal parameter): the receiving variable that is used in
a function.
c. In Python, arguments are passed by assignment.
Nested Functions
1. You can place functions inside another function.
2. This works similarly to nested lists or IF statements.
3. Parameters passed to the outer function are also passed to the inner
function.
4. An example of a nested function is shown below:
a. def func1(x):
b. def func2():
c. print("Hello " + x + "!")
d. func2()
e. func1("Jim") # Outputs "Hello Jim!"
Learning Resources
1. PowerPoint Presentation (Available on the Canvas Module)
a. Review Module
2. Reading Material
a. Free Python Programming Book (goalkicker.com)
References
1. Lutz, M. (2009). Learning Python (4th Edition). O’Reily: California, USA
2. Goalkicker.com. (2020). Python Notes for Professionals. Retrieved from
https://books.goalkicker.com/PythonBook/
3. w3schools. (n.d.) Python Tutorial, w3schools.com. Retrieved from
https://www.w3schools.com/python/default.asp