Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (11 votes)
12K views

Python Notes (Code With Harry)

The document discusses Python modules, pip, and importing modules. It defines modules as files containing reusable code written by others. Pip is a package manager used to install external modules. Built-in modules come pre-installed with Python, while external modules must be downloaded using pip before use. Comments, print statements, escape sequences, variables, data types, typecasting, and the input() function are also overviewed.

Uploaded by

Zain UL ABIDIN
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (11 votes)
12K views

Python Notes (Code With Harry)

The document discusses Python modules, pip, and importing modules. It defines modules as files containing reusable code written by others. Pip is a package manager used to install external modules. Built-in modules come pre-installed with Python, while external modules must be downloaded using pip before use. Comments, print statements, escape sequences, variables, data types, typecasting, and the input() function are also overviewed.

Uploaded by

Zain UL ABIDIN
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

PYTHON PROGRAMMING

Modules & PIP in python


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 from
somewhere.
We can install a module in our system by using 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.
After installing any module in Python, you can import it into your program or your Python
projects. For example, to use flask, I will type "import flask" at the top of my Python
program.
import flask
There are two types of modules in Python:

Built-in Modules:
Built-in modules are the modules that are pre-installed in Python i.e., there is no need to
download them before using. These modules come with python interpreter itself.
Example – random, os, etc.
To get a complete list of built-in modules of python head 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.
Example – Flask, Pandas, TensorFlow, etc.

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
Comments, Escape Sequences & Print Statement
Comments:
Comments are used to write something which the programmer does not want to execute.
Comments can be written to mark author 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())
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())
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,
import os
import flask

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
# 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!


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:
import os
import flask

# 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


Escape Sequences:
 An Escape Sequence character in Python is a sequence of characters that represents a
single character.
 It does not 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
Description 
Sequences

\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 point

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

\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

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
\b Inserts a backspace in the text at that point

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
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 following data types in Python
 Integers (<class 'int'>): Used to store integers
 Floating point numbers (<class 'float'>): Used to store decimal or floating-point
numbers
 Strings (<class 'str'>): Used to store strings
 Booleans (<class 'bool'>): Used to store True/False type values
None: None is a 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 cannot start with a digit. For an example, 5harry  is illegal and not allowed.
 No white-space is allowed 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

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
print(_abcnum + abc123) # This will give sum of 40 + 55.854
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
Note: We cannot do arithmetic operations of numbers with strings 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. '''
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)
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. 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

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
print(str(abc)+45) # It will give an error as abc has been changed into string.
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 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 input () is called, you will get "45"
as a string.

String Slicing and Other Functions In Python


Strings:
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.
Primarily, you will find 3 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 3 as the output as it is a string variable containing 3 characters
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’.
E.g., Consider this string variable x
x = "String Demo"
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:

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
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 second index-1.
For 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 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_valueth character. By default, the skip value is 1 but if we want to

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
choose alternate characters of a string then we can give it as 2. Have a look at the example
below:

Other string functions:


 string.endswith(): This function allows the user to check whether a given string ends
with passed argument or not. It returns True or False.
 string.count(): This function counts the total no. of occurrence 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 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"))

Python Lists and List Functions


Lists:
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]
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 is 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., first element of the list has 0 index, and
the second element has 1 as its index and so on.
Note: If you put an index which is not in the list i.e., that index is not there in list then you
will get an error. i.e., if a list named list1 contains 4 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

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
[1, 2.5, 3.7, 9] # list of numbers (integers and floating point)
['a', 'b', 'c’] # list of characters
['a', 1, 'b', 3.5, 'zero'] # list of mixed value types
['One', 'Two', 'Three'] # list of strings
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
List Slicing:
List slices, like string slices, returns 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]
Just like we saw in strings, slicing will go from a start index to stop_index-1. It means the seq
list which is 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. Lets have a
look at few of them below:

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
# 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.
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)
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 is 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
Sample code for List:
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)

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
# 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


Before going through the actual content i.e., the implementation of a dictionary, it is
important to know some basic theories so that we can know what we are going to learn and
why we are spending our precious time learning it.
Let us 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 own distinct features, commonly known as its key
features. With that said, Python is one out of the box feature is “dictionaries”. Dictionaries
may look very similar to a “List”, but 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 do not know the word or
its spelling, we cannot obtain its definition. Let us look into the syntax of a Python dictionary.

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
a = {'key', 'value', 'cow':'mooh'}
print(a['cow']) #will print "mooh" on the screen
With the help of dictionaries, we do not have to do most of our work manually through code
like in C or C++. What I mean by this is that Python provides us with a long list of already
defined methods for dictionaries that can help us to do our work in a shorter span of time with
a very little 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, which can be made the value of some
keys in the dictionary. etc.

Sample Code for Dictionary


# 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
In Mathematics:
“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 us look at the Python
programming definition of sets:
“A set is a data structure, having unordered, unique, and unindexed elements.”

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
Elements in a set are also called entries and no two entries could be the same within a set.
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 the sets. The intersection
is an operation that creates a set containing common elements from both the 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 which can be performed on sets in python
language too.
Note: If you are a programming beginner who does not 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)

Restrictions:
Everything has a limit to its functionality, there are some limitations on working with sets
too.
Once a set is created, you cannot 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 “in” keyword or by looping through the set by using a for loop.
Despite these restrictions, sets play a very important 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.

Sample Code for Set


s = set()
# print(type(s))
# l = [1, 2, 3, 4]
# s_from_list = set(l)
# print(s_from_list)

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
# print(type(s_from_list))
s.add(1)
s.add(2)
s.remove(2)
s1 = {4, 6}
print(s.isdisjoint(s1))

If Else & Elif Conditionals in Python


“If, else and elif statement can be defined as a multiway decision taken by our program due to
the certain conditions in our code.”
“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.
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”
statement. On the other hand, else or else if statement are 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 cannot have an “else” or
“else-if” without it but let us 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)

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
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.

Sample Code for if, else and elif


# 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")

For Loops in Python


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, that are the basis of
the loop. 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
programing 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, the concept of the loop could be easily understood using an example of songs
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 song playlist the song keeps on playing until we stop it, the
same scenario can be made in case of loops, 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 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,
dictionary, and tuple.
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

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
 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. 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 in Python, it's
simple and easy. We just have to declare a variable so we can print the output through it
during different iterations and just have to use the keyword “for” and “in”.
 Advantages of loops:
 The reusability of code is ensured
 We do not have to repeat the code again and again, 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

Sample Code for “For Loop”


# 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, "HARRY", 5,3, 3, 22, 21, 64, 23, 233, 23, 6]
for item in items:
if str(item).isnumeric() and item>=6:
print(item)

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY
Prepared By:- ZAIN UL ABIDIN
Source:- CODE WITH HARRY
Quizzes
Quiz No. 01:
Create a program that takes two numbers as input from the user and then prints the sum of
these numbers.

Prepared By:- ZAIN UL ABIDIN


Source:- CODE WITH HARRY

You might also like