Python : Day 2 – Lesson 2


Loops


for loop:-

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

Syntax:


for iterator_var in sequence: statements(s)


# Python program to illustrate for i in range(0, 4):

print(i)


0

1

2

3


for i in range(4): print(i)


0

1

2

3

my_list = ["Artificial", "Intelligence", "with", "wNeuron"] for i in range(len(my_list)):

print(my_list[i])


Artificial Intelligence with

wNeuron


for item in my_list: print(item)


Artificial Intelligence with

wNeuron


Assignment-1

create a list of name of length 4, using for loop also use input method to collect friends names from user


# solution


Assignment-2:-

create a list of dictioneries named profiles, each dictionary has the following attributes

Keys: values

name_of_user: str age: float

names_of_brothers: list cell_numbers: set

experience: list of dicts

experience is also a list of dicts, each dict must have the following keys and values

Keys: values

company_name: str join_date: str

end_date: str

no_of_years_worked: float

use input method to take input and for loop to iterate over


profiles = [] names_of_brothers = [] experience = []


cell_number_set = set()


no_of_bro = int(input("how many brothers you have : ")) for i in range(no_of_bro):

bro_name = input("enter name of your brother-{} : ".format(i+1)) names_of_brothers.append(bro_name)

print(names_of_brothers)


no_of_companies = int(input("in how many companies you have worked : ")) for j in range(no_of_companies):

company_name = input("enter name of your company-{} : ".format(j+1)) start_date = input("enter Join date of your company-{} : ".format(j+1)) end_date = input("enter end date of your company-{} : ".format(j+1))

years_worked = float(input("enter number of working years in company-{} : ".format(j+1))) company_dict={

"company_name": company_name, "join_date": start_date, "end_date": end_date, "no_of_years_worked":years_worked

}

experience.append(company_dict) print(experience)


no_of_cell_numbers = int(input("how many contact numbers you want to provide : ")) for k in range(no_of_cell_numbers):

cell = input("enter your cell-number-{} : ".format(k+1)) cell_number_set.add(cell)


print(cell_number_set)


user_name = input("enter Your Name : ") age = float(input("enter Your age : ")) profile_dict = {

"name_of_user": user_name, "age": age,

"names_of_brothers": names_of_brothers, "cell_numbers": cell_number_set, "experience": experience

}

profiles.append(profile_dict)


how many brothers you have : 2

enter name of your brother-1 : Adeel enter name of your brother-2 : Usman ['Adeel', 'Usman']

in how many companies you have worked : 2 enter name of your company-1 : wN

enter Join date of your company-1 : 2019 enter end date of your company-1 : 2020

enter number of working years in company-1 : 2 enter name of your company-2 : ss

enter Join date of your company-2 : 2020 enter end date of your company-2 : 2022

enter number of working years in company-2 : 1

[{'company_name': 'wN', 'join_date': '2019', 'end_date': '2020', 'no_of_years_worked': 2.0}, {'company_name': 'ss', 'join_da how many contact numbers you want to provide : 2

enter your cell-number-1 : 0333123120 enter your cell-number-2 : 0333123120

{'0333123120'}

enter Your NameKhurram enter Your Name25

profiles


[{'name_of_user': 'Khurram', 'age': 25.0,

'names_of_brothers': ['Adeel', 'Usman'], 'cell_numbers': {'0333123120'}, 'experience': [{'company_name': 'wN',

'join_date': '2019',

'end_date': '2020',

'no_of_years_worked': 2.0},

{'company_name': 'ss',

'join_date': '2020',

'end_date': '2022',

'no_of_years_worked': 1.0}]}]


while loop


The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

Syntax


while test_expression: Body of while



# Program to add natural # numbers up to

# sum = 1+2+3+...+n


# To take input from the user, # n = int(input("Enter n: "))


n = 10


# initialize sum and counter sum = 0

i = 1


while i <= n:

sum = sum + i

i = i+1 # update counter


# print the sum print("The sum is", sum)


The sum is 55


'''Example to illustrate the use of else statement with the while loop'''


counter = 0


while counter < 3: print("Inside loop") counter = counter + 1

else:

print("Inside else")


Inside loop Inside loop Inside loop Inside else


Python Operators


Operators are used to perform operations on variables and values.


Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example


+

Addition

x + y

-

Subtraction

x - y

*

Multiplication

x * y

/

Division

x / y

%

Modulus

x % y

**

Exponentiation

x ** y

//

Floor division

x // y


Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same as


=

x = 5

x = 5

+=

x += 3

x = x + 3

-=

x -= 3

x = x - 3

*=

x *= 3

x = x * 3

/=

x /= 3

x = x / 3

%=

x %= 3

x = x % 3

**=

x **= 3

x = x ** 3


Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example


==

Equal

x == y

!=

Not equal

x != y

>

Greater than

x > y

<

Less than

x < y

>=

Greater than or equal to

x >= y

<=

Less than or equal to

x <= y


Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Example


and x < 5 and x < 10

or x < 5 or x < 4

not not(x < 5 and x < 10)


Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Example


in x in y

not in x not in y


if...else statement


Syntax


if test expression: statement(s)


Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True.


password = input("please enter your password : ") if password == "hello123":

print("wellcome to WorldNeuron")


please enter your password : hello123 wellcome to WorldNeuron

password = input("please enter your password : ") if password == "hello123":

print("wellcome to WorldNeuron") else:

print("Provided password is invalid")


please enter your password : 1232 Provided password is invalid

password = input("please enter your password : ") if password == "hello123":

print("wellcome to WorldNeuron") elif password == "Hello123":

print("wellcome to WorldNeuron, you used password Hello123") elif password == "HELLO123":

print("wellcome to WorldNeuron, you used password HELLO123") else:

print("Provided password is invalid")


please enter your password : Hello123

wellcome to WorldNeuron, you used password Hello123


Assignment-3 input


my_str = "i am working as data Scientist"


remove the words 'am' and 'as'

output


my_new_str = "i working data Scientist"


my_str = "i am working as data Scientist" print("Input : ", my_str)

working_list = my_str.split() # creating token List print("tokens list : ",working_list)


for word in working_list: if word in ['am', 'as']:

working_list.remove(word)

print("tokens list with out stop words : ",working_list) my_new_str = ''

for word in working_list:

my_new_str = my_new_str + word + ' ' print("Output : ",my_new_str)

Input : i am working as data Scientist

tokens list : ['i', 'am', 'working', 'as', 'data', 'Scientist']

tokens list with out stop words : ['i', 'working', 'data', 'Scientist'] Output : i working data Scientist


Assignment-4 Given Data


```

user_records = [

{

"username": "ali", "password": "12345"

},

{

"username": "khurram@34", "password": "kkkaaalll"

},

{

"username": "admin", "password": "admin@$12pQ"

}

]

```


above is record for username and passwords

required

ask to user to enter username and password. verify from user_records if username and password are correct print message "Successfully Logged in" otherwise print "you have entered wrong username or password


# solution


Anaconda Installation


For Windows:

https://docs.anaconda.com/anaconda/install/windows/

For Ubuntu:

https://docs.anaconda.com/anaconda/install/linux/


Pycharm Installation


For Windows

https://www.jetbrains.com/pycharm/download/#section=windows

For Linux

https://linuxize.com/post/how-to-install-pycharm-on-ubuntu-18-04/


Virtual Environment


Assignment-5


NOTE: please use pycharm for this assignment Create a python file named myCode.py

in file myCode.py write the following code step by step:

  1. display the following message "please enter the marks of tests Math, computer, and english conducted in the 1st week of Aug-2022".

  2. use input method to get marks of "math" and keep inside variable "math_marks".

  3. use input method to get marks of "computer" and keep inside variable "comp_marks".

  4. use input method to get marks of "english" and keep inside variable "eng_marks".

  5. calculate average marks of student of 1st week and keep this average in a variable named "avg".

  6. display the average marks of 1st week

  7. display the following message "please enter the marks of tests Math, computer, and english conducted in the 2nd week of Aug-2022".

  8. use input method to get marks of "math" and keep inside variable "math_marks".

  9. use input method to get marks of "computer" and keep inside variable "comp_marks".

  10. use input method to get marks of "english" and keep inside variable "eng_marks".

  11. calculate average marks of student of 2nd week and keep this average in a variable named "avg".

  12. display the average marks of 2nd week

  13. display the following message "please enter the marks of tests Math, computer, and english conducted in the 2rd week of Aug-2022".

  14. use input method to get marks of "math" and keep inside variable "math_marks".

  15. use input method to get marks of "computer" and keep inside variable "comp_marks".

  16. use input method to get marks of "english" and keep inside variable "eng_marks".

  17. calculate average marks of student of 3rd week and keep this average in a variable named "avg".

  18. display the average marks of 3rd week


print("please enter the marks of tests Math, computer, and english conducted in the 1st week of Aug-2022") math_marks = int(input("Please enter the math marks : "))

comp_marks = int(input("Please enter the computer marks : ")) eng_marks = int(input("Please enter the english marks : ")) avg = (math_marks + comp_marks + eng_marks)/3

print("your avg marks of week-1 is : ", avg)


print("please enter the marks of tests Math, computer, and english conducted in the 2nd week of Aug-2022") math_marks = int(input("Please enter the math marks : "))

comp_marks = int(input("Please enter the computer marks : ")) eng_marks = int(input("Please enter the english marks : ")) avg = (math_marks + comp_marks + eng_marks)/3

print("your avg marks of week-2 is : ", avg)


print("please enter the marks of tests Math, computer, and english conducted in the 3rd week of Aug-2022") math_marks = int(input("Please enter the math marks : "))

comp_marks = int(input("Please enter the computer marks : ")) eng_marks = int(input("Please enter the english marks : ")) avg = (math_marks + comp_marks + eng_marks)/3

print("your avg marks of week-3 is : ", avg)


please enter the marks of tests Math, computer, and english conducted in the 1st week of Aug-2022 Please enter the math marks : 30

Please enter the computer marks : 30 Please enter the english marks : 30 your avg marks of week-1 is : 30.0

please enter the marks of tests Math, computer, and english conducted in the 2nd week of Aug-2022 Please enter the math marks : 33

Please enter the computer marks : 33 Please enter the english marks : 3 your avg marks of week-2 is : 23.0

please enter the marks of tests Math, computer, and english conducted in the 3rd week of Aug-2022 Please enter the math marks : 22

Please enter the computer marks : 22 Please enter the english marks : 22 your avg marks of week-3 is : 22.0


function in Python


In Python, a function is a group of related statements that performs a specific task.

Syntax


def function_name(parameters): statement(s)



Create a function named greet that 'print' "Hello, How are you" when it is called


# creating function def greet():

print("Hello, How are you")

# calling a function greet()


Hello, How are you


Create a function named greet that 'return' string "Hello, How are you" when it is called


# creating function def greet():

s = "Hello, How are you" return s


# calling a function my_string = greet() print(my_string)


Hello, How are you


Create a function named sum that return the sum of 7 and 13 when it is called


# creating function def sum():

sum = 7 + 13 return sum


# calling a function my_sum = sum() print(my_sum)


20


Create a function named sum that take two arguments then return the sum when it is called


# creating function def sum(a,b):

sum = a + b return sum


# calling a function my_sum = sum(3,7) print(my_sum)


10


Create a function named even_check that return the True if number is even otherwise returns False.

also create a function named even_filter that takes a list as an argument, filter out even numbers and then returns a new list containing all even numbers


# defining a function that will check that a no. is even or not def even(number):

if number % 2 == 0: return True

else:

return False


# defining even_filter function def even_filter(input_list):

filterd_list = []

for number in input_list: result = even(number) if result == True:

filterd_list.append(number) else:

pass

return filterd_list

input_list = [1,2,3,4,5,6,7,8,9,10]


# calling function

even_number_list = even_filter(input_list) print(even_number_list)

[2, 4, 6, 8, 10]


Function's Arguments and Keyword Arguments



Create a function named Sum that take two numbers as argument and return their sum when it is called


Create a function named profile that take two keyword arguments name and age then return the string "hello {name}, your age is {age}." when it is called


# creating function


def profile(name=None, age=None): if name != None and age != None:

s = "hello, {name}, your age is {age}".format(name=name, age=age) return s

else:

return "Some thing went wrong!"


# calling a function


result = profile("khurram", 38) print(result)


hello, khurram, your age is 38


Create a function named Profile that takes first_name and last_name as keyword arguments and return a string "Hello, your First Name is

{first_name} and Last Name is {last_name}"


Object Oriented Programming (OOP)



class

In object-oriented programming, a class is a blueprint for creating objects

Syntax


class ClassName: all methods



Below we have class named Factory contains a method that produces a tyre for a car of radius 12units and thickness 20units


class Factory: def tyer(self):

return "please take your tyre with radius 12units and thickness 20units for your car and you have to pay Rs.2400/- for this


object or instance

In object-oriented programming, an object or instance is some thing that will intract with the class methods


Bmw = Factory() Bmw.tyer()


'please take your tyre with radius 12units and thickness 20units for your car and you have to pay Rs 2400/- for this'


print(type(Bmw))


<class ' main .Factory'>


Honda = Factory() Honda.tyer()


'please take your tyre with radius 12units and thickness 20units for your car and you have to pay Rs 2400/- for this'


print(type(Honda))


<class ' main .Factory'>


Now suppose objects donot want same or fixed configuration of tyre, they want their own customization for radius and thickness


class Factory:

def   init (self, radius, thickness): # Below are instance variables self.rad = radius

self.thick = thickness


def tyer(self):

return "please take your tyre with radius {}units and thickness {}units for your car \ and you have to pay Rs.2400/- for this".format(self.rad, self.thick)


Bmw = Factory(25, 55) Bmw.tyer()


'please take your tyre with radius 25units and thickness 55units for your car and you have to pay Rs 2400/- for this'


Honda = Factory(19, 23) Honda.tyer()


'please take your tyre with radius 19units and thickness 23units for your car and you have to pay Rs 2400/- for this'

As you see above for both configurations of tyres Factory is charging same price Rs.2400/- but it should be differnt for different customizations of tyres


class Factory:

rate = 10 # This is class variable

def   init (self, radius, thickness): # Below are instance variables self.rad = radius

self.thick = thickness


def tyer(self):

return "please take your tyre with radius {}units and thickness {}units for your car \

and you have to pay Rs.{}/- for this".format(self.rad, self.thick, self.rad * self.thick * self.rate)


Bmw = Factory(25, 55) Bmw.tyer()


'please take your tyre with radius 25units and thickness 55units for your car and you have to pay Rs 13750/- for this'


Honda = Factory(19, 23) Honda.tyer()


'please take your tyre with radius 19units and thickness 23units for your car and you have to pay Rs 4370/- for this'


Inheritance



Single Level Inheritance


class A:

def method1(self):

print("i am method-1 from class A")


def method2(self):

print("i am method-2 from class A") class B(A):

def method3(self):

print("i am method-3 from class B")


def method4(self):

print("i am method-4 from class B")


obj = B() obj.method1() obj.method3()


i am method-1 from class A i am method-3 from class B


Multi Level Inheritance


class A:


def method1(self):

print("i am method-1 from class A")


def method2(self):

print("i am method-2 from class A") class B(A):

def method3(self):

print("i am method-3 from class B")


def method4(self):

print("i am method-4 from class B") class C(B):

def method5(self):

print("i am method-5 from class C")


def method6(self):

print("i am method-6 from class C")


obj = C() obj.method1() obj.method3() obj.method5()


i am method-1 from class A i am method-3 from class B i am method-5 from class C


Multiple Inheritance


class A:


def method1(self):

print("i am method-1 from class A")


def method2(self):

print("i am method-2 from class A") class B:

def method3(self):

print("i am method-3 from class B")


def method4(self):

print("i am method-4 from class B")


class C(A,B):


def method5(self):

print("i am method-5 from class C")


def method6(self):

print("i am method-6 from class C")


obj = C() obj.method1() obj.method3() obj.method5()


i am method-1 from class A i am method-3 from class B i am method-5 from class C


obj = B() obj.method1()


-

AttributeError Traceback (most recent call last)

<ipython-input-79-ad51025c4d2b> in <module>

1 obj = B()

----> 2 obj.method1()


AttributeError: 'B' object has no attribute 'method1'


Files


Python uses file objects to interact with the external files on your computer. These file objects cab be of any file format on your computer i.e. can be an audio file, a text file, emails, Excel documents, etc. Note that You will probably need to install certain libraries or modules to interact with those various file types, but they are easily available. (We will cover downloading modules later on in the course).

Python has a built-in open function that allows us to open and play with basic file types. First we will need a file though. We're going to use some iPython magic to create a text file!

iPython Writing a File



%%writefile test21.txt

Hello, this is a quick test file hjgtyudfyffhgghghhfch Writing test21.txt


pwd()


'/content'


Python Opening a file


We can open a file with the open() function. This function also takes in arguments (also called parameters). Let's see how this is used:


# Open the text.txt we made earlier my_file = open('test21.txt')


# We can now read the file my_file.read()


'Hello, this is a quick test file hjgtyudfyffhgghghhfch\n'


# But what happens if we try to read it again? my_file.read()


''


This happens because you can imagine the reading "cursor" is at the end of the file after having read it. So there is nothing left to read. We can reset the "cursor" like this:


# Seek to the start of file (index 0) my_file.seek(10)


10


# Now read again my_file.read()


's is a quick test file hjgtyudfyffhgghghhfch\n'


In order to not have to reset every time, we can also use the readlines method. Use caution with large files, since everything will be held in memory. We will learn how to iterate over large files later in the course.


# Seek to the start of file (index 0) my_file.seek(0)


0


# Readlines returns a list of the lines in the file. my_file.readlines()


['Hello, this is a quick test file hjgtyudfyffhgghghhfch\n']


Writing to a File


By default, using the open() function will only allow us to read the file, we need to pass the argument 'w' to write over the file. For example:


# Add the second argument to the function, 'w' which stands for write my_file = open('test.txt','w+')


# Write to the file my_file.write('This is a new line')


18


# Seek to the start of file (index 0) my_file.seek(0)


0


# Read the file my_file.read()


'This is a new line'


Iterating through a File