Introduction To Basic Python
Introduction To Basic Python
February 8, 2023
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.
[ ]:
Hello, World!
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
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_bol = True
print(type(x_com))
<class 'complex'>
cherry
banana
apple
3
[ ]: #Printing dictionary values
for index, val in x_dic.items():
print(index, ":", val)
name : John
age : 36
[ ]: print(x_list)
[ ]: myd[x_fset]
[ ]: 989
[ ]:
[ ]: # initialize my_set
my_set = {1, 3}
print(my_set)
my_set.add(2)
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)
my_set.discard(2)
print(my_set)
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
5
<class 'memoryview'>
# 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.
mem_view = memoryview(byte_array)
[ ]: value = '20'
prod_str = value * 3
prod_int = int(value) * 3
print(prod_str)
print(prod_int)
202020
60
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)
5.6
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
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
res_add = x + y
res_sub = x - y
res_mul = x * y
res_div = x / y
res_mod = x % y
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
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
x & 3: 2
x: 7
x | 3: 7
x: 6
x ^ 3: 5
x: 6
x >> 3: 1
x: 6
x << 3: 48
[ ]:
[ ]:
5 == 7 False
11
5 != 7 True
5 > 7 False
5 < 7 True
5 >= 7 False
5 <= 7 True
# print(*objects)
# Method with *objects means multiple arguments,
# Here print takes multiple arguments, each argument separated by a space.
print(id(x))
print(id(y))
print(len("140471421999792"))
True
False
139813569166512
139813569166512
15
[ ]:
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
[ ]:
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
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)
[ ]: 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)
print(mytuple3)
[ ]: # Search specific value and returns the position of first occurrence in a tuple
index_num = mytuple3.index('guava')
print(index_num)
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
[ ]: if 'cherry' in myset:
print("Yes exist")
Yes exist
[ ]: myset.add('lemon')
print(myset)
16
"age": 30,
"address": "House#400, Street#12"
}
print(mydict)
[ ]: name = mydict['name']
print(name)
Ali
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")
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")
[ ]: 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
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
18
# If - Elif- Else
my_val = "x greater" if x > y else "y greater" if x < y else "Both are equal"
print(my_val)
[ ]: x = 100
y = 100
if not (x < y or x > y):
print("Both are equal")
for x in "Pakistan":
print(x)
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 less than 50 (using break command)
sum = 0
for i in range(101):
if i == 51:
break
sum += i
print(sum)
[ ]:
[ ]:
print(sum)
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)
if i%2 != 0:
i += 1
continue
sum += i
i += 1
print(sum)
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()
[ ]: ret_value = my_function()
[ ]: print(ret_value)
# 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")
def my_function(*args):
for arg in args:
print(arg)
for i in range(len(args)):
22
print(args[i])
[ ]:
[ ]: # Keyword Arguments, You can also pass argument with its name
# Here order of the arguments passed is not necessary.
def my_function(**args):
print(args['name'])
print(args['age'])
print(args['address'])
my_function(age=40)
my_function(['Ali',30,'Adress'])
23
[ ]: # Function definitions cannot be empty, but if you want to have a function␣
,→definition without content,
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)
24
return 1
else:
return n + sum(n-1)
print(x(5,15))
def myfunc(n):
return lambda a : n * a
print(lamda_func(11))
[ ]: thrice = myfunc(3)
[ ]: thrice(12)
def myfunc2(n):
return lambda a : n ** a # Power function
print(lamda_func2(4))
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
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
[ ]: # 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
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)
[ ]:
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
# statement, the with statement will also ensure automatically closing of the␣
,→file in these cases.
[ ]:
[ ]: #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")
[ ]:
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.
[ ]: # The ord() function returns the number representing the Unicode code of a␣
,→specified character.
[ ]: a = ord("a")
print(a)
a = ord("A")
print(a)
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.
x = zip(a, b)
print(type(x))
for xx in x:
print(xx)
x = zip(a, b, c)
print(type(x))
for xx in x:
print(xx)
[ ]: def myfunc(n):
return len(n)
[ ]:
31