0% found this document useful (0 votes)
57 views

Python pptx12345678

Python is a high-level, interpreted programming language that can be used for a wide variety of tasks. It supports object-oriented, imperative, and functional programming styles. Key features of Python include being cross-platform, having a simple syntax, and supporting automatic memory management. Popular uses of Python include web development, data analysis, and scientific computing.

Uploaded by

Akinsiku Naomi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Python pptx12345678

Python is a high-level, interpreted programming language that can be used for a wide variety of tasks. It supports object-oriented, imperative, and functional programming styles. Key features of Python include being cross-platform, having a simple syntax, and supporting automatic memory management. Popular uses of Python include web development, data analysis, and scientific computing.

Uploaded by

Akinsiku Naomi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

Introduction

What is Python Programming?


Python Programming
• Python is a high-level, cross-platform, and open-sourced programming.

• Guido Van Rossum conceived Python in the late 1980s.

• He named this language after a popular comedy show called


'Monty Python's Flying Circus’
(and not after Python-the snake, as popularly believed).

• In the last few years, its popularity has increased immensely.

• According to stackoverflow.com's recent survey, Python is in the top three Most used
Programming Language.
Python Features:

• Python is an interpreter-based language, which allows the execution of one instruction at a


time.

• 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.

• Variables can be strongly typed as well as dynamic typed.

• Supports object-oriented programming concepts such as class, inheritance, objects, module,


namespace etc.

• Cleaner exception handling support.

• Supports automatic memory management.


What can Python do?
• Python can be used on a server to create web applications.

• Python can be used alongside software to create workflows.

• Python can connect to database systems. It can also read and modify
files.

• Python can be used to handle big data and perform complex


mathematics.

• Python can be used for rapid prototyping, or for production-ready


software development.
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc)

• Python has a simple syntax similar to the English language.

• 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.

• Today a Python Programmer with 3-5 years of experience is asking


for around $150,000 annual package depending on location and
company
Careers with Python

• 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.

• Python uses new lines to complete a command, as opposed to other


programming languages which often use semicolons or parentheses.

• Python relies on indentation, using whitespace, to define scope; such as the


scope of loops, functions and classes. Other programming languages often use
curly-brackets for this purpose.
• You can download python for free from https://www.python.org/

• For visual studio code extensions download code runner and python
extensions
• Launch python IDLE

• Install Anaconda for jupyter notebook


Installation

• Many PCs and Macs will have python already installed.

• 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):

C:\Users\Your Name>python --version

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.

print ("This is Python Script.")

Save it as myPythonScript.py, navigate the command prompt to the folder where


you have saved this file and execute the python myPythonScript.py command, as
shown below. It will display the result.
Python Syntax
First Program

• Python is an interpreted programming language, this means that as a


developer you write Python (.py) files in a text editor and then put those
files into the python interpreter to be executed.

Activity 1

Step 1 : print("Hello World!")


Step 2: Save
Step 3: Run
Python Indentation
• Indentation refers to the spaces at the beginning of a code line.

• Where in other programming languages the indentation in code is for


readability only, the indentation in Python is used indicate a block of code.

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 can be used to make the code more readable.

• Comments can be used to prevent execution when testing code.

• Python has commenting capability for the purpose of in-code documentation.

• 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.

• To add a multiline comment you could insert a # for each line:

#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.

import sys; x ='food'; sys.stdout.write(x + '\n')


Python Data Types
• In programming, data type is an important concept.

• Variables can store data of different types, and different data types can do
different things.

• Python has the following major data types :

• Text Type: string


• Numeric Types: int, float, complex
• Boolean Type: bool
• Binary Types: bytes, bytearray, memoryview

• None Type: NoneType

• Sequence Types: list, tuple, range

• Mapping Type: dict

• Set Types: set, frozenset


x = "Hello World"

x = 20

x = 20.5

x = 1j

x = ["apple", "banana", "cherry"]

x = ("apple", "banana", "cherry")


Python Variables

• Variables are containers for storing data values.

Creating Variables
• Python has no special command for declaring a variable, a variable is created the moment
you first assign a value to it.

counter = 100 # An integer assignment


miles = 1000.3 # A floating point
name = "John" # A string

print (counter)
print (miles)
print (name)
Variables

• Variables do not need to be declared with any particular


type, and can even change type after they have been set, for
instance

x=4 # x is of type int

x = "Simpson " # x is now of type str

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

• String variables can be declared either by using


single or double quotes:

x = "boy" # is the same as

x = 'boy'
Case-Sensitivity
• Variable names are case-sensitive.

a=4
A = "Bruno"

print(a)
print(A)

#A will not overwrite a


Variable Names (Identifiers)

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).

Rules for Python variables:

• A variable name must start with a letter or the underscore character

• A variable name cannot start with a number

• 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 = "john", "Jane", "Barry"


print(x)
print(y)
print(z)

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)

• In the print() function, you can output multiple variables, separated by a


comma:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Output Variables
• You can also use the " +" operator to output multiple variables

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

• Use comma instead

Note the + operator concatenates strings while it also serves as a mathematical addition operator with integers
Python Functions

• A function is a block of organized, reusable code that is used to perform a


single, related action.

• Functions provide better modularity for your application and a high degree
of code reusing.

• A function only runs when it is called.

• You can pass data, known as parameters, into a function.

• A function can return data as a result.


Syntax of a Python Function
• In Python a function is defined using the def keyword, followed by the
function name, parenthesis () and colon :

• This first line in the declaration is called the function header

def my_function(): # function header

print("I was printed from a function") #action


Calling a Function

• To call a function, use the function name followed by parenthesis:

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

result = add(3, 4) # function call


print("The sum is:", result)
Parameters Vs Arguments In a Function
• The terms Parameter and Argument can be used
interchangeably, they’re both information that are passed
into a function.

However from a function's perspective:

• A parameter is the variable listed inside the parentheses in


the function definition (header)

• An argument is the value that is sent to the function when it


is called. (function call)
Default Parameter Value

• If we call the function without argument, it uses the default value:

def my_function(country = "Nigeria"):


print("I am from " + country)

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

• Information can be passed into functions as arguments.

• 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

my_function("John, James & Jake")


Number of Arguments in a Function

• By default, a function must be called with the correct number of arguments as


parameters.

• Meaning that if you enter 2 parameters, you have to call the function with 2
arguments, not more, and not less.

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Christiano", "Ronaldo")
If you try to call the function with 1 or 3 arguments, you will get an error:

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

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

my_function("Tolu", "Tola", "Bayo")


Passing a List as an Argument

• 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)

fruits = ["apple", "mango", "cherry"]

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.

• Global variables can be used, both inside of functions and


outside.

• Local variables are created inside a function & can only be


used inside the function
x = "awesome"

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)

myfunc() #function call executes the function


If you create a variable inside a function, this variable will be local, and can only
be used inside the function.

x = "awesome " #global variable

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.

• Python 3.6 uses the input() method.

• Python 2.7 uses the raw_input() method.

• 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:

username = input("Enter username:")


print("Welcome: " + username)
Python Conditions and If statements
• Python supports the usual logical conditions from mathematics:

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.

An "if statement" is written by using the if keyword.


a = 33
b = 200
if b > a:
print("b is greater than a")

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code.

Other programming languages often use curly-brackets for this purpose.


Elif
• The elif keyword is Python's way of saying "if the previous conditions were
not true, then try this condition“

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

The while Loop


• With the while loop we can execute a set of statements as long as a condition is true.

Print i as long as i is less than 6:

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:

Continue to the next iteration if i is 3:

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:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
Looping Through a String
• Even strings are iterable objects, they contain a sequence of characters:

• Loop through the letters in the word "python":

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:

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break
• Exit the loop when x is "banana", but this time the break comes before the
print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)
The continue Statement
• With the continue statement we can stop the current iteration of the loop, and
continue with the next:

• Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)
The range() Function
• To loop through a set of code a specified number of times, we can use the
range() function,
• The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and ends at a specified number.

Using the range() function:

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.

• Tkinter has several strengths. It’s cross-platform, so the same code


works on Windows, macOS, and Linux.

• Visual elements are rendered using native operating system


elements, so applications built with Tkinter look like they belong on
the platform where they’re run.
• The foundational element of a Tkinter GUI is the window.
Windows are the containers in which all other GUI elements
live.

• These other GUI elements, such as text boxes, labels, and


buttons, are known as widgets. Widgets are contained inside of
windows.

• First, create a window that contains a single widget. Start up a


new Python session and follow along!
VS Code Users

• #Open your console and type 'pip install tk'


to instal tkinter library
With your Python shell open, the first thing you need to do is import the Python GUI
Tkinter module:

from tkinter import *

A window is an instance of Tkinter’s Tk class. Go ahead and create a new window


and assign it to the variable window:

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.

window.mainloop() tells Python to run the Tkinter event loop.


This method listens for events, such as button clicks or keypresses,
and blocks any code that comes after it from running until you close
the window where you called the method.
Go ahead and close the window you’ve created, and you’ll see a new
prompt displayed in the shell.
Working With Widgets

• 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:

Widget Class Description


• Label A widget used to display text on the screen
• Button A button that can contain text and can perform an action
when clicked
• Entry A text entry widget that allows only a single line of text
• Text A text entry widget that allows multiline text entry
• Frame A rectangular region used to group related widgets or
provide padding between widgets
Introduction to the Tkinter grid geometry manager

• 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 columnconfigure() method configures the column index of a grid.

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:

grid(column, row, sticky, padx, pady)


• To add paddings within a widget itself, you use ipadx and ipady options. The
ipadx and ipady are internal paddings:

grid(column, row, sticky, padx, pady, ipadx, ipady)

• The internal and external paddings default to zero.


Tkinter grid user Interface exercise
• In this example, we’ll use the grid geometry manager to design a login
screen as follows:
The login screen uses a grid that has two columns and three rows. Also, the second column is
three times as wide as the first column
import tkinter as tk
from tkinter import ttk

# 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)

password_entry = ttk.Entry(root, show="*")


password_entry.grid(column=1, row=1, sticky=tk.E, 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)

• Design a simple calculator Graphical User Interface


with Python tkinter
• import tkinter as tk
• from tkinter import ttk

• # root window
• root = tk.Tk()
• root.geometry("400x250")
• root.title('Calculator')
• root.resizable(0,0)

• # configure the grid


• root.columnconfigure(0, weight=1)
• root.columnconfigure(1, weight=1)
• root.columnconfigure(2, weight=1)
• root.columnconfigure(3, weight=1)
#Entry widget for calculator

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)

• btn4_button = ttk.Button(root, text="4")


• btn4_button.grid(column=0, row=2, sticky=tk.W, padx=10, pady=5, ipadx=5,
ipady=5)

• btn1_button = ttk.Button(root, text="1")


• btn1_button.grid(column=0, row=3, sticky=tk.W, padx=10, pady=5,ipadx=5,
ipady=5)

• btndot_button = ttk.Button(root, text=".")


• btndot_button.grid(column=0, row=4, sticky=tk.W, padx=10, pady=5,ipadx=5,
ipady=5)
• #second column
• btn8_button = ttk.Button(root, text="8")
• btn8_button.grid(column=1, row=1, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady
=5)

• btn5_button = ttk.Button(root, text="5")


• btn5_button.grid(column=1, row=2, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady
=5)

• btn2_button = ttk.Button(root, text="2")


• btn2_button.grid(column=1, row=3, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady
=5)

• btnz_button = ttk.Button(root, text="0")


• btnz_button.grid(column=1, row=4, sticky=tk.W, padx=5, pady=5,ipadx=5, ipady=5)
• #Third column

• btn9_button = ttk.Button(root, text="9")


• btn9_button.grid(column=2, row=1, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady =5)

• btn6_button = ttk.Button(root, text="6")


• btn6_button.grid(column=2, row=2, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady =5)

• btn3_button = ttk.Button(root, text="3")


• btn3_button.grid(column=2, row=3, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady =5)

• btneq_button = ttk.Button(root, text="=")


• btneq_button.grid(column=2, row=4, sticky=tk.W, padx=5, pady=5,ipadx=5, ipady=5)
• #4th column

• btnce_button = ttk.Button(root, text="CE")


• btnce_button.grid(column=3, row=1, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady =5)

• btndiv_button = ttk.Button(root, text="÷")


• btndiv_button.grid(column=3, row=2, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady =5)

• btnadd_button = ttk.Button(root, text="+")


• btnadd_button.grid(column=3, row=3, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady =5)

• btnsub_button = ttk.Button(root, text="−")


• btnsub_button.grid(column=3, row=4, sticky=tk.W, padx=5, pady=5, ipadx =5, ipady =5)

• root.mainloop()
Import 2

from tkinter import *

root= Tk()
root.title("simple calculator")

def button_click(number):

e = Entry(root, width =35, borderwidth =5)


e.grid(row=0, column =0, columnspan = 4)
button_1 = Button(root, text="1", padx=40, pady = 20, command= lambda: button_click(1))
button_2 = Button(root, text="2", padx=40, pady = 20, command= lambda: button_click(2))
button_3 = Button(root, text="3", padx=40, pady = 20, command= lambda: button_click(3))

button_4 = Button(root, text="4", padx=40, pady = 20, command= lambda: button_click(4))


button_5 = Button(root, text="5", padx=40, pady = 20, command= lambda: button_click(5))
button_6 = Button(root, text="6", padx=40, pady = 20, command= lambda: button_click(6))

button_7 = Button(root, text="7", padx=40, pady = 20, command= lambda: button_click(7))


button_8 = Button(root, text="8", padx=40, pady = 20, command= lambda: button_click(8))
button_9 = Button(root, text="9", padx=40, pady = 20, command= lambda: button_click(9))

button_0 = Button(root, text="0", padx=40, pady = 20, command= lambda: button_click(0))

button_add = Button(root, text="+", padx=39, pady = 20, command= lambda: button_click())


button_equal = Button(root, text="=", padx=88, pady = 20, command= lambda: button_click())
button_clear = Button(root, text="CE", padx=85, pady = 20, command= lambda: button_click())
• button_1.grid(row=3, column =0 )
• button_2.grid(row=3, column =1 )
• button_3.grid(row=3, column = 2)

• 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_0.grid(row=4 , column =0)

• 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:

• First, define a function as a call back.


• Then, assign the name of the function to the command option of the widget.
• For example, the following defines a function called button_clicked():

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

button = ttk.Button(root, text='Click Me', command=button_clicked)


button.pack()

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")

button = ttk.Button(root, text ='ok', command = button_clicked)


button.grid(column =1, row = 1)
root.mainloop()
Python Lambda
• A lambda function is a small anonymous function. (i.e., defined without a
name) that can take any number of arguments but, unlike normal functions,
evaluates and returns only one expression.

• 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

#Add 10 to argument a, and return the result:

# x=lambda a is the argument, while a + 10 is the


expression

print(x(5)) #value of argument was supplied in the print


statement
Multiply argument a with argument b and return the
result:

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?

• The power of lambda is better shown when you use them as an


anonymous function inside another function.

• 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.

• First, define a function that accepts arguments:


def callback_function(args):
# do something
• Then, define a lambda expression and assign it to the command
option. Inside the lambda expression, invoke the callback function:

ttk.Button( root,text='Button', command=lambda: callback(args))


Callback functions

• def my_callback(num):
• print("function my_callback was called with ", num)

• def caller(val, cb):


• cb(val)

• 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()

# Create buttons with lambda functions and use grid method


button1 = tk.Button(root, text="Button 1", command=lambda: on_button_press(1))
button2 = tk.Button(root, text="Button 2", command=lambda: on_button_press(2))
button3 = tk.Button(root, text="Button 3", command=lambda: on_button_press(3))

# Use grid method to organize buttons in a grid layout


button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
button3.grid(row=1, column=0, columnspan=2) # columnspan is used to make this button span 2 columns

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()

• # Entry widget to display the result


• entry_var = tk.StringVar()
• entry = tk.Entry(root, textvariable=entry_var, state="readonly")
• entry.grid(row=0, column=0, columnspan=2)
• # Create buttons with lambda functions and use grid method
• button1 = tk.Button(root, text="Button 1", command=lambda:
on_button_press(1))
• button2 = tk.Button(root, text="Button 2", command=lambda:
on_button_press(2))
• button3 = tk.Button(root, text="Button 3", command=lambda:
on_button_press(3))

• # Use grid method to organize buttons in a grid layout


• button1.grid(row=1, column=0)
• button2.grid(row=1, column=1)
• button3.grid(row=2, column=0, columnspan=2) # columnspan is used to make this
button span 2 columns

• 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()

• # Entry widget to display the result


• entry_var = tk.StringVar()
• entry = tk.Entry(root, textvariable=entry_var, state="readonly")
• entry.grid(row=0, column=0, columnspan=2)
• # Create buttons with lambda functions and use grid method
• button1 = tk.Button(root, text="Button 1", command=lambda:
on_button_press(1))
• button2 = tk.Button(root, text="Button 2", command=lambda:
on_button_press(2))
• button3 = tk.Button(root, text="Button 3", command=lambda:
on_button_press(3))

• # Use grid method to organize buttons in a grid layout


• button1.grid(row=1, column=0)
• button2.grid(row=1, column=1)
• button3.grid(row=2, column=0, columnspan=2) # columnspan is used to make
this button span 2 columns

• 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)

ttk.Button(root, text='Rock', command=lambda: select('Rock')).pack()


ttk.Button(root, text='Paper',command=lambda: select('Paper')).pack()
ttk.Button(root, text='Scissors', command=lambda: select('Scissors')).pack()

root.mainloop()
Python Data Types

• Built-in Data Types


In programming, data type is an important concept.

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:

• Text Type: str


• Numeric Types:int, float, complex
• Sequence Types:list, tuple, range
• Mapping Type: dict
• Set Types:set, frozenset
• Boolean Type: bool
• Binary Types:bytes, bytearray, memoryview
• None Type: NoneType
Python Numbers

• There are three numeric types in Python:

• 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

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)
print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

You cannot convert complex numbers into another number type.


Python Math

• Python has a set of built-in math functions, including an extensive math


module, that allows you to perform mathematical tasks on numbers.

• The min() and max() functions can be used to find the lowest or highest
value in an iterable:

x = min(5, 10, 25)


y = max(5, 10, 25)

print(x)
print(y)
Pow() function
• The pow(x, y) function returns the value of x to the power of y (xy).

• Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

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.

• To use it, you must import the math module:

• 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

• Specify a Variable Type


There may be times when you want to specify a type on to a variable. This can be
done with 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:

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Strings:

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Python Strings & String Methods

• Strings

• Strings in python are surrounded by either single quotation


marks, or double quotation marks.

• 'hello' is the same as "hello".

• You can display a string literal with the print() function:


Assign String to a Variable

• 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:

You can use three double quotes or three single quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Strings are Arrays
• Like many other popular programming languages, strings in
Python are arrays of bytes representing unicode
characters.

• Square brackets can be used to access elements of the


string.

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.

Loop through the letters in the word "Python":

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

• To check if a certain phrase or character is present in a string, we


can use the keyword in
Check if "free" is present in the following
text:

txt = "The best things in life are free!"


print("free" in txt)
Use it in an if statement:

Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT
• To check if a certain phrase or character is NOT present in
a string, we can use the keyword not in.

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)
• Use it in an if statement:

print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
String Slicing

• You can return a range of characters by using the slice syntax.

• 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:

Get the characters from the start to position 5:

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

• The lower() method returns the string in 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.strip()) # returns "Hello, World!"
Replace String

• The replace() method replaces a string with another


string:

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

• To concatenate, or combine, two strings you can use the +


operator.

• To add a space between them, add a ""


String Format
we cannot combine strings and numbers like this:
age = 40
txt = "My name is Jon Snow, I am " + age
print(txt)

#however we may insert str before the int


(casting)
• The format() method takes the passed arguments,
formats them, and places them in the string where
the placeholders {} are:
Use the format() method to insert numbers into
strings:

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

myorder = "I want {} pieces of item {} for {} dollars. "


print(myorder.format(quantity, item_tag_no, price))
• You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:

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

• To insert characters that are illegal in a string, use an escape character.

• An escape character is a backslash \ followed by the character you want to


insert.
• An example of an illegal character is a double quote inside a string that is
surrounded by double quotes:
• You will get an error if you use double quotes inside a string that is
surrounded by double quotes:

txt = "He is the king of kings, "Acknowledge Him." "


txt ="He is the king of kings, \"Acknowledge Him.\" "
Other Escape Characters in Python
Code Result
\’ Single Quote
\\ Backslash #one backslash to escape the backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
Python String Methods
• Assignment
• List 10 Python String Methods and use them in 10 different
implementations
Python Operators
• Operators are used to perform operations on variables and values, for instance
print(20 + 10) # The + operator adds the two values

Python operators are grouped as follows :

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators

• Arithmetic operators are used with numeric values to perform common


mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x % y #remainder in divisions
** Exponentiation x ** y
// Floor division x // y #whole number in divisions
Python Comparison Operators

• Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Collections (Arrays)
There are four collection data types in the Python programming language:

• List is a collection which is ordered and changeable. Allows duplicate


members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No
duplicate members.
• Dictionary is a collection which is ordered** and changeable. No duplicate
members.
• When choosing a collection type, it is useful to understand the properties of
that type. Choosing the right type for a particular data set could mean
retention of meaning, and, it could mean an increase in efficiency or security.
Python Lists
• Lists are used to store multiple items in a single variable.

• 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.

• Lists are created using square brackets:


mylist = ["apple", "banana", "cherry"]
print (mylist)
List Items
• List items are ordered, changeable, and allow duplicate values.

• List items are indexed, the first item has index [0], the second item has index
[1] etc.

• A list can contain several data types, and allows duplication

list1 = ["abc", 34, True, 40, "male"]


Accessing List Items
• List items are indexed and you can access them by referring to the index
number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative indexing means start from the end

-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.

• The insert() method inserts an item at the specified index:


Insert "watermelon" as the third item:

thislist = ["apple", "banana", "cherry"]


thislist.insert(2, "watermelon")
print(thislist)
Remove Specified Item
• The remove() method removes the specified item.

Remove "banana":

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)
Clear the List
• The clear() method empties the list.

• The list still remains, but it has no content.


thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Sort List Alphanumerically
• List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:
thislist = ["orange", " 3 " ,"mango", "kiwi", "pineapple", "banana ", " 1 "]
thislist.sort()
print(thislist)

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:

thislist = [100, 50, 65, 82, 23]


thislist.sort()
print(thislist)

• Sort the list descending:

thislist = [100, 50, 65, 82, 23]


thislist.sort(reverse = True)
print(thislist)
Join Two Lists

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)
Tuple

• Tuples are used to store multiple items in a single variable.


• Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities and
usage.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)
Python - Access Tuple Items
• Access Tuple Items
• You can access tuple items by referring to the index number, inside square
brackets:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])
Change Tuple Values (Replace)
• Once a tuple is created, you cannot change its values. Tuples are unchangeable, or
immutable as it also is called.

• 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 = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Add Items to a tuple
Convert into a list: Just like the workaround for changing a tuple, you can
convert it into a list, add your item(s), and convert it back into a tuple.

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)
Remove Items
• Tuples are unchangeable, so you cannot remove items from it, but you can use
the same workaround as we used for changing and adding tuple items:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)
How to sort Tuples

thistuple = ("apple", "banana", "cherry", "apple", "cherry")

x=list(thistuple)
x.sort()
thistuple= tuple(x)
print(thistuple)
Exercise

• Reverse Sort the tuple

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


Reverse Sorting Tuples
• thistuple = ("apple", "banana", "cherry", "apple", "cherry")

x=list(thistuple)
x.sort(reverse=True)
thistuple= tuple(x)
print(thistuple)

You might also like