0.1 - Review On The Python Programming Language

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

Review on the Python

Programming Language
CC3 – Object Oriented Programming
What is Python?
• Python is an interpreted,
object-oriented, high-level
programming language.
• Python’s simple, easy to learn
syntax emphasizes readability
and therefore reduces the cost
of program maintenance.
• Python supports modules and
packages, which encourages
modularity.
Why do people use Python?
• Software quality
• Developer productivity
• Program portability
• Support libraries
• Component integration
Setting Up Python
• There are two main methods to create python applications.
• You can install Python and an IDE on your system of your
choice.
• You can also make use of an online editor to edit and run
Python code.
Setting Up Python
• Setting Up Python Locally
• Head to https://www.python.org/ and head to the “Downloads” tab.
• Download the latest version of Python 3.
• Install Python on to your machine.
• Start up IDLE (the default editor that comes with a Python install) to
start writing Python code.
• You can also make use of an IDE of your choice.
Setting Up Python
• Use an Online Python Editor
• You can make use of online editors to write and run Python code.
• One online editor is https://www.programiz.com/python-
programming/online-compiler/ if you would like to quickly run and
test code.
• You can also make use of Google Collab, which is an online Python
development tool created by Google.
• You can access it here https://colab.research.google.com/?utm_source=scs-index
• You can save code that you create to your personal Google Drive.
Python Variables
• To create a variable in Python, you specify the variable name,
and then assign a value to it:
• <variable name> = <value>
• Python makes use of “=“ to assign values to variables.
• There is no need to declare a variable in advance (or assign a
data type to it).
Python Variables
• Assigning a value to a variable itself declares and initializes the
variable with that value.
• You cannot declare a variable without assigning it an initial
value.
•a = 3
• print(a) # Outputs 3
• Variable assignment works from left to right.
Python Variables
• Python variable names are case sensitive, so a variable named
“greeting” is not the same as a variable named “Greeting”.
• greeting = "Hello World"
• print(Greeting)
• NameError Traceback (most recent call last)
• <ipython-input-22-901c35cfaeff> in <module>()
• 1 greeting = "Hello World"
• ----> 2 print(Greeting)
• NameError: name 'Greeting' is not defined
Valid Variable Names
• Variable names can be as long or as short as you like, but there
are a few rules that you must follow.
• Variable names may contain uppercase and lowercase letters (A – Z, a
– z), digits (0 – 9), and underscores (__).
• Variable names must start with a letter or the underscore character.
• Variable names cannot begin with a digit.
• Variable names are case-sensitive (age, Age, and AGE are three
different variables).
Comments
• The most common way to write a comment is to begin a new
line in your code with the “#” character.
• When you run your code, Python ignores lines starting with
“#”.
• Place a “#” at the end of the line of code, followed by the text in
your comment.
• # This is a block comment
• greeting = "Hello World"
• print(greeting) # This in an inline comment
Python Data Types
• There are five main data types that you can make use of in
Python.
• These are:
• Integer
• Floating Point
• String
• Boolean
• Null
Python Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation
// Floor Division
% Modulo
Python Expressions
• An expression is a combination of values, variables, and
operators.
• A value by itself is considered an expression, and so is a
variable, so the following are all legal expressions (assuming
that the variable “x” has been assigned to a value):
• 15
•x
• x + 15
Python Statements
• A statement is a unit of code that the Python interpreter can
execute.
• They are usually written in a single line.
• Using the “=“ is an example of the assignment statement.
• Using the “print” function is also an example of a statement.
Input
• There are two basic methods in getting user inputs in Python.
• These are raw_input() and input().
• The syntax for these are
• raw_input([prompt])
• and
• input([prompt])
Input
• raw_input will wait for the user to enter text and then return the
result as a string.
• This is available in Python 2
• foo = raw_input("Put a message here that asks the
user for input")
• In the above example foo will store whatever input the user
provides.
Input
• input will wait for the user to enter text and then return the
result as a string.
• This is available in Python 3
• foo = input("Put a message here that asks the user
for input")
• In the above example foo will store whatever input the user
provides.
Input
• Casting – allows you to specify or convert a type of a variable.
• You can enclose the input method in the int() or float() methods
to convert the input into an integer or float, respectively.
• Type casting to integer or float is needed if you would like to
use the input of the user in an arithmetic computation.
Output
• The print() statement allows you to print an output in Python.
• By default, it ends the output by adding a new line.
• You can change this with the end parameter.
• print("Hello, ", end="\n")
• You could pass in other strings in this parameter.
• print("Hello, ", end="")
• print("World!")
• # Hello, World!
Sequence Structure
• Sequence – is the generic term for an ordered set.
• There are several types of sequences in Python, the following three
being the most important.
• Lists – are the most versatile sequence type and can contain any
object.
• Tuples – are like lists, but they are immutable – they can’t be
changed.
• Dictionary – is a collection of key-value pairs.
Lists
• A list functions similarly to an array in other languages.
• In Python, a list is merely an ordered collection of valid Python
values.
• A list can be created by enclosing values, separated by commas,
in square brackets:
• int_list = [1, 2, 3]
• string_list = ['abc', 'defghi']
Lists
• A list can be empty:
• empty_list = []
• The elements of a list are not restricted to a single data type,
which makes sense given that Python is a dynamic language:
• mixed_list = [1, 'abc', True, 2.34, None]
• A list can contain another list as its element:
• nested_list = [['a', 'b', 'c'], [1, 2, 3]]
Tuples
• Tuples are represented with parentheses instead of square
brackets:
• ip_address = ('10.20.30.40', 8080)
• The same indexing rules for lists also apply to tuples.
Tuples
• A tuple with only one member must be defined (note the
comma) this way:
• one_member_tuple = ('Only member',)
• or
• one_member_tuple = 'Only member', # No brackets
• or just using tuple syntax
• one_member_tuple = tuple(['Only member'])
Dictionaries
• A dictionary in Python is a collection of key-value pairs.
• The dictionary is surrounded by curly braces.
• Each pair is separated by a comma and the key and value are
separated by a colon.
Dictionaries
• Here is how you declare a dictionary:
• state_capitals = {
• 'Arkansas': 'Little Rock',
• 'Colorado': 'Denver',
• 'California': 'Sacramento',
• 'Georgia': 'Atlanta'
•}
Dictionaries
• To get a value, refer to it by its key:
• ca_capital = state_capitals['California']

• You can add a new value to a dictionary by using this syntax:


• dictionary_name[key] = value
• state_capitals[‘Hawaii’] = ‘Honolulu’

• You can also delete a value from a dictionary using this syntax:
• del dictionary_name[key]
• del state_capitals['California']
Conditionals
• 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
• False
• You can also negate or reverse the value of a Boolean variable
with not.
• test = True
• print(not test) # Outputs False
A Review of Boolean Values
• “and” operator – a special operator which allow you to judge if
all arguments in a set are True.
• “or” operator – a special operator which allows you to judge if
at least one argument in a set is True.
A Review of Boolean Values
• The and operator is used to check if two variables are true.
• x = True
• y = True
• z = x and y # z = True
• Both values being compared must be True, otherwise, the result
of the and operator will be False.
• x = True
• y = False
• z = x and y # z = False
A Review of Boolean Values
• The and operator can also evaluate numerical and string values,
but it behaves differently in these cases.
• 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).
• Otherwise, it evaluates to the first False argument.
A Review of Boolean Values
• The or operator is used to check if at least one variable in a set is
True.
• x = True
• y = False
• z = x or y # z = True
• At least one of the values being compared must be True,
otherwise, the result of the or operator will be False.
• x = False
• y = False
• z = x or y # z = False
A Review of Boolean Values
• The or operator can also evaluate numerical and string values,
but it behaves differently in these cases.
• 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).
• Otherwise, it evaluates to the second argument.
IF statement
• The IF statement evaluates a Boolean expression and executes
the block of code only when the Boolean expression is True.
• The syntax for the IF statement is shown below:
• if condition:
• body
IF statement
• 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.
• if True:
• print "It is true!"
• >> It is true!

• if False:
• print "This won't get printed.."
ELIF Statement
• The ELIF statement is used to check additional conditions if the
first condition (usually the IF statement) is evaluated as False.
• a = 5
• b = 5
• if b > a:
• print("b is greater than a")
• elif a == b:
• print("a and b are equal")
ELSE Statement
• The ELSE statement is used if none of the previous conditions
are met.
• if condition:
• body
• else:
• body
ELSE Statement
• The ELSE statement will execute its body only if preceding
conditional statements all evaluate to False, otherwise, it will not
be executed.
• if True:
• print "It is true!"
• else:
• print "This won't get printed.."
• # Output: It is true!
Nested IF-ELSE Statements
• 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
• Repetition control structures are also referred to as iterative
structures.
• These are groupings of code which are designed to repeat a set
of related statements.
• This repetition can repeat zero or more times, until some control
value or condition causes the repetition to cease.
Loops
• The most common term to describe repetition control structures
is a loop.
• Loops have two parts:
• Condition – The logic that evaluates a condition.
• Body – This is where the code integral to the loop is located.
WHILE Loops
• 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.
• When the test in the WHILE statement becomes false, control
passes to the statement that follows the WHILE block.
• The effect of this is that the statements in the WHILE block are
executed repeatedly while the test is true.
• If the test is false to begin with, the body never runs.
WHILE Loops
• 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.
• The general format of the WHILE statement is as follows:
• while <test>: # Loop test/condition
• <statements1> # Loop Body
• else: # Optional else
• <statements2> # Runs if didn’t exit loop with break
PASS, CONTINUE, BREAK and ELSE
• Pass
• Does nothing at all; this is meant to be placeholder
• Continue
• Jumps to the top of the closest enclosing loop (to the loop’s header line)
• Break
• Jumps out of the closest enclosing loop (past the entire loop statement)
• Else
• In loops, this runs if and only if the loop is exited normally (i.e, without
hitting a break)
PASS, CONTINUE, BREAK and ELSE
• If we include the previous statements in our WHILE loop, it will
look something like this:
• while <test1>:
• <statement1>
• if <test2>: break # exits the loop now, skips else
• if <test3>: continue # go to the top of the loop now, to test1
• else:
• <statement2> # run if we didn't hit a "break"
FOR Loop
• A FOR loop in Python is used for iterating a sequence (a list, a
tuple, a dictionary, a set, or a string).
• The FOR loop can execute a set of statements, once for each item
in a list, tuple, dictionary, etc.
FOR Loop
• The python FOR loop begins with a header line that specifies an
assignment target, along with the object you want to step
through.
• The header is followed by a block of statements you want to
repeat:
• for <target> in <object>: # Assign object items to target
• <statements> # Repeated loop body: use target
• else:
• <statements> # If we didn't hit a 'break'
FOR Loop
• An example of the FOR loop being used is seen below:
• food = ['eggs', 'rice', 'chicken', 'beef']
• for x in food: # goes through each value in the loop
• print(x, end=' ') # outputs "eggs, rice, chicken, beef"
NESTED FOR Loops
• In Python, you can create NESTED loops.
• These are simply loops within loops.
• You can use this to search multiple sets of data in a list.
• NESTED Loops means that multiple loops are running at the
same time, with the outer loop calling the inner loop every time
it iterates.
Functions
• Functions in Python provide organized, reusable and modular
code to perform a set of specific actions.
• Functions simplify the coding process, prevent redundant logic,
and makes code easier to follow.
• Python has many built-in functions like print(), input(), len(),
etc.
• You can also create your own functions, called user-defined
functions.
User-defined Functions
• These are functions defined by the user to do more specific jobs.
• Using the “def” statement is the most common way to define a
function in Python.
• This type of statement is called a single clause compound
statement with the following syntax:
• def function_name(parameters):
• statement(s)
User-defined Functions
• Here is an example of a user defined function:
• def greeting():
• print("Hello and Good day!")
• As seen in the example, you have a function called greeting().
• When you would like to call the function, you simply type the
function name along with any arguments you have set.
• greeting() # Outputs “Hello and Good day!”
User-defined Functions
• Here is an example of a user defined function with a parameter:
• def greeting_two(name):
• print("Hello " + name + "!")
• As seen in the example, you now have a function with a
parameter.
• When calling this type of function, you must provide
arguments for the parameters for the function to work.
• greeting_two("Ibrahim") # Outputs "Hello Ibrahim!"
User-defined Functions
• You can also set a default value for a function parameter:
• def greeting(name="User"):
• print("Hello " + name + "!")
• As seen in the example, you set a default value when creating
the parameter.
• This will allow you to call that function without giving a value
for the parameter.
• greeting() # Outputs "Hello User!"
Return Type
• Unlike many other languages, you do not need to explicitly
declare a return type of the function.
• Python functions can return values of any type via the return
keyword.
• One function can return any number of different types.
• You make use of the “return” keyword in a function.
Return Type
• An example of this is seen below:
• def function_returns(x):
• if x > 0:
• return "Number is Positive"
• elif x < 0:
• return "Number is Negative"
• else:
• return 0
Return Type
• A function that reaches the end of execution without a return
statement will always return None.
• An example of this is shown below:
• def function_none():
• pass
• If the function above is called, it will simply output None:
• print(function_none()) # Prints "None"
Return Type
• 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.
• In this case, when the function is called, it simply returns None
and does nothing.
Nested functions
• You can place functions inside another function.
• This works similarly to nested lists or IF statements.
• Parameters passed to the outer function are also passed to the
inner function.
• An example of a nested function is shown below:
• def func1(x):
• def func2():
• print("Hello " + x + "!")
• func2()
• func1("Jim") # Outputs "Hello Jim!"

You might also like