Python pptx12345678
Python pptx12345678
• According to stackoverflow.com's recent survey, Python is in the top three Most used
Programming Language.
Python Features:
• Extensive basic data types are supported e.g., numbers (floating point, complex, and
unlimited-length long integers), strings (both ASCII and Unicode), lists, and dictionaries.
• Python can connect to database systems. It can also read and modify
files.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as
it is written
• Python can be treated in a procedural way, an object-oriented way or a functional
way.
Python Jobs
• Today, Python is very high in demand and all the major companies are looking
for great Python Programmers to develop websites, software components,
and applications or to work with Data Science, AI, and ML technologies.
• Game developer
• Web designer
• Python developer
• Full-stack developer
• Machine learning engineer
• Data scientist
• Data analyst
• Data engineer
• DevOps engineer
• Software engineer
• Many more other roles
It's impossible to list all of the companies using Python, a few big
companies are:
• Google
• Intel
• NASA
• PayPal
• Facebook
• IBM
• Amazon
• Netflix
• Pinterest
• Uber
Python Syntax compared to other programming languages
• Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
• For visual studio code extensions download code runner and python
extensions
• Launch python IDLE
• To check if you have python installed on a Windows PC, search in the start bar
for Python or run the following on the Command Line (cmd.exe):
To check if you have python installed on a Linux or Mac, then on linux open the
command line or on Mac open the Terminal and type:
python --version
Python Interpreter: Shell/REPL
• Python is an interpreter language. It means it executes the code line by line.
Python provides a Python Shell, which is used to execute a single Python
command and display the result.
• It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the
command, evaluates the command, prints the result, and loop it back to
read the command again.
• To run the Python Shell, open the command prompt or power shell on
Windows and terminal window on mac, write python and press enter. A
Python Prompt comprising of three greater-than symbols >>> appears, as
shown below.
Now, you can enter a single statement and get the result. For example, enter a
simple expression like 3 + 2, 3*3, 3/3 press enter and it will display the result
in the next line
Execute Python Script
As you have seen, Python Shell executes a single statement. To execute multiple
statements, create a Python file with extension .py, and write Python scripts
(multiple statements).
For example, enter the following statement in a text editor such as Notepad.
Activity 1
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Python Comments
• Comments can be used to explain Python code.
• Comments start with a #, and Python will render the rest of the line as a
comment
Python comments
• A comment does not have to be text that explains the code, it can also be used
to prevent Python from executing code:
#print("Hello, World!")
print("Cheers, Mate!")
• Comments can be placed at the end of a line, and Python will ignore the rest of
the line:
Example
print("Hello, World!") #This is a comment
Multi Line Comments
• Python does not really have a syntax for multi line comments.
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Multiline comments in python
• You can use a multiline string.
• Since Python will ignore string literals that are not assigned to a variable,
you can add a multiline string (triple quotes) in your code, and place your
comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Multi-Line Statements
• Statements in Python typically end with a new line. Python, however, allows
the use of the line continuation character (\) to denote that the line should
continue. For example −
total ="item_one + \
item_two + \
item_three"
print(total)
Multiple Statements on a Single Line
• The semicolon ( ; ) allows multiple statements on a
single line given that no statement starts a new code
block.
• Variables can store data of different types, and different data types can do
different things.
x = 20
x = 20.5
x = 1j
Creating Variables
• Python has no special command for declaring a variable, a variable is created the moment
you first assign a value to it.
print (counter)
print (miles)
print (name)
Variables
print(x)
Get the Data Type
• You can get the data type of a python variable with the type() function.
x=5
y = "John"
age = 14
Age = "14"
print(type(age))
print(type(Age))
print(type(x))
print(type(y))
Quotations in Python
x = 'boy'
Case-Sensitivity
• Variable names are case-sensitive.
a=4
A = "Bruno"
print(a)
print(A)
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _
)
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Multi Words Variable Names
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John "
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John "
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Assignment of multiple variables
x = y = z = "hello"
print(x)
print(y)
print(z)
The Python print() function
• The Python print() function is often used to output variables.
x = "This is Python Class"
print(x)
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
In the print() function, you cannot combine a string and a number with the +
operator, Python will give you an error
Note the + operator concatenates strings while it also serves as a mathematical addition operator with integers
Python Functions
• Functions provide better modularity for your application and a high degree
of code reusing.
def my_function():
print("Hello I was printed from a function")
my_function()
Application of Python function
def add(a, b): #This function adds two numbers and returns the result
result = a + b
return result
result = add(3, 4) # function call
print("The sum is:", result) # This will print "The sum is: 7 "
""" You can call this function by passing two numbers as arguments, and it will return the sum of those
numbers """
In this example, the add function takes two arguments (3 and 4), adds
them together, and returns the result.
You can call this function with any two numbers, and it will calculate
their sum.
def add(a, b):
result = a + b
return result
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Function placeholder
def myfunction():
pass
• # having an empty function definition like this, would raise an error
without the pass statement
Arguments In a Python function
• Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
def my_function(fname):
print(fname + " are boys") # Arguments
• Meaning that if you enter 2 parameters, you have to call the function with 2
arguments, not more, and not less.
my_function("Christiano", "Ronaldo")
If you try to call the function with 1 or 3 arguments, you will get an error:
my_function("Tony")
Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the
items accordingly:
def my_function(*kids):
print("The youngest child is " + kids[2])
• You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Return Values
• To let a function return a value, use the return statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Global & Local Variables
• Variables that are created outside of a function are known as
global variables.
def myfunc():
print("Python is " + x)
myfunc()
#Create a variable outside of a function, and use it inside the function
def myfunc():
x = "fantastic " #local variable
print("Python is " + x)
def myfunc():
x = "fantastic " #local variable
print("Python is " + x)
myfunc() #function call executes the function
# function ends and next line of code executes from outside the function
print("Python3 is " + x)#if you remove line of code only local var prints to the terminal
The global Keyword
• Normally, when you create a variable inside a function, that variable is local, and can only be used inside
that function.
• To create a global variable inside a function, you can use the global keyword.
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python User Input()
• Python allows for user input this means we are able to ask the user for some
input into our program.
• The following example asks for the username, stores it in a variable called
username and when you enter the username, it gets printed on the screen:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code.
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
• The else keyword catches anything which isn't caught by the preceding
conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Python While Loops
• Python has two primitive loop commands:
• while loops
• for loops
i=1
while i < 6:
print(i)
i += 1
The break Statement
• With the break statement we can stop the loop even if the while condition is
true:
Exit the loop when i is 3: even if i < 6 is true
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
• With the continue statement we can stop the current iteration, and continue
with the next:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
• With the else statement we can run a block of code once when the condition
no longer is true:
Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Python For Loops
• A "for" loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
• This is less like the "for" keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
• With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
• Print each fruit in a fruit list:
for x in "python":
print(x)
The break Statement
• With the break statement we can stop the loop before it has looped through all the
items:
for x in range(6):
print(x)
"Else" in For Loop
• The else keyword in a for loop specifies a block of code to be executed when
the loop is finished:
• Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Break
• Break the loop when x is 3, and see what happens with the
else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Python GUI Programming With Tkinter
• Python has a lot of GUI frameworks, but Tkinter is the only
framework that’s built into the Python standard library.
window = Tk()
When you execute the above code, a new window pops up on your screen. How it
looks depends on your operating system:
Also For Vs Code User Environment
• First of all, import the TKinter module. After importing, setup the application object by
calling the Tk() function. This will create a top-level window (root) having a frame with a
title bar, control box with the minimize and close buttons, and a client area to hold other
widgets
from tkinter import *
window=Tk()
window.geometry('300x500')
mainloop()
• The geometry() method defines the width, height and coordinates of the top left corner
of the frame (all values are in pixels): window.geometry("widthxheight+XPOS+YPOS")
The application object then enters an event listening loop by calling the mainloop()
method. The application is now constantly waiting for any event generated on the
elements in it
wi
ndow.mainloop()
Nothing seems to happen, but notice that no new prompt appears in the shell.
• Widgets are the elements through which users interact with your program.
Each widget in Tkinter is defined by a class. Here are some of the widgets
available:
• The grid geometry manager uses the concepts of rows and columns to
arrange the widgets.
• The following shows a grid that consists of four rows and three columns:
Setting up the grid
• Before positioning widgets on a grid, you’ll need to configure the rows and columns of
the grid.
• Tkinter provides you with two methods for configuring grid rows and columns:
container.columnconfigure(index, weight)
container.rowconfigure(index, weight)
The weight determines how wide the column will occupy, which is relative to other
columns. For example, a column with a weight of 2 will be twice as wide as a column with a
weight of 1.
Positioning a widget on the grid
• To place a widget on the grid, you use the widget’s grid() method:
• The grid() method has the following parameters:
Parameters Meaning
•
• rowsparow The row index where you want to place the widget.n
Set the number of adjacent rows that the widget can span.
• column The column index where you want to place the widget.
• columnspan Set the number of adjacent columns that the widget can
span.
• sticky If the cell is large than the widget, the sticky option
specifies which side the widget should stick to and how to
distribute any extra space within the cell that is not taken
up by the widget at its original size.
• padx Add external padding above and below the widget.
• pady Add external padding to the left and right of the widget.
• ipadx Add internal padding inside the widget from the left and
right sides.
• ipady Add internal padding inside the widget from the top and
bottom sides.
Sticky
• By default, when a cell is larger than the widget it contains, the grid geometry
manager places the widget at the center of the cell horizontally and vertically.
• To change this default behavior, you can use the sticky option. The sticky option
specifies which edge of the cell the widget should stick to.
Padding
• To add paddings between cells of a grid, you use the padx and pady options.
The padx and pady are external paddings:
# root window
root = tk.Tk()
root.geometry("240x100")
root.title('Login')
root.resizable(0, 0)
# configure the grid
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=3)
# username
username_label = ttk.Label(root, text="Username:")
username_label.grid(column=0, row=0, sticky=tk.W, padx=5, pady=5)
username_entry = ttk.Entry(root)
username_entry.grid(column=1, row=0, sticky=tk.E, padx=5, pady=5)
# password
password_label = ttk.Label(root, text="Password:")
password_label.grid(column=0, row=1, sticky=tk.W, padx=5, pady=5)
# login button
login_button = ttk.Button(root, text="Login")
login_button.grid(column=1, row=2, sticky=tk.E, padx=5, pady=5)
root.mainloop()
Project (Due Next week)
• # root window
• root = tk.Tk()
• root.geometry("400x250")
• root.title('Calculator')
• root.resizable(0,0)
cal_entry = ttk.Entry(root)
cal_entry.grid(
column=0, row=0, sticky=tk.NSEW, columnspan= 4, padx=10,
pady=5, ipady=10
)
• #first column
• btn7_button = ttk.Button(root, text="7")
• btn7_button.grid(column=0, row=1, sticky=tk.W, padx=10, pady=5, ipadx=5,
ipady=5)
• root.mainloop()
Import 2
root= Tk()
root.title("simple calculator")
def button_click(number):
• button_4.grid(row=2 , column =0 )
• button_5.grid(row=2 , column =1 )
• button_6.grid(row=2 , column = 2)
• button_7.grid(row=1 , column =0 )
• button_8.grid(row=1 , column =1 )
• button_9.grid(row=1 , column =2 )
• button_add.grid(row=5, column =0 )
• button_equal.grid(row=5, column =1,columnspan=2 )
• button_clear.grid(row=4, column =1, columnspan=2 )
Tkinter command binding
To make the application more interactive, the widgets need to respond to the
events such as:
• Mouse clicks
• Key presses
• This requires assigning a call back function to a specific event. When the
event occurs, the call back will be invoked automatically to handle the event.
• In Tkinter, some widgets allow you to associate a call back function with an
event using the command binding.
• To use the command binding, you follow these steps:
def button_clicked():
print('Button clicked')
After that, you can associate the function with the command option of a button
widget:
ttk.Button(root, text='Click Me',command=button_clicked)
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
def button_clicked():
print('Button clicked')
root.mainloop()
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry("200x200")
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
def button_clicked():
print("this text was printed as a command binding example")
• A lambda function can take any number of arguments, but can only have one
expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
x = lambda a : a + 10
x = lambda a, b : a * b
print(x(5, 6))
Summarize argument a, b, and c and return the
result:
b, c : a + b + c
ambda a,
print(x(5, 6, 2))
Why Use Lambda Functions?
• Say you have a function definition that takes one argument, and that
argument will be multiplied with an unknown number:
• Tkinter button command arguments
• If you want to pass arguments to a callback function, you can use a
lambda expression.
• def my_callback(num):
• print("function my_callback was called with ", num)
• caller(5, my_callback)
• caller(10, my_callback)
• # run...
• function my_callback was called with 5
• function my_callback was called with 10
import tkinter as tk
def on_button_press(number):
print(f"Button {number} pressed!")
root = tk.Tk()
root.mainloop()
To Press into an Entry widget
• import tkinter as tk
• def on_button_press(number):
• entry_var.set(f"Button {number} pressed!")
• root = tk.Tk()
• root.mainloop()
• import tkinter as tk
• def on_button_press(number):
• current_text = entry_var.get()
• entry_var.set(f"{current_text} Button {number}")
• root = tk.Tk()
• root.mainloop()
• The following program illustrates how to pass an argument to the callback function
associated with the button command:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
def select(option):
print(option)
root.mainloop()
Python Data Types
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
• int
• float
• Complex
• Variables of numeric types are created when you assign a value to them:
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
int
• Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
• Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
• Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex Numbers
• Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
• You can convert from one type to another with the int(), float(), and complex() methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(a))
print(type(b))
print(type(c))
• The min() and max() functions can be used to find the lowest or highest
value in an iterable:
print(x)
print(y)
Pow() function
• The pow(x, y) function returns the value of x to the power of y (xy).
x = pow(4, 3)
print(x)
Random Number
• Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make
random numbers:
• Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
The Math Module
• Python has also a built-in module called math, which extends the list of
mathematical functions.
• When you have imported the math module, you can start using methods and
constants of the module.
•:
The math.sqrt() method for example,
returns the square root of a number
import math
x = math.sqrt(64)
print(x)
• The math.ceil() method rounds a number upwards to its nearest integer, and
the math.floor() method rounds a number downwards to its nearest integer,
and returns the result:
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
Python Casting
• int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (provided the string represents a whole
number)
• float() - constructs a float number from an integer literal, a float literal or a string
literal (provided the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals
Casting int float and string data type into integers
x = int(1)
y = int(2.8)
z = int("3")
print(x) #will be 1
print(y) #will be 2
print(z) #will be 3
• Floats:
Strings:
• Strings
• Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:
Multiline Strings
• You can assign a multiline string to a variable by using three quotes:
a = "Python!"
print(a[1])
Looping Through a String
• Since strings are arrays, we can loop through the
characters in a string, with a for loop.
for x in"Python":
print(x)
String Length
• To get the length of a string, use the len()
function.
a = "Hello, Python!"
print(len(a))
Check String
• Specify the start index and the end index, separated by a colon, to return a
part of the string.
• Get the characters from position 2 to position 5 (not included):
b = "Hello World!"
print(b[2:5])
Slice From the Start
• By leaving out the start index, the range will start at the first
character:
b = "Hello, World!"
print(b[:5])
Slice To the End
• By leaving out the end index, the range will go to the end:
• Get the characters from position 2, and all the way to the
end:
b = "Hello, World!"
print(b[2:])
Python - Modify Strings
• Python has a set of built-in methods that you can use on strings.
Upper Case
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case
a = "Hello, World!"
print(a.lower())
Remove Whitespace
• Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
The strip() method removes any whitespace from the beginning or the end:
a = "Hello, World!"
print(a.replace("H", "J"))
Split String
• The split() method returns a list where the text between the specified
separator becomes the list items.
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello,World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
age = 40
txt = "My name is Jon, and I am {}"
print(txt.format(age))
• The format() method takes unlimited number of arguments, and
places them into their respective placeholders:
quantity = 3
item_tag_no = 567
price = 49.95
quantity = 2
itemno = 567
price = 6000
myorder = "I want to pay {2} Naira for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Escape Characters In Python Programming
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
• Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different qualities
and usage.
• List items are indexed, the first item has index [0], the second item has index
[1] etc.
-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
• You can specify a range of indexes by specifying where to start and where to
end the range.
• When specifying a range, the return value will be a new list with the
specified items
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Change List Item Value
• To change the value of a specific item, refer to the index number:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Change range of values the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Insert Items
• To insert a new list item, without replacing any of the existing values, we can
use the insert() method.
Remove "banana":
Sort Descending
To sort descending, use the keyword argument reverse = True:
thislist = ["orange", " 3 " ,"mango", "kiwi", "pineapple", "banana ", " 1 "]
thislist.sort(reverse = True)
print(thislist)
Sort the list numerically:
• But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
x=list(thistuple)
x.sort()
thistuple= tuple(x)
print(thistuple)
Exercise
•
x=list(thistuple)
x.sort(reverse=True)
thistuple= tuple(x)
print(thistuple)