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

Code With Harry

The document discusses modules and pip in Python. Modules allow reuse of code written by others to enhance program quality and save time. Pip is a package manager that can install external modules. To install a module, use the pip command in the terminal followed by the module name. Imported modules can then be used in Python programs. There are built-in and external modules. Built-in modules come pre-installed while external modules must be downloaded using pip before use.

Uploaded by

jinesh pande
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
201 views

Code With Harry

The document discusses modules and pip in Python. Modules allow reuse of code written by others to enhance program quality and save time. Pip is a package manager that can install external modules. To install a module, use the pip command in the terminal followed by the module name. Imported modules can then be used in Python programs. There are built-in and external modules. Built-in modules come pre-installed while external modules must be downloaded using pip before use.

Uploaded by

jinesh pande
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Using Modules & Pip In Python

Sometimes we have to use someone else's code in our program because it saves us a lot of time.
Today, we will learn a technique to use code that is not written by us but will enhance the
quality of our program, save us time and energy, and of course, it is legal and free.
Let us understand what utilities like modules and pip are,
Module – Module or library is a file that contains definitions of several functions, classes,
variables, etc., which is written by someone else for us to use.
Pip – Pip is a package manager for Python, i.e., pip command can be used to download any
external module in Python. It is something that helps us to get code written by someone else.
We can install a module in our system by using the pip command :

 Open cmd or Powershell in your system.


 And then, type pip install module_name and press enter.
 Once you do that, the module will start downloading and will install automatically on
your computer.

For example, for installing flask, I will do this:

After pressing the enter key, you will see something like this:
After installing any module in Python, you can import it into your Python program. For
example, I will type "import flask" at the top of my Python program to use the flask.

import flask

Copy
There are two types of modules in Python:
 Built-in Modules:
Built-in modules are pre-installed in Python, i.e., there is no need to download them. These
modules come with the python interpreter itself. For example– random, os, etc.
To get a complete list of built-in modules of python, head over to the following page of the
official documentation - https://docs.python.org/3/py-modindex.html.
 External Modules:
These are the modules that are not pre-installed in Python, i.e., we need to download them
before using them in our program. For example:– Flask, Pandas, TensorFlow, etc.

Writing Our First Python Program


Today we will be writing our first program in Python Language. I know you have been waiting
for a long to do this.
Let's get to business and start writing our first python program. Follow the below steps:

1. Open Pycharm and create a new file in it.


2. Keep in mind the file name should not match any module name.
3. After creating a new file, type:

print("Hello World")

Copy

4. Now run your program.


5. You will get the output as "Hello World" in your terminal.

So, this is our first python program, and in this program, we just used the print function. In this
function, whatever we pass in parenthesis () in a double quote or single quote gets printed (as it
is) in the terminal.
Make sure you have written and executed the below code to get a feel of what it looks like!

print("Hello world! I am learning Python from CodeWithHarry YouTube


channel!")

Copy
So, that's all in this tutorial. See you in the next one, where we will see how to use python as a
calculator! 

Using Python As A Calculator


First of all, I would like to tell you one thing - the main motive of using Python is not to do raw
calculations. You will perhaps never use python to calculate 3+8 or 34*232, for that matter.
Yeah, that’s true! Python is not just limited to do calculations. It has a vast number of uses and
has many merits or advantages. Using Python, you can do most of the things, such as creating
games, apps, software, websites, etc. 

 To do calculations in Python, open Windows PowerShell (or terminal of your choice


if you are on Linux or Mac) and type "python" to open the Python interpreter. You
will see a screen like this:

 Then simply type or put whatever mathematical calculation you want to do. 5+9, 6-9
choice is all yours!
When you type python, you are inside an interactive python shell where you can type anything,
and the value is displayed on the screen after the computation. That's how you can use python as
a calculator.

And that’s how you can easily do any type of mathematical calculation in Python. I hope you
are enjoying this series of videos :)
This tutorial ends here, and in the next tutorial, we learn the concept of comments and escape
sequences. Till then, keep coding and keep learning.
Comments, Escape Sequences & Print
Statement
Comments are used to write something which the programmer does not want to execute.
Comments can be written to mark the author's name, date when the program is written, adding
notes for your future self, etc.

 Comments are used to make the code more understandable for the programmer.
 The Interpreter does not execute comments.

There are two types of comments in Python Language -:

 Single Line Comment


 Multi-Line Comment

Single Line Comment: Single Line comments are the comments which are written in a single
line, i.e., they occupy the space of a single line.

 We use # (hash/pound to write single-line comments).


 E.g., the below program depicts the usage of comments.

import os
#This is a comment
print("Main code started")

#Now I will write my code here:


print(os.listdir())

Copy

Multi-Line Comment: Multi-Line comments are the comments which are created by using
multiple lines, i.e., they occupy more than one line in a program.

 We use ' ' '….. Comment ….' ' ' for writing multi-line comments in Python (Use lines
enclosed with three quotes for writing multi-line comments). An example of a multi-line
comment is shown below:

import os
'''This is a comment
Author: Harry
Date: 27 November 2020
Multi-line comment ends here
'''
print("Main code started")

#Now I will write my code here:


print(os.listdir())

Copy

Python Print() Statement:


print() is a function in Python that allows us to display whatever is written inside it. In case an
operation is supplied to print, the value of the expression after the evaluation is printed in the
terminal. For example,

# print statement for printing strings


print("Harry is a programmer")

# Print statement with a literal


print(1+87)

#This will print "Harry is a programmer" and 88 on the screen


respectively!

Copy

end: end argument allows us to put something at the end of the line after it is printed. In simple
words, it allows us to continue the line with " " or ',' or anything we want to put inside these
quotes of the end.
It simply joins two different print statements using some string or even by space. Example:

# print statement for printing strings


print("Harry is a programmer", end="**")
# Print statement with a literal
print(1+87)

#This will print "Harry is a programmer**88" on the screen

Copy

Escape Sequences :

 An Escape Sequence character in Python is a sequence of characters that represents a single


character.
 It doesn't represent itself when used inside string literal or character.
 It is composed of two or more characters starting with backslash \ but acts as a single
character. Example \n depicts a new line character.

Some more examples of escape sequence characters are shown below:


Commonly Used Escape Sequences:
Escape
Sequence Description 
s

\n  Inserts a new line in the text at the point

\\ Inserts a backslash character in the text at the point

\" Inserts a double quote character in the text at that po

\' Inserts a single quote character in the text at that poin

\t Inserts a tab in the text at that point

\f Inserts a form feed ln the text at that point

\r Inserts a carriage return in the text at that point

\b Inserts a backspace in the text at that point

 
Code file as described in the video
#Please dont remove this line
"""
This is a
Multiline Comment
"""
"""
This is a comment
"""
# print("Subscribe CodeWithHarry now","Bhai video bhi like kar dena")
# print("next line")
# print("C:\'narry")
print("Harry is \n good boy \t1") #comment after statement
Variables, Datatypes and Typecasting
Variable:
A variable is a name given to any storage area or memory location in a program.
In simple words, we can say that a variable is a container that contains some information, and
whenever we need that information, we use the name of that container to access it. Let's create a
variable:

a = 34 # Variable storing an integer


b = 23.2 # Variable storing real number

Copy

Here a and b are variables, and we can use a to access 34 and b  to access 23.2. We can also
overwrite the values in a and b
Data Types in Python:
Primarily there are the following data types in Python.

1. Integers (<class 'int'>): Used to store integers


2. Floating point numbers (<class 'float'>): Used to store decimal or floating-point numbers
3. Strings (<class 'str'>): Used to store strings
4. Booleans (<class 'bool'>): Used to store True/False type values
5. None: None is literal to describe 'Nothing' in Python 

Rules for defining a variable in Python:

 A variable name can contain alphabets, digits, and underscores (_). For E.g. : demo_xyz =
‘It’s a string variable’
 A variable name can only start with an alphabet and underscore.
 It can't start with a digit. For example, 5harry  is illegal and not allowed.
 No white space is allowed to be used inside a variable name.
 Also, reserved keywords are not recommended to be used as variable names.

Examples of few valid variable names are harry, _demo, de_mo, etc.


Python is a fantastic language that automatically identifies the type of data for us. It means we
need to put some data in a variable, and Python automatically understands the kind of data a
variable is holding. Cool, isn't it?
Have a look at the code below:
# Variable in Python:
abc = "It's a string variable"
_abcnum = 40 # It is an example of int variable
abc123 = 55.854 # It is an example of float variable
print(_abcnum + abc123) # This will give sum of 40 + 55.854

Copy

type() Function in Python: type() function is a function that allows a user to find data type of
any variable. It returns the data type of any data contained in the variable passed to it.
Have a look at the code below, which depicts the use of type function:

# type() Function in Python:


harry = "40"
demo = 55.5
demo = 40
print (type(harry)) #It will give output as string type
demo3 = type(demo) #It will return data type as float
print(demo3) #It will print that data type
print(type(demo2)) #It will give output as int type

Copy

Note – We can't do numbers with strings arithmetic operations, i.e., we can't add a string to any
number. Have a look at the example below:

var1 = "It's a String"


var2 = 5
print(var1+var2) ''' It will give an error as we can't add string to
any number. '''

Copy

Note – We can add (concatenate) two or more strings, and the strings will be concatenated to
return another string. Here is the example showing that:

var1 = "My Name is "


var2 = "Harry"
var3 = var1+var2+" & I am a Good Boy."
print(var1+var2) # It will give output 'My Name is Harry'
print(var3)

Copy

Typecasting :
Typecasting is the way to change one data type of any data or variable to another datatype, i.e.,
it changes the data type of any variable to some other data type.
I know it's a bit confusing but let me tell you in a simple manner. Suppose there is a string "34"
Note: String is not integer since it is enclosed in double-quotes) and as we know, we can't add
this to an integer number, let's say 6. But to do so, we can typecast this string to int data type,
and then we can add 34+6 to get the output as 40. Have a look at the program below:

# Typecasting in Python :
abc = 5
abc2 = '45'
abc3 = 55.95
xyz = 5.0

abc4=int(abc2)

print(abc+abc4) # Output : 50
print(abc+int(abc2)) # Output : 50

print(float(abc)+xyz) # It will add 5.0 + 5.0 and will return 10.0

print(str(abc)+45) # It will give an error as abc has been changed


into string.

Copy

There are many functions to convert one data type into another type :
str() – this function allows us to convert some other data type into a string.
int() – this function allows us to convert some other data type into an integer. For example,
str("34") returns 34 which is of type integer (int)
float() – this function allows us to convert some other data type into a floating-point number,
i.e., a number with decimals.
input() Function – This function allows the user to receive input from the keyboard into the
program as a string.
input() function always takes input as a string, i.e., if we ask the user to take a number as input,
even then, it will take it as a string, and we will have to typecast it into another data type as per
the use case.
If you enter 45 when the input() is called, you will get "45" as a string

# Input Function in Python:


print("Enter your name : ")
name = input() #It will take input from user
print(Your Name is",name) # It will show the name
xyz = input(Enter your age : ")
print("Your age is ",xyz)

Copy

Quick Quiz: Create a program that takes two numbers as input from the user and then prints the
sum of these numbers.
Solution :

# Quiz :
print("Enter First Number : ")
num1= input()
print("Enter Second Number : ")
num2=input()
print("The Sum is",num2) #It will give output as sum of two numbers.

Copy

 
Code file as described in the video
var1 = "54"
var4 = "32"
var2 = 4
var3 = 36.7
# print(100 * str(int(var1) + int(var4)) )
# print(100 * "Hello world\n")
# print("Enter your number")
# inpnum = input()
#
# print("You entered", int(inpnum)+10)
"""
str()
int()
float()
"""

"""
Quiz - Solved in the video
Exercise - Next video
Project - Some awesome python utility
"""
# print(type(var1))

print("Enter first number")


n1 = input()
print("Enter second number")
n2 = input()
print("Sum of these two numbers is", int(n1) + int(n2))
String Slicing And Other Functions In
Python
The string is a data type in Python. Strings in Python programming language are arrays of
bytes representing a sequence of characters. In simple terms, Strings are the combination or
collection of characters enclosed in quotes. Strings are one of the most used data types in any
programming language because most of the real-world data such as name, address, or any
sequence which contains alphanumeric characters are mostly of type ‘String’.
Primarily, you will find three types of strings in Python :

 Single Quote String – (‘Single Quote String’)


 Double Quote String – (“Double Quote String”)
 Triple Quote String – (‘’’ Triple Quote String ‘’’)

Let us now look into some functions you will use to manipulate or perform operations on
strings.
len() Function : This len() function returns the total no. of characters in a string. E.g., for string
a="abc", len(a) will return three as the output as it is a string variable containing 3 characters
E.g., Consider this string variable x

x = "String Demo"

Copy

This string variable x contains a string containing 11 characters (including spaces). Since the
index in a string starts from 0 to length-1, this string can be looked at as:

Note: The indexes of a string begin from 0 to (length-1) in the forward direction and -1,-2,-3,…,
-length in the backward direction. 
String Slicing :
As we know, the meaning of the word ‘slice’ is ‘a part of.’ I am sure you have sliced paneer
cubes at home!
Just like paneer slice refers to the part of the paneer cube; In Python, the term ‘string slice’
refers to a part of the string, where strings are sliced using a range of indices.
To do string slicing, we just need to put the name of the string followed by [n:m]. It means ‘n’
denotes the index from which slicing should start, and ‘m’ denotes the index at which slicing
should terminate or complete. Let's look into an example!

 
In Python, string slicing s[n:m] for a string s is done as characters of s from n to m-1. It means
characters are taken from the first index to the second index-1.
E.g., abc="Demo" then abc[0:3] will give ‘Dem’ and will not give ‘Demo’ coz index number of
‘D’ is 0, ‘e’ is 1, ‘m’ is 2, and ‘o’ is 3. So it will give a range from n to m-1, i.e., 0 to 3-1=2.
That’s why we got the output ‘Dem’.

In string slicing, we sometimes need to give a skip value i.e. string[n:m:skip_value]. This
simply takes every skip_value th character. By default, the skip value is 1 but if we want to
choose alternate characters of a string then we can give it as 2. Have a look at the example
below:
Let's end this tutorial by looking into some of the most used string functions :
 string.endswith(): This function allows the user to check whether a given string ends
with a passed argument or not. It returns True or False.
 string.count(): This function counts the total no. of occurrences of any character in
the string. It takes the character whose occurrence you want to find as an argument.
 string.capitalize(): This function capitalizes the first character of any string. It
doesn’t take any argument.
 string.upper(): It returns the copy of the string converted to the uppercase.
 string.lower(): It returns the copy of the string converted to lower case.
 string.find(): This function finds any given character or word in the entire string. It
returns the index of the first character from that word.
 string.replace(“old_word”, “new_word”): This function replaces the old word or
character with a new word or character from the entire string.

 # String Functions:

 demo = "Aakash is a good boy"


 print(demo.endswith("boy"))
 print(demo.count('o'))
 print(demo.capitalize())
 print(demo.upper())
 print(demo.lower())
 print(demo.find("is")
 print(demo.find("good","nice"))

Copy

I hope you enjoyed this tutorial. If you have any questions, make sure to post them in the
QnA. Let us now move into the next topic, Lists, which is also one of the most used data
types in the python programming language.

Code file as described in the video


mystr = "Harry is a good boy"
# print(len(mystr))
# print(mystr[::-2])

print(mystr.endswith("bdoy"))
print(mystr.count("o"))
print(mystr.capitalize())
print(mystr.replace("is", "are"))
Python Lists And List Functions
Python lists are containers used to store a list of values of any data type. In simple words, we
can say that a list is a collection of elements from any data type. E.g.

list1 = ['harry', 'ram', 'Aakash', 'shyam', 5, 4.85]

Copy

The above list contains strings, an integer, and even an element of type float. A list can contain
any kind of data, i.e., it’s not mandatory to form a list of only one data type. The list can contain
any kind of data in it.
Do you remember we saw indexing in strings? List elements can also be accessed by using
Indices, i.e., the first element of the list has 0 index and the second element has one as its index,
and so on.
Note: If you put an index that isn’t in the list, you will get an error. i.e., if a list named list1
contains four elements, list1[4] will throw an error because the list index starts from 0 and goes
up to (index-1) or 3.
Have a look at the examples below:

Lists in Python

[] # list with no member,


empty list
[1, 2, 3] # list of integers
[1, 2.5, 3.7, 9] # list of numbers (integers
and floating point)
['a', 'b', 'c'] # lisst of characters
['a', 1, 'b', 3.5, 'zero'] # list of mixed value types
['One', 'Two', 'Three'] # list of strings

Copy

List Methods :
Here is the list of list methods in Python. These methods can be used in any python list to
produce the desired output.

# List Methods :
l1=[1,8,4,3,15,20,25,89,65] #l1 is a list
print(l1)

l1.sort()
print(l1) #l1 after sorting
l1.reverse()
print(l1) #l1 after reversing all elements

Copy

List Slicing :
List slices, like string slices, return a part of a list extracted out of it. Let me explain; you can
use indices to get elements and create list slices as per the following format :

seq = list1[start_index:stop_index]

Copy

Just like we saw in strings, slicing will go from a start index to stop_index-1. The seq list, a slice
of list1, contains elements from the specified start_index to specified (stop_index – 1).

List Methods:
There are a lot of list methods that make our life easy while using lists in python. Let's have a
look at a few of them below:
# List Methods :-
list1=[1,2,3,6,,5,4] #list1 is a list

list1.append(7) # This will add 7 in the last of list


list1.insert(3,8) # This will add 8 at 3 index in list
list1.remove(1) #This will remove 1 from the list
list1.pop(2) #This will delete and return index 2 value.

Copy

Tuples in Python:
A tuple is an immutable data type in Python. A tuple in python is a collection of elements
enclosed in () (parentheses). Tuple, once defined, can’t be changed, i.e., its elements or values
can’t be altered or manipulated.

# Tuples in Python :
a=() # It's an example of empty tuple
x=(1,) # Tuple with single value i.e. 1
tup1 = (1,2,3,4,5)
tup1 = ('harry', 5, 'demo', 5.8)

Copy

Note: To create a tuple of one element, it is necessary to put a comma  ‘,’ after that one element
like this tup=(1,) because if we have only 1 element inside the parenthesis, the python
interpreter will interpret it as a single entity which is why it’s important to use a ‘,’ after the
element while creating tuples of a single element.
Swapping of two numbers
Python provides a very handy way of swapping two numbers like below:

# Swapping of two numbers :


a = 10
b = 15
print(a,b) #It will give output as: 10 15
a,b = b,a
print(a,b) #It will give output as: 15 10

Copy

Code file as described in the video


grocery = ["Harpic", "vim bar", "deodrant", "Bhindi",
"Lollypop", 56]
# print(grocery[5])
numbers = [2, 7, 9, 11, 3]
# numbers.remove(9)
# numbers.pop()
# numbers.sort()
# numbers = []
# numbers.reverse()
# numbers.append(1)
# numbers.append(72)
# numbers.append(5)
# numbers.insert(2, 67)
# print(numbers)
# 3, 11, 9, 7, 2
# print(numbers)
# numbers[1] = 98
# print(numbers)
# Mutable - can change
# Immutable - cannot change
# tp = (1,)
# print(tp)
a= 1
b = 8
a, b = b,a
# temp = a
# a = b
# b = temp
print(a, b)
Dictionary & Its Functions Explained
Before going through the actual content, i.e., the implementation of a dictionary, it is essential to
know some fundamental theories so that we can understand what we are going to learn and why
we are spending our precious time learning it.
Let's start with the basic definition of a Python Dictionary:
“Python dictionary is an unordered collection of items. Each item of the dictionary has a key
and value pair/ key-value pair.”
Now coming to the more formal approach:
Every programming language has its distinct features, commonly known as its key features.
With that said, Python’s one out-of-the-box feature is “dictionaries”. Dictionaries may look very
similar to a “List”. Still, dictionaries have some distinct features that do not hold true for other
data types like lists, and those features make it (python dictionary) special.
Here are a few important features of a python dictionary:

 It is unordered (no sequence is required - data or entries have no order)


 It is mutable (values can be changed even after its formation, or new data/information can be
added to the already existing dictionary, we can also pop/remove an entry completely)
 It is indexed (Dictionary contains key-value pairs, and indexing is done with keys. Also, after
the Python 3.7th update, the compiler stores the entries in the order they are created)
 No duplication of data (each key is unique; no two keys can have the same name, so there is
no chance for a data being overridden)

If we talk a little about how it works, its syntax comprises of key and values separated by colons
in curly brackets, where the key is used as a keyword, as we see in real life dictionaries, and the
values are like the explanation of the key or what the key holds (the value). And for the
successful retrieval of the data, we must know the key so that we can access its value, just like
in a regular oxford dictionary where if we don't know the word or its spelling, we cannot obtain
its definition. Let's look into the syntax of a Python dictionary:

a = {'key', 'value', 'cow':'mooh'}


print(a['cow'])
#will print "mooh" on the screen

Copy

With the help of dictionaries, we do not have to do most of our work manually through code like
in C or C++. I mean that Python provides us with a long list of already defined methods for
dictionaries that can help us do our work in a shorter span of time with a minimal amount of
code. Some of these methods are, clear(), copy(), popitem(), etc. The best part about them is that
no extra effort is required to be put in order to learn the functionality as their names explain
their functions (in most of the cases), such as clear() will clear all the data from the dictionary,
making it empty, copy() will make a copy of the dictionary, etc.
Some distinct features that a dictionary provides are:

 We can store heterogeneous data into our dictionary, i.e., numbers, strings, tuples, and the
other objects can be stored in the same dictionary.
 Different data types can be used in a single list, making the value of some keys in the
dictionary.

This was pretty much about dictionaries in Python. You will get further details along with
explanations and implementation in the video tutorial.
I hope you are enjoying it. Do not forget to subscribe to CodeWithHarry.
Code file as described in the video
# Dictionary is nothing but key value pairs
d1 = {}
# print(type(d1))
d2 = {"Harry":"Burger",
"Rohan":"Fish",
"SkillF":"Roti",
"Shubham":{"B":"maggie", "L":"roti", "D":"Chicken"}}
# d2["Ankit"] = "Junk Food"
# d2[420] = "Kebabs"
# print(d2)
# del d2[420]
# print(d2["Shubham"])
# d3 = d2.copy()
# del d3["Harry"]
# d2.update({"Leena":"Toffee"})
# print(d2.keys())
# print(d2.items())

Sets In Python
Let's start with the basic definition of sets in Mathematics. People already familiar with the
concept of sets in mathematics know that as per the mathematical definition - A set is a
collection of well-defined objects and non-repetitive elements that is - a set with 1,2,3,4,3,4,5,2,
2, and 3 as its elements can be written as {1,2,3,4,5}
No repetition of elements is allowed in sets.
In Python programming, sets are more or less the same. Let's look at the Python programming
definition of sets:
“A set is a data structure, having unordered, unique, and unindexed elements.”
Elements in a set are also called entries, and no two entries could be the same within a set.
If your curiosity isn’t satisfied with the basic definition, do not worry, as we are approaching a
more formal illustrative approach to an understanding of python sets.
Well, now that you have a basic idea about sets in mathematics. Let me tell you that a
mathematical set has some basic operations which can be performed on them. For example, the
union of two sets is a set made using all the elements from both sets. The intersection is an
operation that creates a set containing common elements from both sets. A python set has all the
properties and attributes of the mathematical set. The union, intersection, disjoint, etc., all
methods are exactly the same and can be performed on sets in python language.
Note: If you are a programming beginner who doesn't know much about sets in mathematics.
You can simply understand that sets in python are data types containing unique elements. 
If you want to use sets in your python programs, you should know the following  properties of
sets in Python:

 Sets are iterable(iterations can be performed using loops)


 They are mutable (can be updated by adding or removing entries)
 There is no duplication (two same entries do not occur)

Structure:

 Elements of the sets are written in between two curly brackets and are separated with a
comma, and in this simple way, we can create a set in Python.
 The other way of forming a set is by using a built-in set constructor function.

Both of these approaches are defined in the video above.


Let me now share some basic information about sets so that you can know why they are so
important and why you should learn them. 
Unlike the dictionary (that we have learned in tutorials 10 and 11), sets are not just restricted to
Python language, but nearly all commonly used programming languages have sets included in
them as a data type. Examples of these languages include C++, Java, etc., even languages such
as Swift and JavaScript support sets. One of the earliest languages that supported sets was
Pascal. I hope you now have a rough idea of how important these sets actually are because
whichever language you choose to code in, you must have a very basic understanding of sets!
Restrictions:
Everything has a limit to its functionality, and there are some limitations on working with sets
too.
 Once a set is created, you can not change any of its items. Although you can add new items
or remove previous but updating an already existing item is not possible.
 There is no indexing in sets, so accessing an item in order or through a key is not possible,
although we can ask the program if the specific keyword we are looking for is present in the
set by using the “in” keyword or by looping through the set by using a for loop(we will cover
for loops in tutorial # 16 and 17)

Despite these restrictions, sets play a crucial role in the life of a python programmer. In most
cases, these restrictions are never a problem for the programmer, given he knows which data
type to use when. And this skill is something you will learn with time after writing a lot of
python programs
Set Methods:
There are already a lot of built-in methods that you can use for your ease, and they are easily
accessible through the internet. You might want to peep into python's official documentation at
times as well to check for some updates they might push down the line. Some of the methods
you can use with sets include union(), discard(), add(), isdisjoint(), etc., and their functionality
is the same as in the sets in mathematics. Also, the purpose of these functions can easily be
understood by their names.
I hope you now got a basic understanding of Sets and their working. For further explanation and
understanding, watch the video tutorial to grasp the concept altogether. Do not forget to
subscribe on YouTube :)
Code file as described in the video:
s = set()
# print(type(s))
# l = [1, 2, 3, 4]
# s_from_list = set(l)
# print(s_from_list)
# print(type(s_from_list))
s.add(1)
s.add(2)
s.remove(2)
s1 = {4, 6}
print(s.isdisjoint(s1))
f Else & Elif Conditionals In Python
Let's start today's topic of “If else and elif in python”, with a definition:
“If, else and elif statement can be defined as a multiway decision taken by our program due to
the certain conditions in our code.”
For few viewers, the term “elif” is new as they are not familiar with the word, and it is also not
like most of the other words such as list or loops, etc., that have the same meaning in the
English language and in Python programming. In fact, in English, “elif” means honest. But if
you have ever done programming in any language, you must be familiar with the “else-if”
statement; well, “elif” is just that.
We are now coming towards a more formal sort of description. “If and else” are known as
decision-making statements for our program. They are very similar to the decision-making we
apply in our everyday life that depends on certain conditions. The everyday example is
thoroughly explained in the tutorial, so I will not waste your time on that. Instead, I would now
like to focus on more technical details.
Let us focus a little on the working:
Our compiler will execute the if statement to check whether it is true or false now; if it’s true,
the compiler will execute the code in the “if” section of the program and skip the bunch of code
written in “elif” and “else.” But if the “if” condition is false, then the compiler will move
towards the elif section and keep on running the code until it finds a true statement(there could
be multiple elif statements). If this does not happen, then it will execute the code written in the
“else” part of the program.
 An “if” statement is a must because without an if, we cannot apply “else” or “else-if”
statements. On the other hand else or else if statement is not necessary because if we have to
check between only two conditions, we use only “if and else” and even though if we require
code to run only when the statement returns true and do nothing if it returns false then an else
statement is not required at all.  
Now Let’s talk about some technical issues related to the working of decision statements:

 There is no limit to the number of conditions that we could use in our program. We can apply
as many elif statements as we want, but we can only use one “else” and one “if” statement.
 We can use nested if statements, i.e., if statement within an if statement. It is quite helpful in
many cases.
 Decision statements can be written using logical conditions, which are:
 Equal to
 Not equal to
 Less than
 Greater than
 Greater than equal to
 Less than equal to

We can also use Boolean or our custom-made conditions too.


Bonus part:
As we know that an “if” statement is necessary, and you can’t have an “else” or “else-if”
without it, but let’s suppose you have a large amount of code and for some reason, you have to
remove the “if” part of the code (because maybe your code is better without it) but you do not
want to do lots of coding again. Then the solution is just to write pass instead of the code, and
this will help your code run without any error without executing the if part.
So, this was all about if, else, and elif in Python. I hope all the concepts discussed till now are
crystal clear to you. Feel free to ask your queries in the QnA section. I will try my best to clear
your doubts.
Code file as described in the video
# var1 = 6
# var2 = 56
# var3 = int(input())
# if var3>var2:
# print("Greater")
# elif var3==var2:
# print("Equal")
# else:
# print("Lesser")

# list1 = [5, 7, 3]
# print(15 not in list1)
# if 15 not in list1:
# print("No its not in the list")

# Quiz
print("What is your age?")
age = int(input())
if age<18:
print("You cannot drive")

elif age==18:
print("We will think about you")

else:
print("You can drive")

For Loops In Python


Starting with the technical definition of for loops:
Like all the other functions we have seen so far in the video tutorials, for loop is also just a
programming function that iterates a statement or a number of statements based on specific
boundaries under certain defined conditions, which are the loop's basis.
Note that the statement that the loop iterates must be present inside the body of the loop.
Regarding loops, iteration means going through some chunk of code again and again. In
programming, it has the same meaning, the only difference is that the iteration depends upon
certain conditions, and upon its fulfillment, the iteration stops, and the compiler moves forward.
For a beginner or layman, the concept of the loop could be easily understood using an example
of the song's playlist. When we like a song, we set it on repeat, and then it automatically starts
playing again and again. The same concept is used in programming, we set a part of code for
looping, and the same part of the code executes until the certain condition that we provided is
fulfilled. You must be thinking that in the song playlist, the song keeps on playing until we stop
it. The same scenario can be made in the case of loops, and if we put a certain condition that the
loop could not fulfill, then it will continue to iterate endlessly until stopped by force.
An example of where a loop could be helpful to us could be in areas where a lot of data has to
be printed on the screen, and physically writing that many printing statements could be difficult
or, in some cases, impossible. Loops are also helpful in searching data from lists, dictionaries,
and tuples.
Why do we use loops?

 Complex problems can be simplified using loops


 Less amount of code required for our program
 Lesser code so lesser chance or error
 Saves a lot of time
 Can write code that is practically impossible to be written
 Programs that require too many iterations such as searching and sorting algorithms can be
simplified using loops

How to write a for loop?


For loop basically depends upon the elements it has to iterate instead of the statement being true
or false. The latter one is for the While loop, which is the topic for the next tutorial, i.e.,
tutorial# 17. In different programming languages, the way to write a loop is different; in java
and C, it could be a little technical and difficult to grasp for a beginner, but it's simple and easy
in Python. We just have to declare a variable so we can print the output through it during
different iterations and use the keywords “for” and “in”. More explanation could be easily
obtained about working and syntax through the video tutorial.
 Advantages of loops:

 The reusability of code is ensured


 We do not have to repeat the code, again and again; we just have to write it one time
 We can transverse through data structures like list, dictionary, and tuple
 We apply most of the finding algorithms through loops

Example of a for loop:


dict1= {"Best Python Course": "CodeWithHarry",
"Best C Languge Course": "CodeWithHarry",
"Harry Sir":"Tom Cruise Of Programming"
}

for x,y in dict1.items():


print(x, y)

Copy
Output:
Best Python Course: CodeWithHarry
Best C Languge Course: CodeWithHarry
Harry Sir: Tom Cruise Of Programming

Copy

You can see that how I've printed the key-value pairs of the dictionary dict1 using a for loop.
Code file as described in the video
# list1 = [ ["Harry", 1], ["Larry", 2],
# ["Carry", 6], ["Marie", 250]]
# dict1 = dict(list1)
#
# for item in dict1:
# print(item)
# for item, lollypop in dict1.items():
# print(item, "and lolly is ", lollypop)
items = [int, float, "HaERRY", 5,3, 3, 22, 21, 64, 23, 233, 23, 6]

for item in items:


if str(item).isnumeric() and item>=6:
print(item)
While Loops In Python
In the previous tutorial, we discussed about loops in general, what they are and their benefits,
why we should use them, along with syntax, and the working of the “for” loop. If you haven’t
gone through that tutorial till now, I will recommend you to go through that first, so it will be
easier for you to learn the concept of while loop, once you have the concept, what loops
generally are.
Now, as we know now what loops are and why they are used, in this section, I will go directly
towards the working and syntax of while loop along with its comparison with for loop and
where to use it.
“A while loop in python runs a bunch of code or statements again and again until the given
condition is true when the condition becomes false, the loop terminates its repetition.”
The syntax for a while loop is simple and very much like for loop. We have to use the keyword
“while”, along with it, we have to put a condition in parenthesis, and after that, a colon is
placed. The condition could be either true or false. Until the condition is true, the loop will keep
on executing again and again. If we use a certain condition in our while loop that never becomes
false, the program will continue running endlessly until we stop it by force. So, this kind of
mistake in our syntax is known as logical/human error.
To terminate an infinite loop, you can press Ctrl+C on your system.
Syntax of while loop:
while codition_is_true:
Code inside the loop body

Copy

For vs. While:


A “for” statement loop runs until the iteration through, set, lists, tuple, etc., or a generator
function is completed. In the case of a while loop, the statement simply loops until the condition
we have provided becomes false. We generally use for loops for areas where we are already
familiar with the number of iterations and use while loop where the number of iterations are
unknown. Because while the loop is solely based on the state of its condition.
 Let us understand the concept of the while loop and why we use it in areas where the number of
iterations are not defined, or we do not have any idea how many iterations would take place
with the help of an example. Suppose that we have created an application for an ATM from
where a customer can only withdraw money up to 5000 rupees. Now our condition in the while
loop would be to iterate unless the input is between 1 to 5000. So, the condition will be true
unless the user inputs a number between 1 to 5000, so the loop will iterate depending upon the
time until the user submits the wrong input. The example is a bit rough, but I hope it helps you
clear your concepts.
For a While loop to run endlessly, we can pass true or 1 as a condition. 1 is also used in place of
writing true as a whole. So, in this case, the condition will never become false, so the program
will run endlessly. But these kinds of programs do not output anything because they can never
complete their execution.
Break & Continue Statements In Python
“Break and continue statements are used to alter the flow or normal working of a loop, that
could be either a “for loop” or “while loop”.
If you are not familiar with the concept of loops, I recommend you go through Tutorial numbers
16 and 17 of Python Tutorials For Absolute Beginners In Hindi Playlist.
You all know what break and continue mean in the basic English language. Break means
interrupt and continue means resuming after an interrupt as the meanings of the words can
describe that both these functions are totally opposite to each other. Hence, both of these
keywords are mostly defined together, like “if and else” or “try and except,” but unlike the
others, their functionality is quite the opposite of each other. They aren’t even used together in
most of the cases like “except”, could only be used if there is “try” or “else” condition and if
there isn’t “if” statement present, but in cases of “break and continue", they both do not have
any such relation. They may be defined together but not mostly used together.
Defining break statement, break statement alters the normal functionality of the loops by
terminating or exiting the loop containing it. The compiler then moves on to the code that is
placed after the body of the loop. The syntax of break is only a single word, i.e., “break”. A
break statement is relatively easier to understand than a continue statement as it just leaves the
bunch of code written after it inside the loop. The control of the program is then shifted to the
statement written after the loop.
Example Of Break Statement:
i=0;
while(True):
print(f"The value of i is : {i}")
i=i+1
if(i>10):
print("Breaking the loop. ")
break;

Copy
Output:
The value of i is : 0
The value of i is : 1
The value of i is : 2
The value of i is : 3
The value of i is : 4
The value of i is : 5
The value of i is : 6
The value of i is : 7
The value of i is : 8
The value of i is : 9
The value of i is : 10
Breaking the loop.

Copy

Continue statement also alters the flow of a normal working loop, but unlike the break
statement, it takes the compiler to the start of the code that has already been executed before the
statement but is inside the loop boundary. All the code written after the continue statement is
skipped, but it is worth noting that the continue statement works only for a single iteration.
Unless in situations where it's written with decision statements such as if, else, etc., in those
situations, the continue statement will totally be dependent upon the condition of the decision
statement. Its syntax is also plain and easy, like a break statement as you only have to use the
keyword “continue”.
Example Of Continue Statement:
i=0;
while(True):
i=i+1
if(i==5):
continue
if(i>10):
break
print(f"The value of i is : {i}")

Copy
Output:
The value of i is : 1
The value of i is : 2
The value of i is : 3
The value of i is : 4
The value of i is : 6
The value of i is : 7
The value of i is : 8
The value of i is : 9
The value of i is : 10

Copy

Where and when can these statements come in handy:


When you are working with a big project, there might occur a situation where you only need to
use the loop partially without adding new or removing already existing lines of code. You can
easily apply the break statement in your code so that you can partially run it without any sort of
error.
Or in another situation, let's suppose you are working with while loop printing some lines on the
screen and you want to skip an iteration in between others, then you can write the continue
statement using an “if” statement that matches your need so that you can skip the specific
iteration.
Code file as described in the video
while(True):
inp = int(input("Enter a Number\n"))
if inp>100:
print("Congrats you have entered a number greater than 100\n")
break
else:
print("Try again!\n")
continue
Short Hand If Else Notation In Python
Before going through the if-else short-hand statement, we must be familiar with the basic
definition, so that we can know what the short-hand statement actually is. In basic English,
shorthand can be said as “a basic way of writing using abbreviations or symbols”. For example,
we do not use the full name, Kentucky Fried Chicken, instead we use its abbreviation that is
KFC. Writing in such a compact manner is known as shorthand. Now let us move towards the
definition of shorthand with respect to the Python language.
“An executable statement, written in so compact manner that it comprises of only a single line
of code is known as shorthand statement.”
Python supports many sorts of shorthand statements and with the help of these statements, we
can write our code in a more compact sort or form using less space. We learned the original
form of “if and else” statement in tutorial #13 of our playlist, we can also write it in a shorthand
form of code.
If we write the statement:

If-expression if(Condition) else else-expression

Copy

It will be same as:

if condition:
if-expression
else:
else-expression

Copy

Now let us come to the question that why we should use shorthand if-else statement instead of
the original one. First of all, you have to do less typing while using the shorthand form. If you
are making a project that requires thousands of lines of code then, it is very hectic if you are
writing something in four or five lines that could easily be written in a single line. This
advantage would not be too convincing for a lot of viewers now and they would not like to
adopt the shorthand method instead of the one they are using currently. In this case, this tutorial
is still very important for them because if you are a coder then reading other people’s code is a
must. Even though you are clearing your concepts by going through some code on Stack
Overflow or making a group project with other programmers, you will surely encounter
shorthand code at any time, so it is best to have a piece of prior knowledge about it.
 The second advantage of using the shorthand way of programming is that the compiler handles
it in an efficient way. It does not matter for the short program even though if they are a couple
of thousand lines long but when working on a huge project, like Amazon (12 Million lines of
code) or Facebook (62 Million lines of code) or Google (2 Billion lines of code), then it is very
important to save as many lines of code as we can by writing it in a compact form.
There is also a disadvantage of using shorthand, that it is not easily readable. When we are
working on a group project, we always try to choose the approach that is the easiest to
understand, and writing a compact code always bring difficulties when we share our code with
someone. Even though whichever approach we follow, we should always have knowledge about
all possible approaches, because everyone is not using the same approach.
Code file as described in the video
a = int(input("enter a\n"))
b = int(input("enter b\n"))

# if a>b: print("A B se bada hai bhai")


print("B A se bada hai bhai") if a

Functions And Docstrings


 “Functions in Python can be defined as lines of codes that are built to create a specific task and
can be used again and again in a program when called.”
There are two types of functions in the Python language:
 Built-in functions
 User-defined functions

We have used a lot of built-in functions in our code till now, these functions include print(), or
sum(), etc. So, we have a good idea about how to call a function. Built-in functions are already
present in our python program, and we just have to call them whenever we need them to
execute. Being familiar with built-in functions we will now look into User-defined function
mostly in this tutorial.
We must know how to define a function in Python. In order to create one ourselves, we have to
use the def keyword in order to define a function accompanied by the function's name with a
pair of parentheses. The function of parenthesis is to send arguments or parameters to a
function. In simple words, parameters can be defined as values that are sent in the parenthesis.
For example, if a function is used to add two numbers then both the numbers will be passed as
parameters in the parenthesis. After parenthesis, a colon is used to get in the body of the
function. Some functions may return a value to the caller, so in order to get the value, a return
statement is put at the end of the body of the function that gives the value that has been
calculated by the function.
Calling a function is very simple, we just have to write the name of the function along with the
closing parenthesis. If the function requires some arguments then we write those in the
parenthesis, but if it does not return anything, then we leave them empty.
We have discussed a lot about what functions are and how to use them, now let us move to the
advantages of using a function:

 If we are working on a big project then we will prefer to make as many functions as possible,
so every other member of our team could use that.
 By using functions, we can avoid the repetition of code to an extent. As we have discussed in
the previous tutorial i.e. Tutorial #22, more lines of code mean less efficiency. Also repeating
the same code at different places will just make the code more crowded than required.
 The reusability of code is ensured by using functions. We can even use a function inside
another function or in any part of our code.
 By making a function of code that we are going to use again and again, we can save a lot of
time.

Docstrings
Docstring is a short form of documentation string. Its purpose is to give the programmer a brief
knowledge about the functionality of the function. It must be the first string in a function, and it
is also an optional string but always good to have it while working on programs having multiple
functions. The syntax for writing a docstring is very simple as it is just a string written in
between three double quotes placed three times (""" """) on either side of the string. But it has to
be the first line of code in the function’s body. To call a docstring we write the name of the
function followed by ._doc_.
Code file as described in the video
# a = 9
# b = 8
# c = sum((a, b)) # built in function

def function1(a, b):


print("Hello you are in function 1", a+b)

def function2(a, b):


"""This is a function which will calculate average of two numbers
this function doesnt work for three numbers"""
average = (a+b)/2
# print(average)
return average

# v = function2(5, 7)
# print(v)
print(function2.__doc__)
ry Except Exception Handling In Python
Before discussing exceptional handling, let us discuss, what an exception is actually.
“Exception can be said as an error, that causes a program to crash. Unlike syntax error, it is
syntactically correct and occurs mostly due to our negligence”
For example, assigning a string value to an int data type variable or dividing a number by zero
or also when a name of a variable or a function is not found, an exception occurs. Python has
built-in support for dealing with many sorts of exceptions automatically, but we can also define
our own.
The solution to exception related problems is simple. We just have to alter the normal flow of
the program by a bit of code known as an exception handler. This code will save the state of the
program up to the point where the exception occurred and will continue the normal flow from
the code written outside the area of occurrence of an exception. We can also print the exception
by converting it into a string. This way program does not terminate but executes completely
except for the area where the exception occurred.
Now as we have covered the basics, let us move towards an in-depth understanding of exception
handling. Try and except blocks are used in Python to handle the exception. If you are familiar
with any other programming language, the except block is the same as the catch block. In the try
block, we write the code about which we have doubt that exception could occur in it, and in
except block we just write the code that we want to execute in case the exception error occurs.
In such cases where no exception occurs, the except block will not execute. In simple words, in
the try block, we write the code where chances of exception are high, and in except block, we
handle the error, maybe through printing a warning or just skipping the exception part
completely by completely ignoring it as a part of the program.
We can also use an else keyword to print something if no exception occurs. For example. In
case of an exception, the except block is printing the error, likewise, if the exception does not
occur, we could print a statement that no error occurred, using an else keyword.
There are also many sorts of predefines exceptions that we could find in Python such as EOF or
End of File Error (occurs when the end of a file is reached but the operation is not completed) or
ZeroDivisionError (occurs when the number is divided by zero). We can code such expect
blocks that catch only specific sort of exception and ignore the rest. For this purpose, we have to
specify the error name after the keyword except, before putting the colon.
Advantages of using try and catch

 Without a try block if an exception occurs the program will surely crash.
 If we have some part of code that is not much important but can cause an exception, then we
must write it down in the try block so it does not cause the whole program to crash.

Code file as described in the video


print("Enter num 1")
num1 = input()
print("Enter num 2")
num2 = input()
try:
print("The sum of these two numbers is",
int(num1)+int(num2))
except Exception as e:
print(e)

print("This line is very important"


Python File IO Basics
You must have noticed that till now we have been learning one new concept per tutorial. For
some important concepts like loops we had to allocate two tutorials so we can grasp the concept
of both loops (for and while) separately. But now in the case of the file, we have allocated the
next five tutorials (excluding the exercise and their solutions). So, from this, you can take a hint
that how important file handling is in programming.
In this tutorial we are not getting into files in detail, instead, we are discussing the basics of the
file and its modes in a theoretical manner. In computer terms, “a file is a resource for saving
data and information in computer hardware”. A file is stored in the form of bytes in hardware. A
file is opened in the RAM, but it is stored in the hardware because the hardware is non-volatile
i.e. it stores its data permanently. On the other hand, RAM is volatile, it loses its data when the
system is shut down.
Unlike C or C++, file handling in python is relatively easy and simple.  Python treats files
differently as text or binary and this is important. There are two types of files that we normally
encounter in our computer daily. The first one is a text file and the second one is a binary file.
We can understand by the name of the text file that it must contain text in it. The extension for
the text file is .txt. All other forms of files are mostly binary even a .doc file, that we open in
Microsoft Word is a binary file because it requires special software for accessing it.
The second sort of files are binary files. They are almost all the other files that we come in
contact with while using our computer. These files include images, PDFs, Excel files, etc.
Modes of opening file in Python:
There are many modes of opening a file in Python, unlike other languages Python has provided
its users a variety of options. We will discuss seven of them in this tutorial.

 r : r mode opens a file for read-only. We do not have permission to update or change any data
in this mode.
 w : w mode does not concern itself with what is present in the file. It just opens a file for
writing and if there is already some data present in the file, it overwrites it.
 x : x is used to create a new file. It does not work for an already existing file, as in such cases
the operation fails.
 a : a stands for append, which means to add something to the end of the file. It does exactly
the same. It just adds the data we like in write(w) mode but instead of overwriting it just adds
it to the end of the file. It also does not have the permission of reading the file.
 t : t mode is used to open our file in text mode and only proper text files can be opened by it.
It deals with the file data as a string.
 b : b stands for binary and this mode can only open the binary files, that are read in bytes.
The binary files include images, documents, or all other files that require specific software to
be read.
 + : In plus mode, we can read and write a file simultaneously. The mode is mostly used in
cases where we want to update our file.
Open(), Read() & Readline() For Reading
File
As we now have an idea of what files(text or binary) are and their access modes, we are now
ready to dive into the discussion of file handling methods. When we want to read or write a file
(say on our hard drive), we must first open the file. When we open a file, we are asking the
operating system to find the file by name, making sure the file exists.
How to open a file?
Python has a built-in open() function to open a file.
The syntax of the function is:

open("filename" ,"mode")

Copy

To open a file, we must specify two things,

 Name of the file and its extension


 Access mode where we can specify in which mode file has to be opened, it could either be
read (r), write (w) or append(a), etc. For more information regarding access modes, refer to
the previous tutorial.

For Example, 

open("myfile.txt")

Copy

The file “myfile.txt” will open in "rt" mode as it is the default mode. But the best practice is to
follow the syntax to avoid errors.
The open function returns a file object. We store this file object into a variable which is
generally called as a file pointer/file handler. Here is a code snippet to open the file using file
handing in Python,

f=open("myfile.txt," "w")

Copy

You can use this file pointer to further add modifications in the file. An error could also be
raised if the operation fails while opening the file. It could be due to various reasons like trying
to access a file that is already closed or trying to read a file open in write mode.
How to read a file?
To read a file in Python, there are various methods available,

 We can read a whole file line by line using a for loop in combination with an iterator. This
will be a fast and efficient way of reading data.
 When opening a file for reading, Python needs to know exactly how the file should be
opened. Two access modes are available reading (r), and reading in binary mode (rb). They
have to be specified during opening a file with the built-in open() method.

f = open("myfile.txt", "r")

Copy

The read() method reads the whole file by default. We can also use the read(size) method where
you can specify how many characters we want to return i.e.

f.read(2); #Here, you will get the first two characters of the file.

Copy

 You can use the readline() method to read individual lines of a file. By calling readline() a
second time, you will get the next line.
 readlines() method reads until the end the file ends and returns a list of lines of the entire file.
It does not read more than one line.       

f=open("myfile.txt","r");
f.readlines() #Returns a list object

Copy

Note: The default mode to read data is text mode. If you want to read data in binary format, use
''rb".
Is it necessary to close a file?
The answer is yes, it is always the best practice to close a file after you are done performing
operations on it. However, Python runs a garbage collector to clean up the unused objects, but as
good programmers, we must not rely on it to close the file. Python has a build-in close()
function to close a file i.e;

f.close()

Copy
I hope you like this tutorial. Here, we have discussed different file handling in Python with
examples that will help you while working on real-world projects.
Source Code:
f = open("harry.txt", "rt")
print(f.readlines())
# print(f.readline())
# print(f.readline())
# print(f.readline())
# content = f.read()
#
# for line in f:
# print(line, end="")
# print(content)
# content = f.read(34455)
# print("1", content)
#
# content = f.read(34455)
# print("2", content)
f.close()
Python Exercise 3: Solution
Problem Solving Exercise#3:

You have to build a "Number Guessing Game," in which a winning number is set to some
integer value. The Program should take input from the user, and if the entered number is less
than the winning number, a message should display that the number is smaller and vice versa.

Instructions:
1. You are free to use anything we've studied till now.
2. The number of guesses should be limited, i.e (5 or 9).
3. Print the number of guesses left.
4. Print the number of guesses he took to win the game.
5. “Game Over” message should display if the number of guesses becomes equal to 0.
You are advised to participate in solving this problem. This task helps you become a good
problem solver and helps you accept the challenge and acquire new skills.
Have you solved this task? If yes, then it’s time to check your solution. Best of luck.!
Your participation is appreciated. Keep supporting and stay up to date with codewithharry.
Code file as described in the video

# no of guesses 9
# print no of guesses left
# No of guesses he took to finish
# game over

n=18
number_of_guesses=1
print("Number of guesses is limited to only 9 times: ")
while (number_of_guesses<=9):
guess_number = int(input("Guess the number :\n"))
if guess_number<18:
print("you enter less number please input greater number.\n")
elif guess_number>18:
print("you enter greater number please input smaller number.\n
")
else:
print("you won\n")
print(number_of_guesses,"no.of guesses he took to finish.")
break
print(9-number_of_guesses,"no. of guesses left")
number_of_guesses = number_of_guesses + 1

if(number_of_guesses>9):
print("Game Over")
Writing And Appending To A File
We have already discussed how to open and read a file in Python, in the last tutorial. If you
haven’t seen the video, please go and see that one first. Now we will discuss how to write or
insert text to a file and also how we can simultaneously read and write a file. Now, as we know,
there are different modes of opening a file, we will cover three of them in this tutorial.
Note: f is an object for the file. It is not a method or a special character. You will notice me
using f.write() or f.read() or f.close(), in further description or tutorial, but you can use character
or word of your own choice instead.

MODES PURPOSE

Here “w” stands for write. After opening or creating a file, a function, f.write() is
used to insert text into the file. The text is written inside closed parenthesis
“w” surrounded by double quotations. There is a certain limitation to the write mode of
mode: the opening file that it overrides the existing data into the file. For a newly created
  file, it does no harm, but in case of already existing files, the previous data is lost as
f.write() overrides it.  
 

“a” symbolizes append mode here. In English, appends mean adding something at the
end of an already written document, and the same is the function the mode performs
“a” here. Unlike write mode, when we use "a" keyword, it adds more content at the end
mode: of the existing content. The same function i.e., f.write() is used to add text to the file
  in append mode. It is worth noting that append mode will also create a new file if the
file with the same name does not exist and can also be used to write in an empty file.
 

At the beginning of the description, I told you that we would learn reading and
“r+” writing a file simultaneously. Well, r+ mode is more of a combination of reading and
mode: append than read and write. By opening a file in this mode, we can print the existing
  content on to the screen by printing f.read() function and adding or appending text to
it using f.write() function.

 
A very helpful tip for beginners:
If you are writing in append mode, start your text by putting a blank space or newline
character (\n) else the compiler will start the line from the last word or full stop without any
blank space because the curser in case of append mode is placed right after the last character.
So, it is always considered a good practice to adopt certain habits that could help you in the
future, even though they are not much helpful now.
f.close():
f.close() is used to close a file when we are done with it. It is a good practice to close a file after
use because whichever mode you opened it for, the file will be locked in for that specific
purpose and could not be accessed outside the program, even though the file browser.
Code file as described in the video
# f = open("harry.txt", "w")
# a = f.write("Harry bhai bahut achhe hain\n")
# print(a)
# f.close()

# f = open("harry2.txt", "a")
# a = f.write("Harry bhai bahut achhe hain\n")
# print(a)
# f.close()

# Handle read and write both


f = open("harry2.txt", "r+")
print(f.read())
f.write("thank you")
Seek(), tell() & More On Python Files
Python file objects give us many methods and attribute that we can use to analyze a file,
including tools to figure out the name of the file associated with the file object, whether it is
closed or opened, writable, readable and how it handles errors.
We have already discussed the file, its access modes, how to open, close, read, and write files in
the previous tutorials.
Now it is time to pay attention to some of the most useful and important functions used in file
handling.
In today’s tutorial, we are going to study why there is a need for tell() and seek() functions and how we
can use them? 
tell()
When we are working with python files, there are several ways to present the output of a
program, it could be in human-readable form or binary form, or we use read() function with
specified sie to read some data.
What if we want to know the position of the file(read/write) pointer.
For this purpose, we use the tell() function. f.tell() returns an integer giving the file pointer
current position in the file represented as a number of bytes. File Pointer/File Handler is like a
cursor, which defines from where the data has to be read or written in the file. Sometimes it
becomes important for us to know the position of the File Pointer. With the help of tell(), this
task can be performed easily 
Description:

 Syntax:  seek()
 Parameters Required: No parameters are required.
 Return Value:  seek() function returns the current position of the file pointer within the file.

Example:
f = open("myfile.txt", "r")
print(f.readline() )
print(f.tell())

Copy

Here the question arises, what if we want to change the position of the file pointer.
Here the concept of seek() function comes.
seek()
When we open a file, the system points to the beginning of the file. Any read or write will
happen from the start. To change the file object’s position, use seek(offset, whence) function.
The position will compute by adding offset to a reference point, and the whence argument
selects the reference point. It is useful when operating over an open file. If we want to read the
file but skip the first 5 bytes, open the file, use function seek(5) to move to where you want to
start reading, and then continue reading the file.
Description:

 Syntax:  file_pointer .seek(offset, whence).


 Offset:   In seek() function, offset is required. Offset is the position of the read/write pointer
within the file.
 Whence: This is optional. It defines the point of reference. The default is 0, which means
absolute file positioning.

 
Value Meaning
Absolute file positioning. The position is relative to the start of the file.
 0
The first argument cannot be negative.
Seek relative to the current position. The first argument can be negative to
1
move backward or positive to move forward
2 Seek relative to the file’s end. The first argument must be negative.
 
Example:
This code will change the current file position to 5, and print the rest of the line.

f = open("myfile.txt", "r")
f.seek(5)
print( f.readline() )

Copy

 Note: not all file objects are seekable.


 
Code file as described in the video
f = open("harry.txt")
f.seek(11)
print(f.tell())
print(f.readline())
# print(f.tell())
print(f.readline())
# print(f.tell())
f.close()
Using With Block To Open Python Files
There is more than one way to open and close a file. The one we have studied till now is using
the open() and close() function. In today's tutorial, we will go through another yet better and
straightforward approach of opening and closing files. We will see how we can use, with block
to open and close a file, including syntax and benefits. We will be using f as our file’s object.
Opening and closing of files are necessary and crucial steps in file handling. We cannot read,
write, or perform any task on a file without opening it first. Everyone is familiar with it because
it is the first step in file handling. But what most of us are not familiar with is how vital closing
a file is. If we do not close our file after we are done using it, then the file object will keep on
consuming processor memory, and also, there will be more chances of exceptions as the file is
still open hence, more chances of bugs.
To save ourselves from such situations, we could use a with block to open files.
Now how the with block works?
Its syntax is simple:

With open(“file_name.txt”) as f:

Copy

f being the object of the file. The important thing to note is, there is no close()
function required. After running the code in the block, the file will automatically be closed.  
 Now at this level, closing a file does not seem like a big issue, but when we are working on
more significant projects with a higher number of files then there are instances where we tend to
forget that we have closed our file. In such situations, chances of bugs occurrence increase, and
we can not access a file elsewhere until it is closed properly. Also, the program will require
more processing power. So, even if we are not dealing with a more significant project now, still
closing a file is a good practice because, as a programmer, I can tell you that the practices you
adopt now will soon become habits, and they will be difficult to let go.
What opening a file with "With block" actually does is to create a context manager that
automatically closes a file after processing it. Another benefit of using a “With block” is that we
can open multiple files in a single block by separating them using a comma. All the files could
have different modes of opening. For example, we can access one file for reading and another
one for writing purposes. Both files should have different objects referring to them.
The syntax would be:

With open(“file1txt”) as f, open(“file2.txt”) as g

Copy

Both files will be simultaneously closed together.


Let us once again briefly go over the advantages of With block:

 Multiple files can be opened.


 The files that are opened together can have different modes
 Automatically closes file
 Saves processing power by opening and closing file only when running code inside the block
 Creates a context manager, so lesser chances of an exception occurring

Code file as described in the video


with open("harry.txt") as f:
a = f.readlines()
print(a)

# f = open("harry.txt", "rt")
#Question of the day - Yes or No and why?
# f.close()
Scope, Global Variables and Global
Keyword
What is Scope in Python?
Scope refers to the coding area where a particular Python variable is accessible. Hence one
cannot access any particular variable from anywhere from the code. We have studied about
variables in previous lectures. Recall that a variable is a label for a location in memory. It holds
a value. Not all variables are accessible, and not all variables exist for the same amount of time.
Where the variables defined determines that is it accessible or not, and how long it will exist.
Local vs. Global Variables
Local Variable:-
A variable that is declared inside a function or loop is called a local variable. In the case of
functions, when we define a variable within a function, its scope lies within the function only. It
is accessible from the point where it is defined until the end of the function. It will exist for as
long as the function is executing. Local variables cannot be accessed outside the function. The
parameter names in the function, they behave like a local variable.
For Example,
def sum():

a=10 #local variable cannot be accessed outside the function


b=20
sum=a+b
print( sum)

print(a) #this gives an error

Copy

When you try to access variable “a” outside the function, it will give an error. It is accessible
within the function only.
Global Variable:-
On the other hand, a global variable is easier to understand; it is not declared inside the function
and can be accessed anywhere within a program. It can also be defined as a variable defined in
the main body of the program. Any function or loop can access it. Its scope is anywhere within
the program.
For Example,
a=1 #global variable

def print_Number():

a=a+1;
print(a)

print_number()

Copy

This is because we can only access the global variable, but we cannot modify it from inside of
the function.
What if we want to modify the global variable inside the function?
For this purpose, we use the global keyword. In Python, the global keyword allows us to
modify the global variable. It is used to create a global variable and make changes to the
variable in a local scope.
Rules of global keyword:

 If we assigned a value to a variable within the function body, it would be local unless
explicitly declared as global.
 Those variables that are referenced only inside a function are implicitly global.
 There is no need to use the global keyword outside a function.

What if we have a nested function. How does the scope change?


When we define a function inside another function, it becomes a nested function. We already
know how to access a global variable from a function by using a global keyword. When we
declare a local variable in a function, its scope is usually restricted to that function alone. This is
because each function and subfunction stores its variables in its separate workspace.
A nested function also has its own workspace. But it can be accessed to the workspaces of all
functions in which it is nested. A variable whose value is assigned by the primary function can
be read or overwritten by a function nested at any level within the primary.
Code file as described in the video
# l = 10 # Global
#
# def function1(n):
# # l = 5 #Local
# m = 8 #Local
# global l
# l = l + 45
# print(l, m)
# print(n, "I have printed")
#
# function1("This is me")
# # print(m)

x = 89
def harry():
x = 20
def rohan():
global x
x = 88
# print("before calling rohan()", x)
rohan()
print("after calling rohan()", x)

harry()
print(x)
Recursions: Recursive Vs Iterative
Approach
We have worked with iteration in previous lectures, related to loops, while recursion is a new
topic for us. Let's start with the definition:           
"Recursion occurs when a function calls itself."
Mostly both recursion and iteration are used in association with loops, but both are very
different from each other. In both recursion and iteration, the goal is to execute a statement
again and again until a specific condition is fulfilled. An iterative loop ends when it has reached
the end of its sequence; for example, if we are moving through a list, then the loop will stop
executing when it reached the end of the list. But in the case of recursion, the function stops
terminating when a base condition is satisfied. Let us understand both of them in detail.
Recursion:
There are two essential and significant parts of a recursive function. The first one is the base
case, and the second one is the recursive case. In the base case, a conditional statement is
written, which the program executes at the end, just before returning values to the users. In the
recursive case, the formula or logic the function is based upon is written. A recursive function
terminates to get closer to its base case or base condition. As in case of loops, if the condition
does not satisfy the loop could run endlessly, the same is in recursion that if the base case is not
met in the call, the function will repeatedly run, causing the system to crash.
In case of recursion, each recursive call is stored into a stack until it reaches the base condition,
then the stack will one by one return the calls printing a series or sequence of numbers onto the
screen. It is worth noting that stack is a LIFO data structure i.e., last in first out. This means that
the call that is sent into the stack at the end will be executed first, and the first one that was
inserted into the stack will be executed at last.
Iteration:
We have a basic idea about iteration as we have already discussed it in tutorial # 16 and 17
relating loops. Iteration runs a block of code again and again, depending on a user-defined
condition. Many of the functions that recursion performs can also be achieved by using
iterations but not all, and vice versa.
Recursion vs. Iteration:

 Recursion can only be applied to a function, while iteration can be used for any number of
lines of code, we want to repeat
 Lesser coding has to be done in case of recursion than iteration
 Back tracing or reverse engineering in case of recursion can be difficult.
 In the case of recursion, if the condition is not met, the system will repeat a few times and
then crash while in case of iteration it will continue to run endlessly.
 Even though less coding has to be written in case of recursion, it is still slower in execution
because the function has to be called again, and again, storing data into the stack also
increases the time of execution.
In my opinion for smaller programs where there are lesser lines of codes, we should use a
recursive approach and in complex programs, we should go with iteration to reduce the risk of
bugs.
Code file as described in the video
# n! = n * n-1 * n-2 * n-3.......1
# n! = n * (n-1)!
def factorial_iterative(n):
"""
:param n: Integer
:return: n * n-1 * n-2 * n-3.......1
"""
fac = 1
for i in range(n):
fac = fac * (i+1)
return fac

def factorial_recursive(n):
"""
:param n: Integer
:return: n * n-1 * n-2 * n-3.......1
"""
if n ==1:
return 1
else:
return n * factorial_recursive(n-1)
# 5 * factorial_recursive(4)
# 5 * 4 * factorial_recursive(3)
# 5 * 4 * 3 * factorial_recursive(2)
# 5 * 4 * 3 * 2 * factorial_recursive(1)
# 5 * 4 * 3 * 2 * 1 = 120
# 0 1 1 2 3 5 8 13
def fibonacci(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fibonacci(n-1)+ fibonacci(n-2)

number = int(input("Enter then number"))


# print("Factorial Using Iterative Method",
factorial_iterative(number))
# print("Factorial Using Recursive Method",
factorial_recursive(number))
print(fibonacci(number))
nonymous/Lambda Functions In Python
As we have studied function in the previous lecture, we know that if a program has a large piece
of code that is required to be executed repeatedly, then it will be better to implement that piece
of code as a function. Functions improve code reusability, modularity, and integrity.
In this tutorial, we will see how to declare Anonymous functions and how to return values from
them.
As we have studied in the previous lecture, the syntax for function declaration is as follows:

def function_name ():

Copy

What is Anonymous function?


In Python programming, an anonymous function or lambda expression is a function
definition that is not bound to an identifier (def).
The anonymous function is an inline function. The anonymous functions are created using a
lambda operator and cannot contain multiple expressions.
 The following example will show how anonymous functions work: 

result = lambda n1, n2, n3: n1 + n2 + n3;


print ("Sum of three values : ", result( 10, 20, 25 ))

Copy

In the above code, we have created an anonymous function that adds three numbers. The
function is stored in a variable named result. The function can then be called using this variable.
In the above code, the function has been called with three different parameter values for the
function call.
Anonymous functions can accept inputs and return the outputs, just like other functions do.
Why do we use Python Lambda Functions?
The main objective of anonymous functions is that, when we need a function just once,
anonymous functions come in handy. Lambda operator is not only used to create anonymous
functions, but there are many other uses of the lambda expression. We can create anonymous
functions wherever they are needed. Due to this reason, Python Lambda Functions are also
called as throw-away functions which are used along with other predefined functions such
as reduce(), filter(), and map(). 
These functions help reduce the number of lines of the code when compared to named Python
functions.
Significant Differences Between Lambda Expressions And Simple Functions.

1. Can be passed immediately with or without variables.


2. They are inline functions.
3. Automatic return of results.
4. There is neither a document string nor a name.

Python List sort():


Sorting means arranging data systematically. If the data we want to work with is not sorted, we
will face problems finding the desired element.
The Python language, like other programming languages, can sort data.
Python has an in-built method i.e. sort(), which is used to sort the elements of the given list in a
specified ascending or descending order. There is also a built-in function i.e. sorted(), that builds
a new sorted list from an iterable like list, dictionary, etc.
The syntax of the sort() method is:

list.sort(key=myFunc ,reverse=True|False)

Copy

Parameter Values:-

Parameters Values
In the key parameter, we specify a function that is called on each
key
list element before making comparisons. 
This is optional. False will sort the list in ascending order, and true
reverse will sort the list in descending order.
Default is reverse=False.
 
Sort() does not return any value, but it changes from the original list.
 
Code file as described in the video
# Lambda functions or anonymous functions
# def add(a, b):
# return a+b
#
# # minus = lambda x, y: x-y
#
# def minus(x, y):
# return x-y
#
# print(minus(9, 4))

a =[[1, 14], [5, 6], [8,23]]


a.sort(key=lambda x:x[1])
print(a)
Exercise 5: Solution And First Solver
This tutorial contains the solution of Exercise-5 (Health Management System). We used simple
files and some fundamental concepts of Python to accomplish this Exercise. Your answer or
code may vary, but it should give the same output or result, so don't get bothered about it. 
Instructions:

 Create a food log file for each client


 Create an exercise log file for each client.
 Ask the user whether they want to log or retrieve client data.
 Write a function that takes the user input of the client's name. After the client's name is
entered, A message should display "What you want to log. Diet or Exercise"
 Use function

def getdate():
import datetime
return datetime.datetime.now()

Copy

 The purpose of this function is to give time with every record of food or exercise added in the
file.
 Write a function to retrieve exercise or food file records for any client.

Code file as described in the video


# Health Management System
# 3 clients - Harry, Rohan and Hammad

def getdate():
import datetime
return datetime.datetime.now()

# Total 6 files
# write a function that when executed takes as input client name
# One more function to retrieve exercise or food for any client
#bhai ye rha program
import datetime
def gettime():
return datetime.datetime.now()
def take(k):
if k==1:
c=int(input("enter 1 for excersise and 2 for food"))
if(c==1):
value=input("type here\n")
with open("harry-ex.txt","a") as op:
op.write(str([str(gettime())])+": "+value+"\n")
print("successfully written")
elif(c==2):
value = input("type here\n")
with open("harry-food.txt", "a") as op:
op.write(str([str(gettime())]) + ": " + value + "\n")
print("successfully written")
elif(k==2):
c = int(input("enter 1 for excersise and 2 for food"))
if (c == 1):
value = input("type here\n")
with open("rohan-ex.txt", "a") as op:
op.write(str([str(gettime())]) + ": " + value + "\n")
print("successfully written")
elif (c == 2):
value = input("type here\n")
with open("rohan-food.txt", "a") as op:
op.write(str([str(gettime())]) + ": " + value + "\n")
print("successfully written")
elif(k==3):
c = int(input("enter 1 for excersise and 2 for food"))
if (c == 1):
value = input("type here\n")
with open("hammad-ex.txt", "a") as op:
op.write(str([str(gettime())]) + ": " + value + "\n")
print("successfully written")
elif (c == 2):
value = input("type here\n")
with open("hammad-food.txt", "a") as op:
op.write(str([str(gettime())]) + ": " + value + "\n")
print("successfully written")
else:
print("plz enter valid input (1(harry),2(rohan),3(hammad)")
def retrieve(k):
if k==1:
c=int(input("enter 1 for excersise and 2 for food"))
if(c==1):
with open("harry-ex.txt") as op:
for i in op:
print(i,end="")
elif(c==2):
with open("harry-food.txt") as op:
for i in op:
print(i, end="")
elif(k==2):
c = int(input("enter 1 for excersise and 2 for food"))
if (c == 1):
with open("rohan-ex.txt") as op:
for i in op:
print(i, end="")
elif (c == 2):
with open("rohan-food.txt") as op:
for i in op:
print(i, end="")
elif(k==3):
c = int(input("enter 1 for excersise and 2 for food"))
if (c == 1):
with open("hammad-ex.txt") as op:
for i in op:
print(i, end="")
elif (c == 2):
with open("hammad-food.txt") as op:
for i in op:
print(i, end="")
else:
print("plz enter valid input (harry,rohan,hammad)")
print("health management system: ")
a=int(input("Press 1 for log the value and 2 for retrieve "))

if a==1:
b = int(input("Press 1 for harry 2 for rohan 3 for hammad "))
take(b)
else:
b = int(input("Press 1 for harry 2 for rohan 3 for hammad "))
retrieve(b)
Using Python External & Built In
Modules
In Python, a module can be defined as a file containing a runnable python code. The extension
used by modules in Python is .py. Hence any simple file containing Python code can be
considered as a module if its extension is .py. The file and module names are the same; hence
we can call a module only by name without using the extension. Along with this, a module can
define functions, classes, and variables.
There are two types of modules.

 Built-in
 External

Built-in Modules:
Built-in modules are already installed in Python by default. We can import a module in Python
by using the import statement along with the specific module name. We can also access the
built-in module files and can read the Python code present in them. Newly integrated modules
are added in Python with each update. 
Some important modules names are as follows
Modules Names Purpose
calendar used in case we are working with calendars
used for generating random numbers within certain defined
random
limits
enum used while working with enumeration class
html for handling and manipulating code in HTML
math for working with math functions such as sin, cos, etc.
runpy is an important module as it locates and runs python
runpy
modules without importing them first
External modules:
External modules have to be downloaded externally; they are not already present like the built-
in ones. Installing them is a rather easy task and can be done by using the command “pip install
module_name” in the compiler terminal. Being familiar with all the modules seems like a long
shot for even the best of programmers because there are so many modules available out there.
So, we can search and find modules according to our needs and use them as there is no need to
remember all of them when we can simply look for them on the internet when the need occurs.
Being programmers, module makes our life a lot easy. Unlike programming languages in the
past, also known as low-level programming languages, Python provides us with a lot of modules
that make our coding much easy because we do not have to write all the code ourselves. We can
directly access a module for a specific task. For example, to generate a random number within
two numbers, known as its limit, we do not have to write a function ourselves with loops and a
large number of lines of codes. Instead, we can directly import a module, and this makes our
work simple.
We should not concern ourselves with the code written inside the module; instead, we can
search the internet for the functions and properties. If we are not satisfied with the available
module's work or could not find a module that could help us in the required manner, we can
create our own module by making a file with .py extension. The module file will be like any
other file you see in Python, the difference will just arise in the extension.  
Code file as described in the video
import random
random_number = random.randint(0, 1)
# print(random_number)
rand = random.random() *100
# print(rand)
lst = ["Star Plus", "DD1", "Aaj Tak", "CodeWithHarry"]
choice = random.choice(lst)
print(choice)
F-Strings & String Formatting In Python
String formatting is used to design the string using formatting techniques provided by the
particular programming language. From the % formatting to the format() method, to format
string literals, there is no limit as to the potential of string crafting. There are four significant
ways to do string formatting in Python. In this tutorial, we will learn about the four main
approaches to string formatting in Python.
#1 String Formatting (% Operator)
Python has a built-in operation that we can access with the % operator. This will help us to do
simple positional formatting. If anyone knows a little bit about C programming, then they have
worked with printf statement, which is used to print the output. This statement uses the %
operator. Similarly, in Python, we can perform string formatting using the % operator. For
Example:

name="Jack”

n="%s My name is %s” %name

print(n)

Output: "My name is Jack."

Copy

The problem with this method is when we have to deal with large strings. If we specify the
wrong type of input type operator, then it will throw an error. For Example, %d will throw a
TypeError if the input is not an integer.
#2 Using Tuple ()
The string formatting syntax, which uses % operator changes slightly if we want to make
multiple substitutions in a single string. The % operator takes only one argument, to mention
more than one argument, use tuples. Tuples are better than using the old formatting string
method. However, it is not an ideal way to deal with large strings. For Example:

name=”Jack”
class=5
s=”%s is in class %d”%(name,class)
print(s)

Copy

Output: Jack is in class 5.


#3  String Formatting (str.format)
Python 3 introduced a new way to do string formatting. format() string formatting method
eliminates the %-operator special syntax and makes the syntax for string formatting more
regular. str.format() allows multiple substitutions and value formatting. We can use format() to
do simple positional formatting, just like you could with old-style formatting:
In str.format(), we put one or more replacement fields and placeholders defined by a pair of
curly braces { } into a string.
Syntax: {}.format(values)
For Example,

str = "This article is written in {} "

print (str.format("Python"))

Copy

Output: This article is written in Python.


This string formatting method is preferred over %-style formatting. Using the format() method,
we can deal with large strings, and the code will become more readable.
#4 Using f-Strings ( f ):
Python added a new string formatting approach called formatted string literals or "f-strings."
This is a new way of formatting strings. A much more simple and intuitive solution is the use of
Formatted string literals.f-string has an easy syntax as compared to previous string formatting
techniques of Python. They are indicated by an "f" before the first quotation mark of a string.
Put the expression inside { } to evaluate the result. Here is a simple example

## declaring variables

str1="Python”

str2="Programming”

print(f"Welcome to our {str1}{str2} tutorial”)


Copy

Output: Welcome to our Python Programming tutorial.


Time Module:-
The time module provides time-related functions. It handles the time-related tasks. To use
functions that are defined in this module, we need to import the module first.

import time

Copy

It is mostly used in measuring the time elapsed during program execution.


Code file as described in the video
# F strings
import math

me = "Harry"
a1 =3
# a = "this is %s %s"%(me, a1)
# a = "This is {1} {0}"
# b = a.format(me, a1)
# print(b)
a = f"this is {me} {a1} {math.cos(65)}"
# time
print(a)
Positional arguments are the one in which an order has to be followed while passing
arguments. We have been dealing with them until now.
We know how normal functions work with positional arguments, so now we will
directly start exploring keyword arguments. But to understand them, we have to
know about asterisk or more commonly known in Perl 6 and ruby as a splat operator.
 Asterisk is used in python as a mathematical symbol for multiplication, but in case of
arguments, it refers to unpacking. The unpacking could be for a list, tuple, or a
dictionary. We will discover more about it by defining *args and **kwargs.
*args:

args is a short form used for arguments. It is used to unpack an argument. In the case
of *args, the argument could be a list or tuple. Suppose that we have to enter the
name of students who attended a particular lecture. Each day the number of students
is different, so positional arguments would not be helpful because we can not leave
an argument empty in that case. So the best way to deal with such programs is to
define the function using the class name as formal positional argument and student
names with parameter *args. In this way, we can pass student's names using a tuple.
Note that the name args does not make any difference, we can use any other name,
such as *myargs. The only thing that makes a difference is the Asterisk(*).
**kwargs:

The full form of **kwargs is keyword arguments. It passes the data to the argument
in the form of a dictionary. Let's take the same example we used in the case of *args.
The only difference now is that the student's registration, along with the student's
name, has to be entered. So what **kwargs does is, it sends argument in the form of
key and value pair. So the student's name and their registration both can be sent as a
parameter using a single ** kwargs statement.
Same as we discussed for args*, the name kwargs does not matter. We can write any
other name in its place, such as **attendance. The only mandatory thing is the double
asterisks we placed before the name.   
One of the instances where there will be a need for these keyword arguments will be
when we are modifying our code, and we have to make a change in the number of
parameters or a specific function.
Code file as described in the video

# def function_name_print(a, b, c, d, e):


# print(a, b, c, d, e)

def funargs(normal, *argsrohan, **kwargsbala):


print(normal)
for item in argsrohan:
print(item)
print("\nNow I would Like to introduce some of our
heroes")
for key, value in kwargsbala.items():
print(f"{key} is a {value}")

# function_name_print("Harry", "Rohan", "Skillf", "Hammad",


"Shivam")

har = ["Harry", "Rohan", "Skillf", "Hammad",


"Shivam", "The programmer"]
normal = "I am a normal Argument and the students are:"
kw = {"Rohan":"Monitor", "Harry":"Fitness Instructor",
"The Programmer": "Coordinator", "Shivam":"Cook"}
funargs(normal, *har, **kw)
ime Module In Python
Welcome to another tutorial guys. We are just going to open our Pycharm ide and start this
tutorial without wasting any time.
 

We are going to name our file time123 here. Moving towards our today's topic.
In Tutorial #38, we discussed modules in detail, along with their types. We also discussed a few
important modules in that tutorial. If you have not gone through it, then I would recommend
you to go and see that one first. The execution time of a program is defined as the system's
time to execute the task. As we know, all program takes some execution time, but we don't
know how much. So, don't worry. In this tutorial, we will learn it by using a very helpful
module known as the "Time module." 
As can be defined by the name, "time module handles time-related tasks."
It can be accessed by simply using an import statement.

import time

Copy

In Python, time can be tracked through its built-in libraries. The time module consists of all
time-related functions. It also allows us to access several types of clocks required for various
purposes. We will be discussing some of these important functions that are commonly used and
come handy for further programming.
time.time():
It returns us the seconds of time that have elapsed since the Unix epoch. In simple words, it tells
us the time in seconds that have passed since 1 January 1970. Its syntax is simple and easy to
use.

import time
seconds = time.time()
print("Seconds since epoch =", seconds)
time.asctime():

Copy

We use the function time.asctime() to print the local time onto the screen. There are a lot of
other ways to do it but time.asctime() prints the time in a sequence using a 24 characters string. 
The format will be something like this: Mon Feb 10 08:01:02 2020
Time.sleep():
What sleep() function does is, it delays the execution of further commands for given specific
seconds. In simple terms, it sends the program to sleep for some defined number of seconds.
sleep() function is mostly used in programs directly connected to the operating system and in-
game development. It halts the program execution, giving other programs a chance to get
executed simultaneously. 
The syntax is :
time.sleep(5)

Copy

The number of seconds is sent as a parameter within parenthesis. The program will go to sleep
for 5 seconds after getting to this line of code and will continue its execution afterward.
 time localtime():
The time.localtime() is used to convert the number of seconds to local time. This function takes
seconds as a parameter and returns the date and time in time.struct_time format. It is optional to
pass seconds as a parameter. If seconds is not provided, the current time will be returned by
time() is used.
The syntax is:
time.localtime([ sec ])

Copy

For Example:
import time

print "time.localtime() returns: %s",%time.localtime()

Copy

Uses of time modules:


We can use the time module 

 In games where missions depend on a certain time limit.


 To check the execution time a certain part of our code is taking.
 To print the date or local time onto the screen
 To suspend the execution of python thread.
 To measure the efficiency of the code.

There are many built-in functions in the time  module. Not all of them are discussed in this
tutorial. Explore more time module functions and use them in your code, so that you can
measure the execution time of your code. 
Code file as described in the video
import time
initial = time.time()

k = 0
while(k<45):
print("This is harry bhai")
time.sleep(2)
k+=1
print("While loop ran in", time.time() - initial, "Seconds")

initial2 =time.time()
for i in range(45):
print("This is harry bhai")
print("For loop ran in", time.time() - initial2, "Seconds")

# localtime = time.asctime(time.localtime(time.time()))
# print(localtime)

You might also like