Code With Harry
Code With Harry
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 :
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.
print("Hello World")
Copy
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!
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!
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.
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.
import os
#This is a comment
print("Main code started")
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")
Copy
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:
Copy
Escape Sequences :
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:
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.
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.
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:
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:
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:
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
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
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))
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:
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.
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.
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
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
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:
Copy
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:
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:
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.
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
# 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")
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]
Copy
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
Copy
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"))
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
# 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.
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
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()
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:
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
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:
Copy
# 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():
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.
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)
Copy
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.
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))
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.
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”
print(n)
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
print (str.format("Python"))
Copy
## declaring variables
str1="Python”
str2="Programming”
import time
Copy
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
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
Copy
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)