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

Introduction To Basic Python

This document provides an introduction to basic Python concepts including: 1) Why Python is popular for machine learning, data science, and software development due to its libraries and properties for new programmers. 2) Examples of writing a basic "Hello World" program, creating variables, and Python's built-in data types. 3) How to set the data type of variables explicitly, cast between data types, and work with booleans.

Uploaded by

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

Introduction To Basic Python

This document provides an introduction to basic Python concepts including: 1) Why Python is popular for machine learning, data science, and software development due to its libraries and properties for new programmers. 2) Examples of writing a basic "Hello World" program, creating variables, and Python's built-in data types. 3) How to set the data type of variables explicitly, cast between data types, and work with booleans.

Uploaded by

h usman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Introduction to basic Python

February 8, 2023

1 Introduction to basic Python


Dr. Bahar Ali
Assistant Professor (CS), National University Of Computer and Emerging Sciences,
Peshawar.

2 Why Python?
Python is the most popular programming language. It was created by Guido van Rossum, and
released in 1991. Python is used for machine learning, data science as well as software development.
It offers a wide variety of libraries related to machine learning and data science.
Python is a mature programming language, it also has excellent properties for newbie programmers,
making it ideal for people who have never programmed before.
Some of the most remarkable properties of Python are as follow; 1. Easy to read code 2. Suppression
of non-mandatory delimiters 3. Python uses indentation to define scope 4. Dynamic typed, and
dynamic memory usage 5. Python is an interpreted indentation language, the code is executed
immediately in the Python console 6. Python can be run on interactive consoles (Jupyter notebook,
IPython) 7. Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc) 8.
Python has a simple syntax similar to the English language and allows developers to write programs
with fewer lines. 9. Python can be treated in a procedural way or an object-orientated way.
[ ]:

2.1 Writing the First Python Program


[ ]: print ("Hello, World!")

Hello, World!

2.2 Creating Variables


Variables are containers for storing data values.

A variable is created the moment you first assign a value to it


[ ]: x = 10
y = "Pakistan"

1
print("Integer Variable: ", x)
print("String Variable", y)
print(type(x))

Integer Variable: 10
String Variable Pakistan
<class 'int'>

Variables do not need to be declared with any particular type and can even change
type after they have been set.
[ ]: x = 10 # Here x is of type int
x = "Converted to String" # Here, the type of x is changed to string
print(x)

Converted to String

2.3 Variable Name


Variable name must start with a letter or the underscore character
Variable name cannot start with a number
Variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive
[ ]: #Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

#Illegal variable names:


#2myvar = "John"
#my-var = "John"
#my var = "John"

2.4 Python Built-in Data Types


Variables store data of different types
Python has the following built-in data types, in these categories:
1. Text Type:—– str
2. Numeric Types:—– int, float, complex
3. Sequence Types:—– list, tuple, range
4. Mapping Type:—– dict
5. Set Types:—– set, frozenset

2
6. Boolean Type:—– bool
7. Binary Types:—– bytes, bytearray, memoryview x_str = “Hello World” x_int = 20 x_flt
= 20.5 x_com = 1j x_list = [“apple”, “banana”, “cherry”, 9] x_tpl = (“apple”, “banana”,
“cherry”)
x_range = range(3,6) #An in-built function. It returns a sequence of numbers. #range(start,
stop, step) #start: Optional parameter. Starting point of sequence. By default, it’s zero. #stop:
Mandatory parameter. Stopping point of the sequence, Sequence stops just before the given number.
#step: Optional parameter. The incrementation on each iteration. By default, the value is one.
x_dic = {“name” : “John”, “age” : 36} x_set = {“apple”, “banana”, “cherry”} x_fset =
frozenset({“apple”, “cherry”, “banana”}) #is an immutable version of a Python set object x_bol
= True
#print(type(x_rang))

[ ]: x_str = "Hello World"


x_int = 20
x_flt = 20.5
x_com = 1j
x_list = ["apple", "banana", "cherry", 9]
x_tpl = ("apple", "banana", "cherry")

x_range = range(3,6) #An in-built function. It returns a sequence of numbers.


#range(start, stop, step)
#start: Optional parameter. Starting point of sequence. By default, it’s zero.
#stop: Mandatory parameter. Stopping point of the sequence, Sequence stops␣
,→just before the given number.

#step: Optional parameter. The incrementation on each iteration. By default,␣


,→the value is one.

x_dic = {"name" : "John", "age" : 36}


x_set = {"apple", "banana", "cherry"}
x_fset = frozenset({"apple", "cherry", "banana"}) #is an immutable version of a␣
,→Python set object

x_bol = True

print(type(x_com))

<class 'complex'>

[ ]: #Printing Set/ frozen set values


for x_val in x_fset:
print(x_val)

cherry
banana
apple

3
[ ]: #Printing dictionary values
for index, val in x_dic.items():
print(index, ":", val)

name : John
age : 36

[ ]: ## Tuple acts as key for value in dictionary


my_dict = {x_tpl:1}
my_dict

[ ]: {('apple', 'banana', 'cherry'): 1}

[ ]: x_list = ["apple", "banana", "cherry", 9]


x_list.append("Mango")

[ ]: print(x_list)

['apple', 'banana', 'cherry', 9, 'Mango']

[ ]: ## Frozen set acts as key for value in dictionary


myd = {x_fset: 989}

[ ]: myd[x_fset]

[ ]: 989

[ ]:

[ ]: # initialize my_set
my_set = {1, 3}
print(my_set)

#print(my_set[0]) # TypeError: 'set' object does not support indexing

my_set.add(2)
print(my_set)

# add multiple elements


# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)

# add list and set


# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)

4
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}

[ ]: # initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard an element
my_set.discard(4)
print(my_set)

# remove an element
my_set.remove(6)
print(my_set)

# discard an element does not throw an error, if element is not present in a␣


,→set

my_set.discard(2)
print(my_set)

# remove an element throws an error, if element is not present in a set


#my_set.remove(2)

{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}

2.5 Setting the Specific Data Type


[ ]: x_str = str("123")
x_int = int(100.0)
x_flt = float(100)
x_comp = complex(2j)
x_list = list(("apple", "banana", "cherry"))
x_tpl = tuple(["apple", "banana", "cherry"])
x_rang = range(10)
x_dic = dict(name="Ali", age=40)
x_set = set(("apple", "banana", "cherry"))
x_fset = frozenset(("apple", "banana", "cherry"))
x_bol = bool(15)
x_byt = bytes(15)
x_byt_arr = bytearray(15)
x_mem = memoryview(bytearray(15))
print(type(x_mem))

5
<class 'memoryview'>

[ ]: # Buffer protocol provides a way to access the internal data of an object.


# This internal data is a memory array or a buffer.
# It allows one object to expose its internal data (buffers) and the other to␣
,→access those buffers without intermediate copying.

# Buffer protocol is only accessible to us at the C-API level and not using our␣
,→normal codebase.

# So, to expose the same protocol to a normal Python codebase, memory views are␣
,→present.

# Python program to illustrate


# Modifying internal data using memory view
# random bytearray
byte_array = bytearray('XYZ', 'utf-8')
print('Before update:', byte_array)

mem_view = memoryview(byte_array)

#Update 2nd index of mem_view to J, 74 is an ASCII code for letter "J"


mem_view[2] = 74
print('After update:', byte_array)

Before update: bytearray(b'XYZ')


After update: bytearray(b'XYJ')

[ ]: value = '20'
prod_str = value * 3
prod_int = int(value) * 3

print(prod_str)
print(prod_int)

202020
60

2.6 Python Casting


Casting in python is done using constructor functions:
int() - constructs an integer number from an integer literal, a float by rounding to the whole part
in a number, a string providing the string represents a valid number
float() - constructs a float number from an integer literal, a float literal or a string literal providing
the string represents a valid number.
str() - constructs a string from a wide variety of data types, including strings, integer literals and
float literals

6
[ ]: x = int(20) # x will be 20
y = int(5.8) # y will be 5
z = int("12") # z will be 12
#w = int("13d") # Invalid literal
print(y)

[ ]: x = float(30) # x will be 30.0


y = float(4.5) # y will be 4.5
z = float("456") # z will be 456.0
w = float("5.6") # w will be 5.6
#x_in = float("5.6c") # Invalid literal
print(w)

5.6

[ ]: x = str("Values are 1, 2, 4..") # x will be 'Values are 1, 2, 4..'


y = str(56) # y will be '56'
z = str(20.0) # z will be '20.0'
print(x)

Values are 1, 2, 4..

2.7 Python Booleans


Booleans represent one of two values: True or False.
[ ]: x = True
y = False

print(x)
print(y)

print(10 > 9)
print(10 == 9)
print(10 < 9)

True
False
True
False
False

[ ]:

[ ]: if (x):
print("X is True")

7
else:
print("X is False")

X is True

[ ]: print(bool(0))
print(bool(1))
print(bool(-1))

False
True
True

[ ]: print(bool("Hello"))
print(bool(''))
print(bool(""))
print(bool(' '))
print(bool('None'))
print(bool(None))

True
False
False
True
True
False

[ ]: # In Python, NaN is a special floating-point value returned by certain␣


,→operations

# when one of their results ends in an undefined value.


# A subtle feature of NaN values is that two NaN are never equal.

if float('NaN') == float('NaN'):
print("Equal")
else:
print("Not Equal")

Not Equal

[ ]: import numpy as np
print(bool(np.nan))
print(np.nan)

if np.nan == np.nan:
print(True)
else:
print(False)

8
True
nan
False

[ ]: print(bool(None))
print(bool(()))
print(bool([]))
print(bool({}))

False
False
False
False

2.8 Python Operators


In Python the operators are divided in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
[ ]: ## Python Arithmetic Operators
x = 15
y = 2

res_add = x + y
res_sub = x - y
res_mul = x * y
res_div = x / y
res_mod = x % y

res_floor = x // y # Floor division

res_exp = x ** y
print(res_exp)
print(res_floor)

225
7

[ ]:

[ ]:

9
[ ]: # Python Assignment Operators
x = 5 # x = 5
print("x: ", x)

x += 3 # x = x + 3
print("x + 3: ", x)
x -= 3 # x = x - 3
print("x - 3: ", x)
x *= 3 # x = x * 3
print("x * 3: ", x)
x /= 3 # x = x / 3
print("x / 3: ", x)
x **= 3 # x = x ** 3
print("x ** 3: ", x)
x //= 3 # x = x // 3
print("x // 3: ", x)
x %= 3 # x = x % 3
print("x % 3: ", x)

x: 5
x + 3: 8
x - 3: 5
x * 3: 15
x / 3: 5.0
x ** 3: 125.0
x // 3: 41.0
x % 3: 2.0

[ ]:

[ ]: 110

[ ]: # Python Bitwise assignment


x = 6
print("\nx: ", x)

x &= 3 # x = x & 3
print("x & 3: ", x)

x = 6
x |= 3 # x = x | 3
print("\nx: ", x)
print("x | 3: ", x)

x = 6
print("\nx: ", x)
x ^= 3 # x = x ^ 3

10
print("x ^ 3: ", x) # XOR

x = 6
print("\nx: ", x)
x >>= 2 # x = x >> 3
print("x >> 3: ", x)

x = 6
print("\nx: ", x)
x <<= 3 # x = x << 3
print("x << 3: ", x)

#x=6 => 00000110


#3 => 00000011
#x&3 => 00000010 = 2

x: 6
x & 3: 2

x: 7
x | 3: 7

x: 6
x ^ 3: 5

x: 6
x >> 3: 1

x: 6
x << 3: 48

[ ]:

[ ]:

[ ]: # Python Comparison Operators


a = 5
b = 7
print(a,"==",b, a==b)
print(a,"!=",b, a!=b)
print(a,">",b, a>b)
print(a,"<",b, a<b)
print(a,">=",b, a>=b)
print(a,"<=",b, a<=b)

5 == 7 False

11
5 != 7 True
5 > 7 False
5 < 7 True
5 >= 7 False
5 <= 7 True

[ ]: # Python Logical Operators


x = True
y = False
print(x, "and", y, "=", x and y)
print(x, "or", y, "=", x or y)
print("not", x, "=", not x)

# print(*objects)
# Method with *objects means multiple arguments,
# Here print takes multiple arguments, each argument separated by a space.

True and False = False


True or False = True
not True = False

[ ]: # Python Identity Operators (Interning)


x = "Python"
y = "Python"

# Both variable x and y point to same value in Heap


print(x is y) # Returns True if both variables are the same
print(x is not y) # Returns True if both variables are not the same

print(id(x))
print(id(y))
print(len("140471421999792"))

True
False
139813569166512
139813569166512
15

[ ]:

[ ]: # Python Membership Operators

x = [[5,10,15],20]
y = [5,10,15]
print(y in x) # Returns True if a sequence with the specified value is␣
,→present in the object

12
print(y not in x) # Returns True if a sequence with the specified value is␣
,→not present in the object

True
False

[ ]:

[ ]: # Python Bitwise Operators


x = 6
print("\nx: ", x)
x &= 3 # x = x & 3
print("x & 3: ", x)

x = 6
print("\nx: ", x)
x |= 3 # x = x | 3
print("x | 3: ", x)

x = 6
print("\nx: ", x)
x ^= 3 # x = x ^ 3
print("x ^ 3: ", x) # XOR

x = 6
print("\nx: ", x)
x >>= 3 # x = x >> 3, Signed right shift
print("x >> 3: ", x)

x = 6
print("\nx: ", x)
x <<= 3 # x = x << 3, Zero fill left shift
print("x << 3: ", x)

x = 6
print("\nx: ", x)
x = ~x # x = ~x => NOT => Inverts all the bits (Returns␣
,→one’s complement of the number)

print("~x: ", x)

#x=6 => 00000110


#~x => -(00000110 + 1) => -(00000111) => -7

x: 6
x & 3: 2

13
x: 6
x | 3: 7

x: 6
x ^ 3: 5

x: 6
x >> 3: 0

x: 6
x << 3: 48

x: 6
~x: -7

3 Python Lists
Four collection data types in the Python:
1. List: is a collection which is ordered and changeable. Allows duplicate members
2. Tuple: is a collection which is ordered and unchangeable. Allows duplicate members
3. Set: is a collection which is unordered and unindexed. No duplicate members
4. Dictionary: is a collection which is unordered, changeable and indexed. No duplicate members
(Keys are unique not values)
When choosing a collection type, it is useful to understand the properties of that type.
[ ]: # List
my_list = ["apple", "banana", "cherry"]
print(my_list)

[ ]: # Tuple
my_list = ("apple", "banana", "cherry")
print(my_list)

3.1 Python Tuples


A tuple is a collection which is ordered and unchangeable or immutable.
[ ]: mytuple = ("apple", "banana", "cherry", "guava", "orange", 12, 5.0,"Ali")
#print(mytuple[0])
#print(mytuple[-3])
print(mytuple[3:6])

('guava', 'orange', 12)

[ ]: for x in mytuple:
print(x)

14
apple
banana
cherry
guava
orange
12
5.0
Ali

[ ]: for x in range(len(mytuple)):
print(mytuple[x])

apple
banana
cherry
guava
orange
12
5.0
Ali

[ ]: # Deleting tuple
mytuple = ("apple", "banana", "cherry")
del mytuple
# print(mytuple)

[ ]: # Combining two tuples


mytuple1 = ("apple", "banana", "orange")
mytuple2 = ("guava", "orange", "lemon")
mytuple3 = mytuple1 + mytuple2

print(mytuple3)

('apple', 'banana', 'orange', 'guava', 'orange', 'lemon')

[ ]: # Search specific value and returns the position of first occurrence in a tuple
index_num = mytuple3.index('guava')
print(index_num)

# Count all items with specific value in a tuple


count_items = mytuple3.count('orange')
print(count_items)

3
2

15
3.2 Python Sets
A set is a collection which is unordered and unindexed.
As it is unordered, therefore items cannot be accessed by referring to an index or a key.
[ ]: myset = {"apple", "banana", "cherry"}
print(myset)

{'banana', 'apple', 'cherry'}

[ ]:

[ ]: for item in myset:


print(item)

banana
apple
cherry

[ ]: if 'cherry' in myset:
print("Yes exist")

Yes exist

[ ]: myset.add('lemon')
print(myset)

{'apple', 'lemon', 'banana', 'cherry'}

[ ]: myset.remove('lemon') # Get error if lemon not in set


print(myset)

myset.discard("lemon") # No error although if lemon not in set

{'apple', 'banana', 'cherry'}

[ ]: #myset.update({'lemon','guava'}) # set working


#myset.update(['lemon','guava']) # list also working
myset.update(('lemon','guava')) # tuple also working
print(myset)

{'guava', 'apple', 'banana', 'cherry', 'lemon'}

3.3 Python Dictionaries


A dictionary is a key value pair collection which is unordered, mutable and indexed.
[ ]: mydict = {
"name": "Ali",

16
"age": 30,
"address": "House#400, Street#12"
}
print(mydict)

{'name': 'Ali', 'age': 30, 'address': 'House#400, Street#12'}

[ ]: name = mydict['name']
print(name)

Ali

[ ]: # You can also used get() method of dictionaly to access value


name = mydict.get('name')
print(name)

Ali

3.4 Python Conditions (if), (if and else), (if, elif and else )
To define scope of body of the condistion, Python uses indentation (whitespace, preferably 4 white
spaces)

[ ]: # If statement

x = 100
y = 300

if x < y:
print("x is less than y")

x is less than y

[ ]: # If else statement

x = 400
y = 300

if x < y:
print("x is less than y")

else:
print("x is not less than y")

x is not less than y

17
[ ]: # If elif else statement
x = 300
y = 300

if x < y:
print("x is less than y")

elif x > y:
print("x is greater than y")

else:
print("Both are equal")

Both are equal

[ ]: x = 100
y = 120
if x < y: print("x is less than y")

[ ]: x = 7
y = 7
my_val = "apple" if x > y else "banana" if x < y else "cherry"
print(my_val)

cherry

[ ]: # Ternary Operators (Short Hand) for If, elif and Else


# Java and C/C++ Syntax: max = (n1 > n2) ? n1 : n2;

x = 50
y = 100

# If - Else
print("x greater") if x > y else print("x not greater")

# If - Elif- Else
print("x greater") if x > y else print("y greater") if x < y else print("Both␣
,→are equal")

x not greater
y greater

[ ]: # Assign ternary result to a variable


x = 100
y = 100

18
# If - Elif- Else
my_val = "x greater" if x > y else "y greater" if x < y else "Both are equal"
print(my_val)

Both are equal

[ ]: # Using logical operators in conditions


x = 100
y = 100

if not (x < y) and not (x > y):


print("Both are equal")

Both are equal

[ ]: x = 100
y = 100
if not (x < y or x > y):
print("Both are equal")

Both are equal

3.5 Python Loops


To define scope of body of the condistion, Python uses indentation (whitespace, preferably 4 white
spaces)
Python has two primitive loops (for and while)

3.5.1 For Loop

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


for fruit in fruits:
print(fruit)

[ ]: # Loop through string value

for x in "Pakistan":
print(x)

[ ]: # For loop with range() fuction

for i in range(5): # in range(5), the loop will stop just before 5, so 5 is␣
,→inclusive

print(i)

19
[ ]: for i in range(3,11,3):
print(i)

[ ]: # Sum integer values within range 100


sum = 0
for i in range(101):
sum += i
print(sum)

[ ]: # Sum integer values within range less than 50 (using break command)
sum = 0
for i in range(101):
if i == 51:
break
sum += i

print(sum)

[ ]:

[ ]:

[ ]: # Sum even values within range (using continue command)


sum = 0
for i in range(101):
if i%2 != 0:
continue
sum += i

print(sum)

[ ]: # Nested for loop


for i in range(5):
row = ""
for j in range(6):
row = row + str(j) + ","
print(row)

3.5.2 While Loop

20
[ ]: # Sum integer values within range
sum = 0
i = 1
while i <= 100:
sum += i
i += 1
print(sum)

[ ]: # Sum integer values within range less than 50 (using break command)
sum = 0
i = 1
while i <= 100:
sum += i
i += 1
if i == 51:
break

print(sum)

[ ]: # Sum even values within range (using continue command)


sum = 0
i = 1
while i <= 100:

if i%2 != 0:
i += 1
continue

sum += i
i += 1

print(sum)

[ ]: # Nested while loop


i = 0
while i < 5:
row = ""

j = 0
while j < 6:
row = row + str(j) + ","
j += 1
print(row)
i += 1

[ ]: sum = 0
input_value = 0

21
while input_value != 'q':
sum += int(input_value)
print("Sum = ", sum)
print("Enter New number to add")
input_value = input()

3.6 Python Functions


A function is a block of code which only runs when it is called.
You pass parameters to a function and function return data as a result.
Function in Python always return something
To return value use keyword ‘return’
[ ]: def my_function():
print("This is my firt function in Python")
#return 66

[ ]: ret_value = my_function()

[ ]: print(ret_value)

[ ]: # Parametrized method and Number of Arguments

# Single argument
def my_function1(name):
print("Hello,", name)

# Two arguments
def my_function2(message, name):
print(message , name)

[ ]: my_function1("World")
my_function2("Hello,", "World")

[ ]: # Arbitrary Arguments, *args


# Add a * for arbitrary arguments before the parameter name in the function␣
,→definition .

# This way the function will receive arguments as tuples

def my_function(*args):
for arg in args:
print(arg)

for i in range(len(args)):

22
print(args[i])

my_function("Ali", 40, "Street#123")

[ ]:

[ ]: # Keyword Arguments, You can also pass argument with its name
# Here order of the arguments passed is not necessary.

def my_function(name, age, address):


print(name, age, address)

my_function(name = "Ali", address = "Street#134", age = 40)

[ ]: # Arbitrary Keyword Arguments, **kwargs

def my_function(**args):
print(args['name'])
print(args['age'])
print(args['address'])

#for arg in args:


# print(arg)

my_function(name="Ali", age=40, address="Street#123")

[ ]: # Default Parameter Value


# If a function with default arguments is called without arguments, it uses the␣
,→default values

# Default argument should not be followed by non-default arguments

def my_function(age, name='No Name', address="No Address"):


print(name)
print(age)
print(address)

my_function(age=40)

[ ]: # Passing a List as an Argument


def my_function(values):
print(values)

my_function(['Ali',30,'Adress'])

23
[ ]: # Function definitions cannot be empty, but if you want to have a function␣
,→definition without content,

# Use the pass statement

[ ]: # Passing a List as an Argument


def my_function():
pass

my_function()

3.7 Recursion
Recursion is when a statement in a function calls itself repeatedly
Recursion is a common programming concept.
[ ]: #Fibonacci Series
# 0, 1, 1, 2, 3, 5, 8, 13, 21
def fib(n):
if(n <= 1):
return 0

elif(n == 2):
return 1

else:
return fib(n-2) + fib(n-1)

n = 8
print("\n\nFibonacci number at position ", n, " is", fib(n))

[ ]: fact = 1
for i in range(4):
fact += fact*(4-i);

print(fact)

[ ]: def fact(n):
if n == 1:
return 1
else:
return n*fact(n-1)

fact(5)

[ ]: #Sum integer nubmer to specific range using recursion


def sum(n):
if(n <= 1):

24
return 1
else:
return n + sum(n-1)

print("\nSum: ", sum(4))

3.8 Python Lambda


A lambda function is a small anonymous function
A lambda function can take any number of arguments, but can only have one expression
[ ]: x = lambda a, b : a + b

print(x(5,15))

[ ]: #Creating dynamically double, thrice etc of a number method

def myfunc(n):
return lambda a : n * a

lamda_func = myfunc(3) # Here the method is created dynamically, which will␣


,→double/ thrice of every number

# lamda_func = lambda a : 3 * a # Actually, this happens

print(lamda_func(11))

[ ]: thrice = myfunc(3)

[ ]: thrice(12)

[ ]: #Creating dynamically square, cube etc method

def myfunc2(n):
return lambda a : n ** a # Power function

lamda_func2 = myfunc2(3) # Here the method is created dynamically, which will␣


,→calculate power of every number

# lamda_func = lambda a : 3 ** a # Actually, this happens

print(lamda_func2(4))

3.9 Python Classes and Objects


Python is an object oriented programming language.

25
Almost everything in Python is an object.
A Class is a template or blueprint for creating objects.
[ ]: class MyClass:
name = 'Sahir'

[ ]: my_obj = MyClass()
my_obj.name

[ ]: # __init__() Function
class MyClass:
def __init__(self, name, age=0, address='No Address'):
self.name = name
self.age = age
self.address = address

my_obj = MyClass('Khan', 43, 'Hayatabad')


my_obj.address

[ ]: # Access private attribute with class method

class MyClass:
def __init__(self, name, age=0, address='No Address'):
self.name = name #Public
self._age = age #Protected
self.__address = address #Private

def get_name(self):
return self.name

def get_age(self):
return self._age - 10

def get_address(self):
return self.__address

my_obj = MyClass('Khan', 43, 'Hayatabad')


#print(my_obj.name)
print(my_obj._age)

[ ]: # Note:
# The single underscore for protected doesn't prevent instance variables from␣
,→accessing or modifying

# the instance from outside class. Although, if your are using the property to␣
,→modify the attribute, it is

# still accessible in Python. Hence, the responsible programmer would avoid/


,→refrain from accessing and modifying

26
# the instance variables prefixed with _ from outside its class.

[ ]:

[ ]: # Inheritance
class Employee:
def __init__(self, fname, lname):
self.firstname = fname
self._lastname = lname

def __str__(self):
return self.firstname + " " + self._lastname

def __repr__(self):
return 'First Name: {}, Last Name: {}'.format(self.firstname,self.
,→_lastname)

class Teacher(Employee):
def __init__(self, fname, lname, specialization):
#Employee.__init__(self, fname, lname)
super().__init__(fname, lname)
self.specialization = specialization

def __str__(self):
return super().__str__() + " with specialization " + self.
,→specialization

def __repr__(self):
return super().__repr__() + ', Specialization: {}'.format(self.
,→specialization)

teacher_obj = Teacher("Muhammad", 'Khan', "Information Security")


print(teacher_obj) # By Default __str__ method is called␣
,→(Implicitly called)

print(teacher_obj.__str__()) # Explicity calling __str__ method


print(teacher_obj.__repr__()) # Explicity calling __repr__ method,
#__repr__ method is implicilty called, when␣
,→__str__ method is not there

[ ]:

3.10 Python File Open


File handling is an important part of programing language
In Python we can create, read, append to, and delete files.

27
Following are the modes of file opening
1. “r” => Read: Default value. Opens a file for reading, error if the file does not exist
2. “a” => Append: Opens a file for appending, creates the file if it does not exist.
3. “w” => Write: Opens a file for writing, creates the file if it does not exist
4. “x” => Create: Creates the specified file, returns an error if the file exists
Two modes of File handling
1. “t” => Text: Default value
2. “b” => Binary: Binary mode
[ ]: f = open("Normal.csv")
#f = open("Normal.csv", "rt") # Read in text mode
#print(f.read(10))
print(f.read())

[ ]: f = open("Normal.csv")
for line in f:
print(line)

[ ]: f = open("Normal.csv")
line = f.readline()

while(line):
print(line)
line = f.readline()

[ ]: f = open("TestFile.txt", "w")
f.write("Hello, World!")
f.close()

f = open("TestFile.txt", "r")
print(f.read())
f.close()

[ ]:

[ ]: f = open("TestFile.txt", "a")
f.write("\nAgain Hello, World!")
f.close()

f = open("TestFile.txt", "r")
print(f.read())
f.close()

28
[ ]: # The "with" statement clarifies code that previously would use try and finally␣
,→blocks to ensure that clean-up

# code is executed. The with statement will automatically close the file at the␣
,→end of with block. If an

# exception occurs before the end of the block, it will close the file before␣
,→the exception is caught by an

# outer exception handler. If the nested block were to contain a return␣


,→statement, or a continue or break

# statement, the with statement will also ensure automatically closing of the␣
,→file in these cases.

with open("TestFile.txt", "r") as f:


print(f.read())

#print(f.read()) # It will throw an exception, as file 'f' is already closed␣


,→at the end of "with" bloack.

[ ]:

[ ]: #f = open("TestFile.txt", "x")

[ ]: # Deleting File
f = open('TestFile.txt', 'w')

import os
if os.path.exists("TestFile.txt"):
os.remove("TestFile.txt")
print("File removed")
else:
print("There is no such file exist")

[ ]: # Deleting File
if os.path.exists("TestFile.txt"):
os.remove("TestFile.txt")
print("File removed")
else:
print("There is no such file exist")

[ ]: #Creating Directory

import os
os.mkdir("mydir")

[ ]: #Deleting Directory

import os

29
if os.path.exists("mydir"):
os.rmdir("mydir")
print("Deleted")
else:
print("There is no such directory exist")

[ ]:

3.11 Python Built-in Functions


[ ]: #The type() function returns the type of the specified object.

list_of_fruits = (1, 2, 3, 4)
print(type(list_of_fruits))

[ ]: #The input() function allows taking the input from the user.
a = input('Enter Value:')
print(a)

[ ]: #The dir() function returns all the properties and methods of the specified␣
,→object.

print(dir(str))

[ ]: #The sorted() function returns a sorted list of the specified iterable object.

[ ]: tuple = ("d", "e", "b", "a", "c")


print(sorted(tuple))

[ ]: tuple = ("d", "e", "b", "a", 0)


#print(sorted(tuple))
#Note: If a list contains string values as well as numeric values, then sorted␣
,→method does not work.

[ ]: # The ord() function returns the number representing the Unicode code of a␣
,→specified character.

[ ]: a = ord("a")
print(a)

a = ord("A")
print(a)

[ ]: #The help() function is used to display the documentation of modules,␣


,→functions, classes, keywords, etc.

help(sum)
#help() Try this one

30
[ ]: # The zip() function returns a zip object, which is an iterator of tuples where␣
,→the first item in each

# passed iterator is paired together, and then the second item in each passed␣
,→iterator are paired together etc.

a = ("1", "2", "3")


b = ("One", "Two", "Three")

x = zip(a, b)
print(type(x))
for xx in x:
print(xx)

[ ]: a = ("1", "2", "3")


b = ("I", "II", "III")
c = ("One", "Two", "Three")

x = zip(a, b, c)
print(type(x))
for xx in x:
print(xx)

[ ]: def myfunc(n):
return len(n)

x = map(myfunc, ('apple', 'banana', 'cherry'))


print(tuple(x))

[ ]: def myfunc(a, b):


return a + "-" + b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))


print(tuple(x))

[ ]:

31

You might also like