Programming With Python
Programming With Python
Programming With Python
Python
Presidential Initiative for
Artificial Intelligence & Computing
Introduction
Software
● A software is a program or set of programs written
using programming languages.
● Software is responsible for running hardware.
● All operating systems are also softwares.
● Operating system controls and runs all hardware.
Difference between Hardware and
Software
All the tangible All the intangible
components of a computer components of a computer
system are Hardware system are Software
● Python Version 2
● Python Version 3
Why Python?
● Python works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to English.
● Python has syntax that allows developers to write
programs with fewer lines than some other
programming languages.
● Python can be treated in a procedural way, an object-
oriented way, or a functional way.
Data Sciences and Artificial Intelligence
● Python is the fastest adoptable language in data
science and artificial intelligence.
Outputs: 123
print(123 , ‘Hello PIAIC’)
Outputs: 9
num_1 = 56.98
print(num_1)
Outputs: 56.98
Math Operations
Outputs: 0
power = 2 ** 3
print(power)
Outputs: 8
var1 = 4
var1 += 2
print(var1)
Outputs: 6
Math Expressions:
Eliminating
Ambiguity
BODMAS
Brackets
Order of Powers
Division
Multiplication
Addition
Subtraction
Concatenating Text Strings
● Concatenation, in the context of programming, is the
operation of joining two strings together. The
term"concatenation" literally means to merge two
things together.
● Also known as string concatenation.
● For instance, one string would be “hello” and the other
would be “world.” When you use concatenation to
combine them it becomes one string, or “hello world”.
first_string = “Hello”
second_string = “World”
full_word = first_string + “ ” +
second_string
print(full_word)
Outputs: Hello World
If Statements
● An if statement is a programming conditional
statement that, if proved true, performs a function or
displays information.
● If statements are used for decision making. They will
run the body of code only when the IF statement is
true.
● When you want to justify one condition while the other
condition is not true, then you use the "if statement".
num1 = 22
if num1 == 22:
print(“The number is 22”)
== is equal to
!= is not equal to
animal = ‘cat’
if animal == ‘cat’:
print(“This is a cat”)
Outputs:
This is not a comment…
This line also not comment
User Input
● Input from Keyboard
● For this purpose, Python provides the function input().
input has an optional parameter, which is the prompt
string.
input_name = input(“Enter your name: ”)
input_age = input(“Enter your age: ”)
WHEN YOU RUN THIS CODE…….
Enter your name : Muhammad Shahzad Ahsan
Enter your age: 21
Outputs:
Muhammad Shahzad Ahsan
21
List
● A list is a data structure in Python that is a mutable,
or changeable, ordered sequence of elements.
● Each element or value that is inside of a list is called an
item.
● Just as strings are defined as characters between
quotes, lists are defined by having values between
square brackets [ ] and every value is seperated by ,
(comma).
friends = [‘Hamza’ , ‘Fatima’ , ‘Azhar’ , ‘Laiba’ , ‘Ali’ ,
‘Zoya’]
OR
numbers = [1,2,3,4,5,6,7,8,9]
OR
list_float = [ 2.43 , 98.67 , 7.45 , 45.65]
OR
mix = [ ‘Ahsan’ , 2 , 4.56 , 6.87 , True , ‘Maham’ , 56
, False ]
List Operations
Common List Operations
● Access value
● Add new value at the end / tail of list
● Find the index of a value in list
● Slicing the elements from list
● Deleting and removing the elements from List
● Popping elements from the list
Accessing List Elements
List elements are accessed by providing the identifier and index of element
inside square brackets. For example in following snippet arr is an identifier
which points to a list.
print(arr[2])
Please note that to access the position 3 we have provided index 2, because
first element in Python List always starts with 0 (Zero) index.
DEMO
Adding Values in List
Python provides a function append() which adds the value at the end of List.
For example arr points to a list in following snippet
arr.append(321)
Now if we check the elements in list arr we will get the following content
arr.index(1)
This call will give the result 0 even you execute this line many times, the
reason is by default this function starts searching from index 0 and stops
when it finds first occurrence of the desired value.
Searching / Finding a Value in List
● What can we do to search the next element(s)?
● What if the desired value is not present in the List?
DEMO
Slicing the elements from List
Python provides a very handy feature if you want to take a partial piece of List. Note
that slicing operation copies elements from the original List hence this operation
returns a new List which is subset of the original List. Example syntax:
arr = [1, 3, 2, 6, 4]
del arr[2]
Now if we check the contents of List arr we will get the following output
[1, 3, 6, 4]
Deleting and removing the value from List
2) In case if we know the value but we do not know the index of that
value in List, we call remove function over the List identifier and pass
the value to the function. Example
arr = [1, 3, 2, 6, 4]
arr.remove(2)
Now if we check the contents of List arr we will get the following output
[1, 3, 6, 4]
DEMO
Popping Elements from the List
Popping elements works in two ways
Example:
arr = [1, 2, 4, 6, 7]
arr.pop() # will remove the value 7 from the end of List
print(tpl[1]) # outputs 4
print(elem)
The output of this snippet will print each element of the list in new line
DEMO
For Loop break keyword
There are situations where we want to terminate our loop even all the
elements are not yet traversed, e.g when finding a desired value and you found
it in middle of the sequence. In such cases you would want to terminate the
loop. Python provides the break keyword for this scenario.
if elem == 6:
if elem % 2 == 0:
print(elem)
DEMO
Nested For Loop
Nested For Loop
When you have a sequence of sequences and you need to process elements
then we need to place loop inside a loop. Outer loop traverses the main
sequence and inner loop traverses on the inner sequence, which contains the
values
print(elem)
DEMO
Type Casting
Type Casting
As you are now already familiar with input function which is used for data
input. Also you must be familiar till now that input function returns that data
as String type. There are scenarios where you want your users to input the
value as number (int or float type) . Python provides functions to type cast
String types to numbers and numbers to String type.
str_data = “i AM A hUMAN”
Python provides a data structure Dictionary for such cases. Dictionary in simple
words is a data structure which stores the key value pairs, e.g. if you want to
store the information about a student
Please note that keys must be between single or double quotation if they are
string type, every pair is separated from other pairs by a comma, and every pair
of key value is separated by a colon.
Accessing information from Dictionary
student = {‘Name’: ‘Zaid’, ‘Class’: ‘AI’, ‘Program’: ‘PIAIC’,
‘Age’: 42}
print(student[‘Name’])
If you try to access any key which is not present in dictionary will raise an
exception of type KeyError. Also beware of the fact that the Keys are case
sensitive, hence the following statement will throw an exception of type
KeyError
Please note that when keys are of type number they are not required to be
enclosed in single or double quotations.
DEMO
Dictionary adding keys
student = {‘Name’: ‘Zaid’, ‘Class’: ‘AI’, ‘Program’: ‘PIAIC’,
‘Age’: 42}
In the dictionary student we don’t have FatherName key what if now I want
assign a value to this key in dictionary?
student[‘FatherName’] = ‘Bakar’
When we are assigning a value in a key which does not exists, Python creates
the key and assigns the value in the key. If key is already present the value is
overwritten.
DEMO
Dictionary removing items
student = {‘Name’: ‘Zaid’, ‘Class’: ‘AI’, ‘Program’: ‘PIAIC’,
‘Age’: 42}
There are cases when you need to delete a key value pair from dictionary e.g.
del student[‘Program’]
print(student)
DEMO
Dictionary iterating items
Python provides 3 methods over dictionary object to iterate over dictionary
values, keys and key value pair
print(value)
print(key)
Dictionary iterating items Contd.
Python provides 3 methods over dictionary object to iterate over dictionary
values, keys and key value pair
print(key, value)
DEMO
Dictionary; what you can store
Any data structure we have studied so far we can store as value in
dictionary.e.g
students = []
students = []
print(student)
DEMO
Dictionary; that holds a list
employee = {‘Name’: ‘Shams’, ‘ChildrenNames’: [‘Humairah’,
‘Abdul Rahman’]}
print(employee[‘ChildrenNames’][0])
print(employee[‘ChildrenNames’][1])
print(employee[‘Children’][‘Humairah’])
print(employee[‘Children’][‘Abdul Rahman’][‘Age’])
In this snippet we have created a dictionary inside dictionary and child name is
used as keys. In first print statement we can observe that the first pair of
square brackets with employee returns a dictionary to access the elements of
that dictionary we provide another pair with key.
DEMO
Functions
Functions
Functions are a way to achieve the modularity and reusability in code. Before
moving forward we must need to know what are these:
def add():
print(number1 + number2)
Note that every statement which is part of function body is a level indented
more than the definition of function
Functions
In previous slide we have declared a function named add now we can call it as
many times and in any module as we want. To call the function we just need to
write the name of function followed by pair of parentheses, e.g.
add()
DEMO
Functions: Passing information positional
arguments
A generic function does not define any data it processes inside it hard-coded
instead it accepts the data when it is called and processes that data,e.g.
print(number1 + number2)
Now to call the function we need to pass two arguments and they are matched
according to their position in the function call, e.g. here value 3 will be assigned
in number1 while value 5 will be assigned to number2 variable
add(3, 5)
DEMO
Functions: Passing information keyword
arguments
def add(number1, number2):
print(number1 + number2)
There is another way to call same function that we pass the arguments with the
name of variable, this way position does not matter but the value is assigned to
matching name variable in function parameters, e.g.
add(number2 = 5, number1 = 3)
DEMO
Functions: Default value parameters
def add(number1 = 0, number2 = 0):
print(number1 + number2)
There are times when some parameter value are optional but still you need a
default value in case if someone does not provide the value to avoid any non
deterministic behaviors, e.g.
add(number2 = 5)
DEMO
Functions: Mixing positional and keyword
arguments
Be careful mixing positional and keyword arguments. Positional arguments
must come before keyword arguments. Keyword arguments don't have to line
up with parameters, but positional arguments must do.
DEMO
Functions: Dealing with an unknown number of
arguments
In some cases we can not actually guess how many arguments user would
pass when calling function so we need a parameter that can take all values
provided by the user.
Global varaibles are the varaibles defined out side the function and can be
accessed and modified in and outside the function
DEMO
Functions within functions
Right now we have learned how to call function. We can call a function inside
another function providing the required signature of the function.
DEMO
While Loops
We have studied loops in ealrier lectures. There is another type of loops called
‘While Loops’
They work similar to for loops. But differ in the sense that it allows user to
terminate loop by setting flags.
DEMO
Classes
Python is an “object-oriented programming
language.” This means that almost all the code
is implemented using a special construct called
classes.
Programmers use classes to keep related
things together. This is done using the
keyword “class,” which is a grouping of object-
What is a Class?
- A Class is a model
- A class is a template
Class Car():
# body of class Car
What actually class holds??
A class may hold attributes (variables)
Example:
car1 = Car()
car2 = Car()
Demo
A complete example on classes & objects
Demo
Data Files
In all the coding so far in this book, none of the data has been
preserved. We created variables, lists, dictionaries, and class instances
that containedinformation, but as soon as the computer was turned
off, all of it disappeared.
With open(“file_name.txt”,“mode”)
There are three modes:
Read, write, & append
Writing to a text File
With open (“myFile.txt”, “w”) as file:
file.write(“This is my file”)
Note: If file does not exist ,“w” mode will create and
write in it.
Demo
Reading from a text File
With open (“myFile.txt”, “r”) as file:
contents_of_file = file.read()
print(content)
Note: If file does not exist ,“r” mode will throw file not
found error
Demo
Writing a file in append mode
With open (“myFile.txt”, “a”) as file:
You can store functions, classes, and more in a module. Most commonly,
modules are used to store functions.
What's good about modules:
Write a function once, call it from any Python program.
Keep your main programs shorter and simpler to read.
Use code written by other people by importing their modules.
Demo
Exceptions
Exceptions are run time errors.
Year,Event,Winner
1995,Best-Kept Lawn,None
1999,Gobstones,Welch National
import csv
with open("competitions.csv") as f:
contents_of_file = csv.reader(f)
The contents of the CSV file returned by the csv.reader function aren't
useable yet. You have to loop through the data stored in contents_of_f,
with open("competitions.csv") as f:
contents_of_f= csv.reader(f)
potter_competitions = []
potter_competitions += each_line
# Writing to a CSV file
with open("whatever.csv", "w", newline="") as f:
data_handler.writerow(["Year", "Event","Winner"])
data_handler.writerow(["Year", "Event","Winner"])
json.dump(alphabet_letters, f)
Writing Python Dictionary in
JSON File
customer_29876 = {"first name": "David","last name": "Elliott",
json.dump(customer_29876, f)
Reading Data from JsonFile
with open("customer_29876.json") as f:
customer_29876 = json.load(f)
print(customer_29876)
print(customer_29876["last name"])