Shanto mariam university of
creative thchnology
Assignment No-01- Starting To Mid
Course Title-Python Programming Language
Course Code-CSE4116
Submitted To
Dr. Md. Robiul Islam
Lecturer of SMUCT
Department of CSE & CSIT
Submitted BY
Name : Md Hasan Miah
Id : 183071021
Semester : 10th
Department : CSE
1
June 8, 2022
[1]: #python introduction
#python basic
print("hello world")
hello world
[2]: # Python Data Type
#Text Type: str
#Numeric Types: int, float, complex
#equence Types: list, tuple, range
#Mapping Type: dict
#Set Types: set, frozenset
#Boolean Type: bool
#Binary Types: bytes, bytearray, memoryview
x= 5
y = "Hasan"
z = 20.05
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'str'>
<class 'float'>
[3]: #Assign String to a variable
a = "md hasan miah"
print(a)
#Assign multiple string variable
b = "my name is md hasan maih i am from comilla"
print(b)
2
#String are Array
c = "Hello World"
print(a[1])
#String length
d = "hellow world"
print(len(d))
md hasan miah
my name is md hasan maih i am from comilla
d
12
[3]: #check if not
text = "the best thing in life are free"
print("expensive" not in text)
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
True
No, 'expensive' is NOT present.
[12]:
llo
[4]: #Python - Slicing Strings
b = "Hello, World!"
print(b[2:5])
#Slice From the Start
b = "Hello, World!"
print(b[:5])
#Slice form the end
c = "Hello, World!"
3
print(c[2:])
#negative index
d = "hellow world"
print(d[-5:-2])
llo
Hello
llo, World!
wor
[7]: #python modify String
#upper case
#lower Case
a = "this is an Apple"
print(a.upper())
b = "MY NAME IS HASAN"
print(b.lower())
#remove whitespace
c = "hello, world"
print(c.strip())
#replacing String
d = "hello world"
print(d.replace("h","j"))
THIS IS AN APPLE
my name is hasan
hello, world
jello world
[9]: #Python - String Concatenation
a = "Hello"
b = "World"
c=a+b
print(c)
#Python - Format - Strings
4
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
#Python - Escape Characters
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
HelloWorld
I want 3 pieces of item 567 for 49.95 dollars.
We are the so-called "Vikings" from the north.
[13]: #Python Syntax
#Python Indentation
if 5 > 2:
print("Five is greater than two!")
else:
print("Five is less than two!")
Five is greater than two!
[12]: #PYTHON VARIABLE
#CREATING VARIABLE
#casting
#get the type
x = str(5)
y = int(6)
z = float(4)
a = "hasan"
print(type(x))
print(type(y))
print(type(z))
print(type(a))
#ASSIGN MULTIPLE VARIABLE
b,c,d = "md","hasan","miah"
print(b)
5
print(c)
print(d)
#ONE VALUE TO MULTIPLE VARIABLES
e=f=g="hasan"
print(e)
print(f)
print(g)
#unpack a colllection
name = ["md","hasan","miah"]
h=i=j=name
print(h)
print(i)
print(j)
#operator output multiple variale
k = "my "
l = "is "
m = "Hasan"
print(k+l+m)
#GLOBAL VARIABLE
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
<class 'str'>
<class 'int'>
<class 'float'>
<class 'str'>
md
hasan
miah
hasan
hasan
hasan
['md', 'hasan', 'miah']
['md', 'hasan', 'miah']
6
['md', 'hasan', 'miah']
my is Hasan
Python is fantastic
[17]: #Python Type Casting#####
#Integers:
x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)
#Floats:
a = float(1)
b = float(2.8)
c = float("3")
d = float("4.2")
print(a)
print(b)
print(c)
print(d)
#Strings:
e = str("s1")
f = str(2)
g = str(3.0)
print(e)
print(f)
print(g)
1
2
3
1.0
2.8
3.0
4.2
s1
2
3.0
[22]: #PYTHON BOOLEANS
7
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
#SOME VALUE ARE FALSE
class myclass():
def len (self):
return 0
myobj = myclass()
print(bool(myobj))
#Functions can Return a Boolean
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
b is not greater than a
False
YES!
[24]: #Python Operators
a= 5
b = 10
c = 15
d =20
e = a+b
f = d-c
g = d/a
h = a*b
print(e)
print(f)
print(g)
print(h)
print(a+b-c*d/f)
15
5
8
4.0
50
-45.0
[26]: #Python Lists
mylist = ["arum","bean","arum","brinjal"]
print(mylist)
print(len(mylist))
print(type(mylist))
#list item data type
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
print(list1)
print(list2)
print(list3)
#THE LIST() CONSTRUCTOR
thislist = list(("apple", "banana", "cherry"))
print(thislist)
print(type(thislist))
#Python - Access List Items
fruit_list = ["apple", "banana", "cherry"]
print(fruit_list[1])
print(fruit_list[-2])
print(fruit_list[2:5])
print(fruit_list[:4])
print(fruit_list[2:])
print(fruit_list[-1:])
print(fruit_list[-4:-2])
#check if item exists
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
print("Yes, 'apple' is in the fruits list")
#Python - Change and Add and remove List Items
9
fruits_item = ["apple", "banana", "cherry"]
fruits_item[1] = "blackcurrant"
print(fruits_item)
fruits_item[1:2] = ["mango","watermilon"]
print(fruits_item)
fruits_item.insert(2,"orange")
print(fruits_item)
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana") print(thislist)
#Clear the List
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
#Python - Loop Lists
#loop throug a list
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
#Loop through the index number
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
#using while loop
10
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i =i + 1
#Python - List Comprehension
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
#Python - Sort Lists
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
#Sort Descending
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
#revers order
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
#Python - Copy Lists
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
11
['arum', 'bean', 'arum', 'brinjal']
4
<class 'list'>
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False] ['apple',
'banana', 'cherry']
<class 'list'>
banana
banana
['cherry']
['apple', 'banana', 'cherry']
['cherry']
['cherry']
['apple']
Yes, 'apple' is in the fruits list
['apple', 'blackcurrant', 'cherry']
['apple', 'mango', 'watermilon', 'cherry']
['apple', 'mango', 'orange', 'watermilon', 'cherry']
['apple', 'cherry']
[]
apple
banana
cherry
apple
banana
cherry
apple
banana
cherry
['apple', 'banana', 'mango']
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
['pineapple', 'orange', 'mango', 'kiwi', 'banana']
['cherry', 'Kiwi', 'Orange', 'banana']
['apple', 'banana', 'cherry']
[32]: #PYTHON TUPLE
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
12
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# tuple unpacking is also possible
a, b, c = my_tuple
print(a)
print(b)
print(c)
my_tuple = ("hello")
print(type(my_tuple))
# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple))
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple))
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0])
print(my_tuple[5])
# IndexError: list index out of range
# print(my_tuple[6])
# Index must be an integer
# TypeError: list indices must be integers, not float
# my_tuple[2.0]
# nested tuple
13
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3])
print(n_tuple[1][1])
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(my_tuple[-1])
print(my_tuple[-6])
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
print(my_tuple[1:4])
# elements beginning to 2nd
print(my_tuple[:-7])
# elements 8th to end
print(my_tuple[7:])
# elements beginning to end
print(my_tuple[:])
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
# However, item of mutable element can be changed
my_tuple[3][0] = 9
print(my_tuple)
14
# Tuples can be reassigned
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
# Concatenation
print((1, 2, 3) + (4, 5, 6))
# Repeat
print(("Repeat",) * 3)
# Tuple method
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p'))
print(my_tuple.index('l'))
# Membership test in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e',)
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'dog')
3
4.6
dog
15
<class 'str'>
<class 'tuple'>
<class 'tuple'>
p
t
s
4
t
p
('r', 'o', 'g')
('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
(4, 2, 3, [9, 5])
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
2
3
True
False
True
[5]: # PYTHON SETS
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
# we can make set from a list
my_set = set([1, 2, 3, 2])
print(my_set)
# initialize my_set
my_set = {1, 3}
print(my_set)
# add an element
my_set.add(2)
print(my_set)
16
# add multiple elements
my_set.update([2, 3, 4])
print(my_set)
# add list and set
my_set.update([4, 5], {1, 6, 8})
print(my_set)
# Difference between discard() and remove()
# 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 = set("HelloWorld")
print(my_set)
# pop an element
print(my_set.pop())
# pop another element
my_set.pop()
print(my_set)
# clear my_set
my_set.clear()
print(my_set)
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
17
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
print(A & B)
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
print(A - B)
# in keyword in a set
# initialize my_set
my_set = set("apple")
# check if 'a' is present
print('a' in my_set)
# check if 'p' is present
print('p' not in my_set)
{1, 2, 3}
{1.0, 'Hello', (1, 2, 3)}
{1, 2, 3}
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{'l', 'W', 'r', 'd', 'o', 'e', 'H'}
l
{'r', 'd', 'o', 'e', 'H'}
set()
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
18
{1, 2, 3}
True
False
[2]: #PYTHON DICTONARY
# initialize dict1
dict1 = {
"brand": "Ford",
"model": "Musting",
"year": 1964,
"year": 2000
}
print(dict1)
print(dict1["year"])
print(len(dict1))
# Changing and adding Dictionary Elements
dict1 = {
"brand": "Ford",
"model": "Musting",
"year": 1964,
"colors": ["red", "green", "blue"]
}
print(dict1)
print(dict1["colors"])
print(dict1["colors"][2])
dict1["colors"][2] = "yellow"
print(dict1)
print(type(dict1))
dict1["year"] = 2022
dict1.update({"year":2020})
#remove dictonary item
dict1.pop("model")
print(dict1)
#access list which is placed in dictionary
x = dict1["year"]
print(x)
y = dict1.get("model")
print(y)
#check if key exist
if "colors" in dict1:
19
print("yes colors is one o the keys in dict1 dictionary")
#The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
#Python - Loop Dictionaries
thisdict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict1:
print(x)
###### Program for accessing keys:
this_dict = {
"brand": "Ford",
"model": "Musting",
"year": 1998
}
key = this_dict.keys()
print(key)
key_list = list(key)
print(type(key_list))
print(key_list[1])
for i in range(len(key_list)):
if key_list[i] == "model":
print("Model key Exists")
else:
continue
for x in key:
if x == "model":
20
print("Model key Exists")
else:
continue
#Python - Nested Dictionaries
myfamily = {
"child1":{
"name":"Rahim",
"year": 1889
},
"child2":{
"name":"tuli",
"year": 1989
},
"child3":{
"name": "karim",
"year": 2020
}
}
print(myfamily["child1"])
print(myfamily["child1"]["name"])
print("length of dictionary:")
print(len(myfamily))
print("Keys of dictionary:")
for x in myfamily.keys():
print(x)
print("Values of dictionary:")
for y in myfamily.values():
print(y)
print("Index wise values of dictionary:")
for y in myfamily.values():
print(y["name"])
# demo for all dictionary methods
dict1={1:"Python",2:"Java",3:"Ruby",4:"Scala"}
#copy() method
dict2=dict1.copy()
21
print(dict2)
#clear() method
dict1.clear()
print(dict1)
#get() method
print(dict2.get(1))
#items() method
print(dict2.items())
#keys() method
print(dict2.keys())
#pop() method
dict2.pop(4)
print(dict2)
#popitem() method
dict2.popitem()
print(dict2)
#update() method
dict2.update({3:"Scala"})
print(dict2)
# values() method
print(dict2.values())
{'brand': 'Ford', 'model': 'Musting', 'year': 2000}
2000
3
{'brand': 'Ford', 'model': 'Musting', 'year': 1964, 'colors': ['red', 'green',
'blue']}
['red', 'green', 'blue']
blue
{'brand': 'Ford', 'model': 'Musting', 'year': 1964, 'colors': ['red', 'green',
'yellow']}
<class 'dict'>
{'brand': 'Ford', 'year': 2020, 'colors': ['red', 'green', 'yellow']}
2020
None
yes colors is one o the keys in dict1 dictionary
{}
brand
model
22
year
dict_keys(['brand', 'model', 'year'])
<class 'list'>
model
Model key Exists
Model key Exists
{'name': 'Rahim', 'year': 1889}
Rahim
length of dictionary:
3
Keys of dictionary:
child1
child2
child3
Values of dictionary:
{'name': 'Rahim', 'year': 1889}
{'name': 'tuli', 'year': 1989}
{'name': 'karim', 'year': 2020}
Index wise values of dictionary:
Rahim
tuli
karim
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
[ ]:
23