Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Review on the Python Programming Language

This document is a review module for the Python programming language aimed at students of the University of the Cordilleras. It covers key topics such as Python data types, variables, control structures, and the setup of Python locally and online. The module also provides practical examples and explanations to help students create and understand Python programs.

Uploaded by

chakrasgt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Review on the Python Programming Language

This document is a review module for the Python programming language aimed at students of the University of the Cordilleras. It covers key topics such as Python data types, variables, control structures, and the setup of Python locally and online. The module also provides practical examples and explanations to help students create and understand Python programs.

Uploaded by

chakrasgt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

University of the Cordilleras

College of Information Technology and Computer Science


2nd Trimester, School Year: 2021-2022

CC3 – Object Oriented Programming


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.

What makes Python great?


1. Software quality - python’s code is designed to be readable, and hence
reusable and maintainable.
2. Developer productivity - python code is typically smaller than equivalent
C++ or Java code.
3. Program portability - most Python programs run unchanged on all major
computer platforms.
4. Support libraries - python’s functionalities can be extended with
homegrown libraries and third-party application software.
5. Component integration - python scripts can easily communicate with
other parts of an application, using a variety of integration mechanisms.

Setting Up Python Locally


1. Head to https://www.python.org/ and head to the “Downloads” tab.
2. Download the latest version of Python 3.
3. Install Python on to your machine.
4. Start-up IDLE (the default editor that comes with a Python install) to start
writing Python code.
5. You can also make use of an IDE of your choice.

Setting Up Python Locally


1. You can make use of online editors to write and run Python code.
2. One online editor is https://www.programiz.com/python-
programming/online-compiler/ if you would like to quickly run and test
code.
3. You can also make use of Google Collab, which is an online Python
development tool created by Google.
a. You can access it here
https://colab.research.google.com/?utm_source=scs-index.
b. You can save code that you create to your personal Google Drive.

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.

Valid Variable Names


1. Variable names can be as long or as short as you like, but there are a few
rules that you must follow.
a. Variable names may contain uppercase and lowercase letters (A –
Z, a – z), digits (0 – 9), and underscores (__).
b. Variable names must start with a letter or the underscore character.
c. Variable names cannot begin with a digit.
d. Variable names are case-sensitive (age, Age, and AGE are three
different variables).

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

Operators, Expressions and Statements


1. Python has 6 main operators which allow you to make a variety of
calculations.
a. Addition (+)
b. Subtraction (-)
c. Multiplication (*)
d. Division (/)
e. Exponentiation (**)
f. Floor Division (//)
g. Module (%)
2. An expression is a combination of values, variables, and operators.
3. A value by itself is considered an expression in Python, and so is a variable,
so the following are all legal expressions (assuming that the variable “x”
has been assigned to a value):
a. 15
b. x
c. x + 15
4. A statement is a unit of code that the Python interpreter can execute.
5. They are usually written in a single line.
6. Using the “=“ is an example of the assignment statement.
7. Using the “print” function is also an example of a statement.

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!

Python Sequence Structure


1. Sequence – is the generic term for an ordered set.
a. There are several types of sequences in Python, the following three
being the most important.
2. Lists – are the most versatile sequence type and can contain any object.
3. Tuples – are like lists, but they are immutable – they can’t be changed.
4. Dictionary – is a collection of key-value pairs.

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']

Decision Control Structure


1. Conditional expressions, involving keywords such as IF, ELIF, and ELSE,
provide Python programs with the ability to perform different actions
depending on a Boolean condition: True or False.
2. Booleans - represent one of two values: True or False.
3. You can evaluate any expression in Python, and get one of two answers,
True or False.
4. Booleans can be declared as a variable:
a. test = True
5. Booleans can be the result of an equation:
a. print(10 > 9) # Outputs True
b. print(10 == 0) # Outputs False
6. You can also negate or reverse the value of a Boolean variable with not.
a. test = True
b. print(not test) # Outputs False

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

Repetition Control Structure


1. Repetition control structures are also referred to as iterative structures.
2. These are groupings of code which are designed to repeat a set of
related statements.

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

PASS, CONTINUE, BREAK and ELSE Keywords


1. Pass – Does nothing at all; this is meant to be placeholder
2. Continue – Jumps to the top of the closest enclosing loop (to the loop’s
header line)
3. Break – Jumps out of the closest enclosing loop (past the entire loop
statement)
4. Else – In loops, this runs if and only if the loop is exited normally (i.e, without
hitting a break)

Using the PASS, CONTINUE, BREAK and ELSE Keywords


1. If we include the previous statements in our WHILE loop, it will look
something like this:
a. while <test1>:
b. <statement1>
c. if <test2>: break # exits the loop now, skips else
d. if <test3>: continue # go to the top of the loop now, to test1
e. else:
f. <statement2> # run if we didn't hit a "break"

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'

NESTED FOR Loops


1. In Python, you can create NESTED loops.
2. These are simply loops within loops.
3. You can use this to search multiple sets of data in a list.
4. An example of a NESTED FOR loop is seen below:
a. for x in (1, 2, 3):
b. for y in (10, 20, 30):
c. z=x*y
d. print(z)

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.

Return Types for Functions


1. Unlike many other languages, you do not need to explicitly declare a
return type of the function.
2. Python functions can return values of any type via the return keyword.
3. One function can return any number of different types.
4. You make use of the “return” keyword in a function.
5. An example of this is seen below:
a. def function_returns(x):
b. if x > 0:
c. return "Number is Positive"
d. elif x < 0:
e. return "Number is Negative"
f. else:
g. return 0
6. A function that reaches the end of execution without a return statement
will always return None.
7. An example of this is shown below:
a. def function_none():
b. pass
8. A function cannot have an empty body, so if you create a function with
no statements, you can use the Pass statement as a placeholder.
9. In this case, when the function is called, it simply returns None and does
nothing.

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

You might also like