0% found this document useful (0 votes)
130 views62 pages

Python Programming Notes

Uploaded by

ark.convey
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
130 views62 pages

Python Programming Notes

Uploaded by

ark.convey
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 62

INTRODUCTION TO AI

(LAB)
Week 1
What is Python?
• Python is a popular programming language.
It was created by Guido van Rossum, and
released in 1991.
• Python general purpose language used for:
• Web development (server-side),
• Software development,
• Mathematics,
• System scripting,
• AI Applications
Some facts about Python
• Python is currently the most widely used multi-purpose,
high-level programming language.
• It is being used by almost all tech-giant companies like –
Google, Amazon, Facebook, Instagram, Dropbox, Uber…
etc.
• The biggest strength of Python is huge collection of
standard library which can be used for the following –
• Machine Learning
• GUI Applications (like Kivy, Tkinter, PyQt etc. )
• Web frameworks like Django (used by YouTube,
Instagram, Dropbox)
• Image processing (like OpenCV, Pillow)
• Web scraping (like Scrapy, BeautifulSoup, Selenium)
• Test frameworks
• Multimedia
• Scientific computing
• Text processing and many more..
What is 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. This
means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-
orientated way or a functional way
Good to know about
Python?
• The most recent major version of Python is Python
3, Python 2 is older one,
• It is possible to write Python in an Integrated
Development Environments, which are particularly
useful when managing larger collections of Python
files.
• Spyder
• IDLE
• Thonny,
• Pycharm,
• Netbeans or
• Eclipse etc.
FIRST PROGRAM
Download and Installation

• Download From: https://www.python.org/downloads/windows/


First Program
•Write following code in your text editor and save with .py
extension

# Simple Program
print("Hello, Python!")r >python helloworld.py
•Save your file. Open your command line, navigate to the
directory where you saved your file, and run::\Users\Your
Name>python helloworld.py
Interactive Python (Command Line)
• To test a short amount of code in python sometimes
it is quickest and easiest not to write the code in a
file. This is made possible because Python can be
run as a command line itself
• Or, if the "python" command did not work, you can
try "py":C:\Users\Your Name
• Whenever you are done in the python command
line, use exit()exit()
Python Indentation
• :\Your
• 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 very
important.
• Python uses indentation to indicate a block of code.
• 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
Execute Python Syntax
•if 5 > 2:
print("Five is greater than two!")
•Python will give you an error if you skip the indentation:
•if 5 > 2:
print("Five is greater than two!")
•The number of spaces is up to you as a programmer, but
it has to be at least one.
•if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
•You have to use the same number of spaces in the same
block of code, otherwise it is an error:
•if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Comments
• Single Line Comments: (# Comment)
• Multiline Comments: (“”” Comment “””)
• Multiline Comments: (“”” Comment “””)
BUILT-IN DATA
TYPES
Built-in Datatypes

Text Sequence Mappin Set Boolean Binary


Numeric
Type Types g Type Types Type Types
Types
list dict set bool
str int bytes
float tuple frozenset bytearray

complex range memoryview


Built-in Datatypes
• str: x = "Hello World"
• int: x = 20
• float: x = 20.5
• complex: x = 1j
• list: x = ["apple", "banana", "cherry"]
• tuple: x = ("apple", "banana", "cherry")
• range: x = range(6)
• dict: x = {"name" : "John", "age" : 36}
• set: x = {"apple", "banana", "cherry"}
• frozenset: x = frozenset({"apple", "banana", "cherry"})
Built-in Datatypes
• Variable Assignment
• age = 45
• salary = 1456.8
• name = "John"
• name= ‘John’
• x=y=y=45
• x, y, z = "Orange", "Banana", "Cherry"
• Variable Value output
• print(age)
• print(“Salary=“, salary)
• print(“Name=“, name)
Built-in Datatypes
• Variable Names
• A variable should descriptive name (age, car, name,
total_volume).
• A variable name must start with a letter or the
underscore character
• A variable name cannot start with a number
• Alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive
• Cannot use Keywords
• Casting a variable in to another
• str(x)
• int(x)
• float(x)
Built-in Datatypes
• Input Variable
• input() function is used for input, it input data in str
format
• name=input(“Enter your name:”)
• age=int(input(“Enter your age:”))
• salary=float(input(“Enter your salary:”))
• age=eval(input(“Enter your age:”))
• x, y, z=eval(input(“Enter three values :”))
• print (type(x))
• Deleting a variable
• x="Waqar Ahmad"
• print(x)
• del x
Example
• a=input("Please Enter First Number:")
• x=int(a)
• y=int(input("Please Enter Second Number:"))
• print("Sum=",x+y)
• print("Product=",x/y)
• print("Exact Division=",x//y)
String Datatype
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
M u h a m m a d A b d u l l a h
-17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

x="Muhammad Abdullah"
Method Output
print("Complete String:", x) Complete String: Muhammad
Abdullah
print("Index String:", x[0]) Index String: M
print("Index String:", x[-5]) Index String: u
print("Slicing String:", x[0:8]) Slicing String: Muhammad
print("Slicing String:", x[-8:-1]) Slicing String: Abdulla
print("Slicing String:", x[:8]) Slicing String: Muhammad
print("Slicing String:", x[9:]) Slicing String: Abdullah
String Datatype
• String Length
a = “ Hello, Python! "
print(len(a))
• String Methods
• print(a.strip()) # Removes beginning and ending spaces
• print(a.lower())
• print(a.upper())
• print(a.replace("H", "J"))
• Check String
in/not in: To check if a certain phrase or character is
present .
print("Python" in a)  True
String Datatype
• Concatenation
a = "Hello"
b = "World"
c=a+""+b
print(c)
• We cannot concatenate number with string use
format for this purpose
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
String Datatype

Escape
Character
s
Dictionaries
• Dictionaries are lists of key-valued pairs.

In:

Out:
Exercise

• Create a string that is 10 characters in length.


• Print the second character to the screen.
• Print the third to last character to the screen.
• Print all characters after the fourth character.
• Print characters 2-8.
Tuples

• Tuples are containers that are immutable; i.e. their


contents cannot be altered once created.

In: Out:

In: Out:
Lists
• Lists are essentially containers
of arbitrary type.
• They are probably the
container that you will use In:
most frequently.
• The elements of a list can be
of different types.
• The difference between Out:
tuples and lists is in
performance; it is much faster
to ‘grab’ an element stored in
a tuple, but lists are much • Create a list and populate it with
more versatile. some elements.
• Note that lists are denoted by
[] and not the () used by
tuples.
Adding elements to a list
• Lists are mutable; i.e. their contents can be
changed. This can be done in a number of ways.
• With the use of an index to replace a current
element with a new one.

In: Out:

• Replace the second element in your string with the integer 2.


Amending elements to
a list
• You can use the insert() function in order to add
an element to a list at a specific indexed location,
without overwriting any of the original elements.
In: Out:

• Use insert() to put the integer 3 after the 2 that


you just added to your string.
Amending elements to
a list
• You can add an element to the end of a list
using the append() function.
In: Out:

• Use append() to add the string “end” as the last


element in your list.
Removing elements from a
list
• You can remove an element from a list based upon
the element value.
• Remember: If there is more than one element with
this value, only the first occurrence will be
removed.
In: Out:
Removing elements from a
list
• It is better practice to remove elements by their
index using the del function.

In: Out:

• Use del to remove the 3 that you added to


the list earlier.
OPERATORS
Operators
Python divides the operators in the following groups:
Arithmetic operators

Assignment operators

Comparison operators

Logical operators

Identity operators

Membership operators

Bitwise operators
# Examples of Arithmetic Operator
a=9
b=4 Arithmetic Operat
add = a + b
sub = a - b
mul = a * b
div1 = a / b
div2 = a // b
mod = a % b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
# Examples of Relational Operators
a = 13
b = 33 Comparison
print(a > b) Operators
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Logical
• # Examples of Logical Operator Operators
• a = True
• b = False
• print(a and b)
• print(a or b)
• print(not a)
Identity and Membership
Operators
• a , b=60 , 13
• print("a=",bin(a),"\nb=",bin(b))
• print("a&b=",bin(a&b)) Bitwise Operators
• print("a|b=",bin(a|b))
Operator Description Example
• print("a^b=",bin(a^b)) (a & b) (means 0000
& Binary AND
• print("a|b=",bin(a|b)) 1100)
(a | b) = 61 (means
| Binary OR
• print("~a=",bin(~a)) 0011 1101)
(a ^ b) = 49 (means
^ Binary XOR
• print("a<<2=",bin(a<<2)) 0011 0001)
(~a ) = -61 (means 1100
• print("a>>b=",bin(a>>2)) Binary Ones 0011 in 2's complement
~
Complement form due to a signed
binary number.
Binary Left a << 2 = 240 (means
<<
Shift 1111 0000)
Binary Right a >> 2 = 15 (means
>>
Shift 0000 1111)
Assignment
Operators
Operator Example
= c = a + b assigns value of a + b into c
+= c += a is equivalent to c = c + a
-= c -= a is equivalent to c = c - a
*= c *= a is equivalent to c = c * a
c /= a is equivalent to c = c / ac /= a is
/=
equivalent to c = c / a
%= c %= a is equivalent to c = c % a
**= c **= a is equivalent to c = c ** a
//= c //= a is equivalent to c = c // a
Sr.No. Operator & Description
1 ** Exponentiation (raise to the power)
Operator Precedence
2 ~ + - Complement, unary plus and minus
3 * / % // Arithmetic Operator
4 + - Arithmetic Operator
5 >> << Bitwise Shift
6 & Bitwise 'AND'
7 ^ | Bitwise exclusive `OR' and regular `OR'
8 <= < > >= Comparison operators
9 <> == != Equality operators
10 = %= /= //= -= += *= **= Assignment operators
11 is , is not Identity Operator
12 in , not in Membership Operator
13 not , or , and Logical operators
Turtle
Graphics
Turtle Graphics
• Is a module to draw graphic primitives (Line, Circle, Rectangle etc. )
• Import turtle module (Import Turtle )
• Useful Functions
• turtle.showturtle()
• turtle.backward(50)
• turtle.right(70)
• turtle.forward(50)
• turtle.goto(50,50)
• turtle.penup()
• turtle.pendown()
• turtle. circle(45)
• turtle.color(“blue”)
• turtle.pensize(3)
Example (Line Drawing)
• import turtle
• x1, y1=eval(input("Enter x1,y1:"))
• x2, y2=eval(input("Enter x2,y2:"))
• distance=((x1-x2)**2+(y1-y2)**2)**0.5
• #distance=format(distance,'10.2f')
• turtle.penup()
• turtle.goto(x1,y1)
• turtle.write("P1")
• turtle.pendown()
• turtle.goto(x2,y2)
• turtle.write("P2")
• turtle.penup()
• turtle.goto((x1+x2)/2, (y1+y2)/2)
• turtle.write(distance)
• turtle.hideturtle()
• turtle.done()
import turtle Example
turtle.pensize(3)
turtle.color("red")
turtle.penup()
# Triangle
turtle.goto(-200,-50)
turtle.pendown()
turtle.circle(40, steps=3)
# Rectangle
turtle.penup()
turtle.goto(-100,-50)
turtle.pendown()
turtle.circle(40, steps=4)
# Pentagon
turtle.penup()
turtle.goto(0,-50)
turtle.pendown()
turtle.circle(40, steps=5)
Example (filled region)
• # Octagon
• turtle.penup()
• turtle.goto(200,-50)
• turtle.begin_fill()
• turtle.color(“purple")
• turtle.pendown()
• turtle.circle(40, steps=8)
• turtle.end_fill()
SELECTIVE
Statements
SELECTIVE STATEMENTS

• Single Selection (if):

• Double Selection (if-else):

• Multiple Selection (if-elif):

• Nested Selective Structure:


SELECTIVE STATEMENTS

• # if to check even number


• Single Selection (if): • a , b = 10, 15
• if a % 2 == 0:
• Double Selection (if-else): • print("Even Number")
• # if-else to check even or odd
• if b % 2 == 0:
• print("Even Number")
• else:
• print("Odd Number")
SELECTIVE
• Multiple Selection (if-elif):
STATEMENTS
• Nested Selective Structure:
• if a % 2 == 0:
• if a % 5 == 0:
• print("Number is divisible by both 2 and 5")
• # if-elif
• if (a == 11):
• print ("a is 11")
• elif (a == 10):
• print ("a is 10")
• else:
• print ("a is not present")
SELECTIVE STATEMENTS
•Indentation
a = 33
b = 200
if b > a:
print("b is greater than a") # Indentation error
•One Line if & if-else
if a > b: print("a is greater than b")
print("A") if a > b else print("B")
• The pass Statement: if statement with no content,
put in the pass statement to avoid getting an error.
if b > a:
pass
Functions
Functions

• A function is a collection of statements that perform


some specific task and return the result to the caller
• The user the ability to reuse the same code
• In Python, def keyword is used to create functions:
def function_name(arguments):
statements
Example
• def function_A():
• print("Hello from a function A")
• def function_B():
• print("Hello from a function B")
• # Driver Code
• function_B()
• function_A()
Example (Function with
Arguments)
main
Function
Arbitrary number of
Arguments
• def display_record(*arg):
• print(arg[0], arg[1], arg[2])
• # Driver Code
• def main():
• display_record("10-NTU-1149", "Ali Ahmad", "BSSE")
• main()
Keyword Arguments

• Arguments can be send with name key = value syntax.


• This way the order of the arguments does not matter.
• Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = “Ali", child2 = “Ahmad", child3 = “Sara")


Return Values

• To let a function return a value, use the return


statement:
• Example
• def my_function(x):
• return 5 * x
• print(my_function(3))
• print(my_function(5))
• print(my_function(9))
Passing a List as an
Argument
• Any data types can be send as argument to a function
(string, number, list, dictionary etc.),
• And it will be treated as the same data type inside the
function.
• Example
def my_function(food):
print(food)
# Driver Code
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Recursive Functions

• Python also accepts function recursion, which


means a defined function can call itself.
• Recursion is very effective technique
• The developer should be very careful with
recursion to avoid infinite recursive calls
• For this purpose carefully design base case
(ending condition for recursion)
Recursive Functions

• def display(k):
• if(k>0): #Base Case
• display(k-1)
• print(k)
• #Driver Code
• a=eval(input("\n\nEnter a Number:"))
• display(a)

You might also like