PYTHON1
PYTHON1
■ Python Introduction
■ Python Installation
■ Keywords In Python
■ Variables In Python
■ Getting Input In Python
■ Pycharm installation in Python
■ Single and Multi line Comment in Python
■ Type Casting in Python
■ String and String Functions in Python
■ String Manipulation in Python
■ Arithmetic Operators in Python
■ Assignment Operators in Python
■ Comparison operators in Python
■ Logical operators in Python
■ Bitwise operators in Python
■ IF Statement in Python
■ IF - Else Statement in Python
■ ELIF Statement in Python
■ Nested IF Statement in Python
■ While Loop in Python
■ Continue using While Loop in Python
■ Break using While Loop in Python
■ Range in Python
■ For Loop in Python
■ Nested For Loop in Python
■ Nested For Loop in Python
■ While Else & For Else
■ Lists in Python
■ Tuple in Python
■ Set in Python
■ Dictionary in Python
■ Identity Operators in Python
Introduction
■ Python is an interpreted, object-oriented, high-level programming
language that can be used for a wide variety of applications.
■ Python is a powerful general-purpose programming language.
■ First developed in the late 1980s by Guido van Rossum.
■ Python is open source programming language.
■ Guido van Rossum named it after the BBC Comedy TV series
Monty Python’s Flying Circus
Advantages of Python Programming
■ Python is easy to learn and use.
■ Large number of libraries available that can be used in your projects
today.
■ High Level Programming Language.
■ Huge Community
■ Object-oriented language
■ Portable across Operating systems
Organizations using Python
■ Google
■ Microsoft
■ Facebook
■ Mozilla
■ cisco
■ Quora
■ YouTube etc...
Python Based Jobs
■ Data Analysis
■ Artificial Intelligence
■ Automation
■ Web Application
■ Desktop Application
■ Hacking
■ School Students
High-level Languages
■ Machine languages are very close to the hardware. Every computer has its machine
language. A machine language programs are made up of series of binary pattern.
(Eg. 110110) It represents the simple operations which should be performed by the
computer. Machine language programs are executable so that they can be run
directly.
Complier
■ A Complier transforms code written in a high-level programming language into a
machine code or any other Intermediate code.It converts the text that a programmer
writes into a format the CPU can understand.The conversion manner is diffrent.It
convers the Entire source code in one go and reports all the errors of the program
along with the line numbers.After all the error are removed,the program is
recompiled and after that the compailer is no needed in memory as the object
program is available.
interpreter
■ The interpreter converts the source code line-by-line during Run
Time,translates it into machine code or virtual machine code.
Interpreter allows evaluation and modification of the program while it
is executing.if there is error in any line,it reports it at the same time
and program executio cannot resume untill the errror is
rectified.Interprerer must always be present in the memory every time
the program is run.it is first interpreted and then executed
Difference between Compiler and Interpreter
Compiler Interpreter
It read the whole program at a time. It read the program line by line.
It translates the whole program at a time into It translates only one line of program at a time
machine code. into machine code.
It produces machine code which is directly It produces intermediate code after translation.
understood by computer.
It takes large amount of time to analyze the It takes less amount of time to analyze the
source code. source code.
it is faster it is slower
Programming language like C,C++ use compiler. Programming language like Python,Ruby use
interpreter.
Python Installation
■ Before you start working in python, you need to install Python on your
computers. There is multiple Python distribution available today.We
can install Python from www.python.org this is called
ad CPython installation and comes with python interpreter, Python
IDLE (Python GUI) and Pip (Package Installer).
■ There are many other Python distribution are available. Anaconda
Python distribution is one such highly recommended distribution that
comes preloaded with many packages and libraries (e.g., NumPy,
SciPy, Panda libraries etc..).Many popular IDEs are also available
e.g., Spyder IDE, PyCharm, Notepad++ etc. In Anaconda Python
distribution Spyder IDE is already available.
Keywords in Python Programming
■ Keywords are the words that convey a special meaning to the language
compiler/interpreter. These are reserved for special purpose and must not
be used as normal identifier names. Eg: for,break,continue,etc.
■ A keyword is a word having special meaning reserved by programming
language
■ We cannot use a keyword as a variable name, function name or any other
identifier.
■ True and False are truth values in Python. They are the results of comparison
operations or logical (Boolean) operations in Python.
■ None is a special constant in Python that represents the absence of a value
or a null value.
■ and, or, not are the logical operators in Python. and will result into True only
if both the operands are True.
■ The async and await keywords are provided by the asyncio library in Python.
They are used to write concurrent code in Python.
Setting the Data Type
Example Data Type Try it
x = 20 int Try it »
x = 1j complex Try it »
x = None NoneType
Example Data Type
x = "Hello World“ str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Source Code Keyword
import keyword
print(keyword.kwlist)
Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
Variables in Python Programming
name= "Ram"
User_name= "Ram"
name2= "Ram"
Input Function in Python Programming
■ he input() function takes the user's input in the next single line, so
whatever user writes in a signle line would be assign to to a variable.
The input ( ) function helps to enter data at run time by the user and
returns it as a string. This function prompts the user for an input from
the keyboard.
■ Once the user has give the input and pressed enter One of the most
important things to note here is that we're storing whatever the user
entered into a variable. The output function print ( ) is used to display
the result of the program on the screen after execution.
■ Use the int ( ) Function to Check if the Input Is an Integer in Python.
The int ( ) function can convert a given string integer value to an
integer type. Use the float ( ) Function to Check if the Input Is an
decimal number in Python. The float ( ) function can convert a given
string decimal number value to an float type.
Source Code Getting input in Python
#Getting String input Statement
name=input("Enter Name : ")
print(type(name))
print(name)
■ Typecasting or type conversion is a method of changing an entity from one data type
to another.
■ Type casting is a method used for changing the variables or values declared in a
certain data type into a different data type in order to match for the operation
required to be performed by the code snippet. In python, this feature can be
accomplished by using the constructor functions like int(), string(), float(), etc.
"""
a = 10.0
print(a)
print(type(a))
b = int(a)
print(b)
print(type(b))
int()
float()
str()
"""
a = int(input("Enter The Value of A : "))
b = int(input("Enter The Value of B : "))
c=a+b
print("Total : " + str(c))
String and String Functions in Python
■ Python has several built-in functions associated with the string data type. These
functions let us easily modify and manipulate strings. Creating Strings is the
simplest and easy to use in Python. To create a string in Python, we simply enclose a
text in single as well as double-quotes.
■ type() => The returns the type of the object.
■ upper() => All the characters in a given string are uppers case.
■ lower() => All the characters in a given string are lower case.
■ capitalize() => The first character is the upper case
■ The title() => The first character in every word of the string is an upper case.
■ count() => Finds the number of times a specified value in the given string.
■ find() => Finds the first occurrence of the specified value.
■ replace() => Replaces a specified phrase with another specified phrase.
■ isalnum() => Checks whether all the characters in a given string is alphanumeric or
not
■ isalpha() => returns True if all the characters in the string are alphabets
■ islower() => Checks if all characters in the string are lowercase
■ isupper() => Checks if all characters in the string are uppercase
■ strip() => The used to trim whitespaces from the string object
# String And String Function
s = “sarabesh chess"
print(s)
print(type(s))
print(s.upper())
print(s.lower())
print(s.capitalize())
print(s.title())
print(s.count("t"))
print(s.endswith("ED"))
print(s.find("o"))
print(s.find("o", 5))
print(s.replace("o", '0'))
a = "joes1234"
print("Is Upper : ", a.isupper())
print("Is Lower : ", a.islower())
print("Is Alpha Numeric : ", a.isalnum())
print("Is Alpha : ", a.isalpha())
s = "he\nis\ngood"
print(s)
print(s.splitlines())
print(s.splitlines(True))
a = “Welcome Python World"
print(a.split(" "))
a = “Python,Welcome,World"
print(a.split(","))
s=" Python "
print(len(s))
print(len(s.strip()))
print(len(s.lstrip()))
print(len(s.rstrip()))
s=‘20-09-2023'
print(s.partition('-'))
String Manipulation in Python
Syntax :
s [ start : end ]
s [ start : ]
s [ : end ]
s[::]
Source Code
# String Manipulation
'''
S a m p l e
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
'''
s = "sample"
print(s)
print(s[0:2])
print(s[:5])
print(s[1:])
print(s[-1])
print(s[-2:-1])
print(s[:-1])
print(s[::-1])
Arithmetic Operators in Python
■ Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication ,division and also python have floor
division,exponentiation.
■ Addition ( + ) => This operator is a binary operator and is used to add two operands.
■ Subtraction ( - ) => This operator is a binary operator and is used to subtract two
operands.
■ Multiplication ( * ) => This operator is a binary operator and is used to multiply two
operands.
■ Division ( / ) => This is a binary operator that is used to divide the first
operand(dividend) by the second operand(divisor) and give the quotient as result.
■ Modulus ( % ) => This is a binary operator that is used to return the remainder when
the first operand(dividend) is divided by the second operand(divisor).
■ Exponentiation ( * * ) => The performs exponential (power) calculation on operators
■ Floor division ( / / ) => The division of operands where the result is the quotient in
which the digits after the decimal point are removed.
Source Code
# Arithmetic operators
"""
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponentiation
// Floor division
"""
a = 123
b = 10
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(2**3)
Assignment Operators in Python
■ Assignment operators are used to assigning value to a variable. The left side
operand of the assignment operator is a variable and right side operand of the
assignment operator is a value. This operator is used to assign the value on the right
to the variable on the left
Compound Operator Sample Expression Expanded Form
+= a+=2 a=a+2
-= a-=6 a=a-6
*= a*=7 a=a*7
/= a/=4 a=a/4
%= a%=9 a=a%9
"""
= Assignment
+= Addition
-= Subtraction
*= Multiplication
/= Division
%= Modulus
**= Exponentiation
//= Floor division
"""
a = 125
print(a)
a += 5 # a=a+5
print(a)
a -= 10 # a=a-10
print(a)
a *= 10 # a=a*10
print(a)
a /= 10
print(a)
a %= 10
print(a)
a **=10
print(a)
a //= 10
print(a)
Comparison Operators or Relational Operators in Python
"""
a = 20 Output
b = 20
print(a == b) True
print(a != b) False
print(a > b) False
print(a < b) False
print(a >= b) True
print(a <= b) True
Logical Operators in Python
• Logical operators are used to combine multiple conditions in a single expression in Python. The
three logical operators in Python are and, or, and not.
• and: This operator returns True if both the conditions on either side of the operator are True,
otherwise it returns False.
• or: This operator returns True if either of the conditions on either side of the operator is True,
otherwise it returns False.
• not: This operator inverts the truth value of a single condition. If a condition is True, the not
operator will make it False and vice versa.
• This program is using logical operators in Python to check if the value of a variable a falls within a
certain range.
"""
a = 25
print(a >= 10 and a <= 20)
print(a >= 10 or a <= 20)
print(not(a >= 10 and a <= 20))
Output
False
True
True
Bitwise Operators in Python
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Right shift
This program uses bitwise operations in Python.
• a & b: The "&" operator performs a bitwise AND operation, resulting in the value 9 (binary
representation of 25 is 11001 and 45 is 101101, so the AND operation is 100001 which is 9
in decimal).
• a | b: The "|" operator performs a bitwise OR operation, resulting in the value 61 (binary
representation of 25 is 11001 and 45 is 101101, so the OR operation is 111101 which is 61
in decimal).
• a ^ b: The "^" operator performs a bitwise XOR operation, resulting in the value 52 (binary
representation of 25 is 11001 and 45 is 101101, so the XOR operation is 010100 which is
52 in decimal).
• ~a: The "~" operator performs a bitwise NOT operation, resulting in the value -26 (in binary,
the NOT of 11001 is 00110, which is -26 in two's complement).
• a << 2: The "<<" operator performs a bitwise left shift operation, resulting in 100 (the binary
representation of 25 is 11001, so the left shift operation is 100100 which is 100 in decimal).
• a >> 2: The ">>" operator performs a bitwise right shift operation, resulting in 6 (the binary
representation of 25 is 11001, so the right shift operation is 00110 which is 6 in decimal).
Source Code
Output
# Bitwise Operators 9
""" 61
& AND 52
| OR -26
^ XOR 100
~ NOT 6
<< Zero fill left shift
>> Signed right shift
"""
a = 25
b = 45
print(a & b)
print(a | b)
print(a ^ b)
print(~a)
print(a << 2)
print(a >> 2)
IF Statement in Python
The if statement is the most basic of all the control flow statements. It tells your program to execute a certain
section of code only if a particular test evaluates to true. The if statement is written with the if keyword.
Syntax :
if ( condition ) :
// body of the statements will execute if the condition is true
This program is a simple implementation of an "if-else" statement in Python to check whether a given number is
even or odd.
n = int(input("Enter The Number : ")) - This line takes the input from the user and converts it to an integer.
if n % 2 == 0: - The "if" statement checks if the value of n divided by 2 has a remainder of 0. If it's true, the following
indented block of code is executed.
print(n, " is Even Number") - If the condition in the if statement is true, this line will print the message "n is Even
Number".
The program checks if the given number is even or odd by checking if it's divisible by 2 (i.e. n % 2 == 0), and if it is,
the program outputs the message "n is Even Number".
Source Code
# IF Statement in Python
Output
Enter The Number : 34
34 is Even Number
IF - Else Statement in Python
The if-else statement is used to execute both the true part and the false part of a given
condition. If the condition is true, the if block code is executed and if the condition is false,
the else block code is executed.
Syntax :
if ( condition ) :
// body of the statements will execute if the condition is true
else :
// body of the statements will execute if the condition is false
This program is a simple Python script that prompts the user to enter their name and age,
and then checks if the entered age is greater than or equal to 18. If the age is greater than or
equal to 18, the program prints a message stating that the person is eligible to vote, along
with their name and age. If the age is less than 18, the program prints a message stating
that the person is not eligible to vote, along with their name and age.
Source Code
Output
Enter Your Name : Ram
Enter Your Age : 23
Ram age is 23 Eligible for Vote.
Elif Statement in Python
The elif condition is used to multiple conditional expressions after the if condition or
between the if and else conditions. The elif block is executed if the specified condition
evaluates to True.
Syntax :
if ( condition 1 ) :
// body of the statements will execute if the condition1 is true
elif ( condition 2 ) :
// body of the statements will execute if the condition2 is true
.
.
else :
// body of the statements will execute if the condition1 is false condition2 is
False
• This program is a Python script that prompts the user to enter a number of days and then calculates a fine
based on that number.
• It starts by using the input() function to ask the user to enter a number of days, which is stored in the "days"
variable.
• Then, the program uses an if-elif block to check the value of the "days" variable against a series of conditions.
• If the value of "days" is equal to 0, the program prints "Good No Fine"
• If the value of "days" is greater than or equal to 1 and less than or equal to 5, the program calculates the fine as
0.5 * days and prints the fine amount
• If the value of "days" is greater than 5 and less than or equal to 10, the program calculates the fine as 1 * days
and prints the fine amount
• If the value of "days" is greater than 10 and less than or equal to 30, the program calculates the fine as 5 *
days and prints the fine amount
• If none of the above conditions are met, the program will print "Membership Cancel"
• So the program is checking the number of days and based on the number of days it is calculating the fine.
Source Code
# elif Statement in Python
"""
0 No Fine
1-5 0.5 Output
5-10 1
10-30 5 Enter The Days : 5
>30 Membership Cancel
""" Fine Amount : 2.5
days = int(input("Enter The Days : "))
if days == 0:
print("Good No Fine")
elif days >= 1 and days <= 5:
print("Fine Amount : ", days * 0.5)
elif days > 5 and days <= 10:
print("Fine Amount : ", days * 1)
elif days > 10 and days <= 30:
print("Fine Amount : ", days * 5)
else:
print("Membership Cancel")
Nested If Statement in Python
Nested If Statement means to place one If inside another If Statement. Nested ifs are very common in
programming. when you nest ifs, the main thing to remember is that an else statement always refers to the
nearest if statement that is within the same block as the else and that is not already associated with an else.
Syntax:
if ( Expression 1 ) :
// Executes when the Expression 1 is true
if ( Expression 2 ) :
// Executes when the Expression 2 is true
This program is a Python script that prompts the user to enter three marks, then calculates the total and
average of those marks, and then uses if-else statements to determine the result and grade based on the
marks.
• It starts by using the input() function to ask the user to enter three marks, m1, m2, and m3,
which are then stored in variables. The program then calculates the total of the marks by adding
the three marks and stores it in the variable 'total' and also calculates the average of the marks
by dividing total with 3.0 and stores it in the variable 'average'
• Then, the program uses an if-elif block to check the value of the three marks against a series of
conditions.
• If all three marks are greater than or equal to 35, the program will print "Result : Pass" and then
again check the average of the marks and calculate the grade If average is greater than or
equal to 90 and less than or equal to 100, the program will print "Grade : A" If average is greater
than or equal to 80 and less than or equal to 89, the program will print "Grade : B" If average is
greater than or equal to 70 and less than or equal to 79, the program will print "Grade : C" If
none of the above conditions are met, the program will print "Grade : D"
• If any of the three marks is less than 35, the program will print "Result : Fail" and "Grade : No
Grade"
• So the program is checking the student's three marks, calculating the total and average of the
marks, and then determining the result and grade based on the marks and average.
Source Code
# Nested If Statement in Python
"""
3 Marks as Input
Total
Average
Result
If Pass Grade
90-100 A
80-89 B
70-79 C
Else D
"""
m1 = int(input("Enter Mark-1 : "))
m2 = int(input("Enter Mark-2 : "))
m3 = int(input("Enter Mark-3 : "))
total = m1 + m2 + m3
average = total / 3.0
print("Total : ", total)
print("Average : ", average)
if m1 >= 35 and m2 >= 35 and m3 >= 35:
print("Result : Pass")
if average >= 90 and average <= 100:
print("Grade : A")
elif average >= 80 and average <= 89:
print("Grade : B")
elif average >= 70 and average <= 79:
print("Grade : C")
else:
print("Grade : D")
else:
print("Result : Fail")
print("Grade : No Grade")
Output
Enter Mark-1 : 90
Enter Mark-2 : 90
Enter Mark-3 : 90
Total : 270
Average : 90.0
Result : Pass
Grade : A
While Loop in Python
The while loop is repeats a statement or block while its controlling expression is true.The condition can be
any Boolean expression. The body of the loop will be executed as long as the conditional expression is true.
When condition becomes false, control passes to the next line of code immediately following the loop.
If the condition to true, the code inside the while loop is executed.
The condition is evaluated again.
This process continues until the condition is false.
When the condition to false, the loop stops.
Syntax:
while ( Condition ) :
// body of statement
The first while loop in the code you provided will continue to execute and print the numbers from 1 to 10. It
initializes the variable i to 1 and then uses the while loop to check if i is less than or equal to 10. If the
condition is true, it prints the current value of i and then increments the value of i by 1. This process will
repeat until i is no longer less than or equal to 10, at which point the while loop will exit.
The second while loop in the code is designed to print the even numbers from 2 to 20. It initializes the
variable i to 2, and the variable n to 20. Then, it uses the while loop to check if i is less than or equal to 20. If
the condition is true, it prints the current value of i and then increments the value of i by 2. This process will
repeat until i is no longer less than or equal to 20, at which point the while loop will exit.
Output
Source Code 1
# While Loop 2
""" 3
1.While Loop 4
2.For Loop 5
""" 6
i=1 7
while i <= 10: 8
print(i) 9
i += 1 10
print("--------------------") --------------------
print("Even No : ") Even No :
n = 20 2
i=2 4
while i <= 20: 6
print(i) 8
i += 2 10
12
14
16
18
20
Continue using While Loop in Python
• The continue statement instructs a loop to continue to the next iteration. The continue statement is used to
skip the remaining statements of the current loop and go to the next iteration.
• This program is a Python script that uses a while loop to iterate over the numbers from 1 to 20, and prints
only the odd numbers.
• It starts by initializing a variable i to 1, which is used as the counter for the while loop. The while loop then
runs as long as the value of i is less than or equal to 20.
• Inside the while loop, there is an if statement that checks whether the remainder of i divided by 2 is equal to
0 using the modulo operator %. If the remainder is 0, it means that the number is even and the program will
continue to the next iteration using the continue statement.
• The continue statement causes the program to skip the rest of the code in the current iteration of the loop,
and move on to the next iteration.
• If the remainder is not 0, it means that the number is odd, and the program will print the current value of i
and then increments the value of i by 1.
• This process will repeat until i is no longer less than or equal to 20, at which point the while loop will exit and
the program will end.
• So the program is using a while loop to iterate over the numbers from 1 to 20, and using an if statement to
check whether each number is even or odd. The program is only printing the odd numbers and skipping the
even numbers using continue statement.
Source Code
Print Odd Numbers using While Loop in Python
# Continue Statement
i=1
while i <= 20:
if i % 2 == 0:
i=i+1
continue;
print(i)
i += 1
Output
1
3
5
7
9
11
13
15
17
19
Break using While Loop in Python
• The break statements are your way of asking the loop to stop and execute the next statement. When a
break statement is encountered inside a loop, the loop is immediately terminated and the program control
resumes at the next statement following the loop
• This program is a Python script that uses a while loop to iterate over the numbers from 1 to 20, but it exits
the loop when the number 7 is encountered.
• It starts by initializing a variable i to 1, which is used as the counter for the while loop. The while loop then
runs as long as the value of i is less than or equal to 20.
• Inside the while loop, there is an if statement that checks whether the value of i is equal to 7 using the
comparison operator ==. If the value is 7, it means that the number is 7 and the program will exit the loop
using the break statement.
• The break statement is used to exit a loop prematurely. When the break statement is encountered inside a
loop, the loop is immediately terminated and the program continues with the next statement following the
loop.
• If the value of i is not equal to 7, it means that the number is not 7, and the program will print the current
value of i and then increments the value of i by 1.
• This process will repeat until i is no longer less than or equal to 20, or until i is equal to 7 at which point the
while loop will exit using the break statement and the program will end.
• So the program is using a while loop to iterate over the numbers from 1 to 20, and using an if statement
with break statement to check whether the number is 7 or not. When the number is 7, the while loop exits
and the program ends.
Source Code
# Break Statement
i=1
while i <= 20:
if i==7:
break
print(i)
i += 1
Output
1
2
3
4
5
6
Range in Python
• The above program is a Python script that demonstrates the use of the built-in range() function.
• The range() function creates an iterator that generates a sequence of numbers within a given range.
• In the first line, range(5) creates an iterator that generates a sequence of numbers from 0 (inclusive)
to 5 (exclusive). The list() function is used to convert the iterator to a list, so the output is [0, 1, 2, 3,
4].
• In the second line, range(2, 5) creates an iterator that generates a sequence of numbers from 2
(inclusive) to 5 (exclusive). The output is [2, 3, 4].
• In the third line, range(0, 21, 2) creates an iterator that generates a sequence of numbers from 0
(inclusive) to 21 (exclusive) with a step of 2. The output is [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20].
• In the fourth line, range(1, 20, 2) creates an iterator that generates a sequence of numbers from 1
(inclusive) to 20 (exclusive) with a step of 2. The output is [1, 3, 5, 7, 9, 11, 13, 15, 17, 19].
• So the program is using the range() function and list() function to create a range of numbers with
different start, stop and step values. The range() function creates an iterator and the list() function is
used to convert the iterator to a list.
Source Code
# Range in Python
""" Output
1-5 =>1,2,3,4,5
0-5 =>2,4 +2 [0, 1, 2, 3, 4]
range(5) =>0,1,2,3,4 [2, 3, 4]
range(2,5) => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
""" [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
print(list(range(5)))
print(list(range(2, 5))) # n-1
print(list(range(0, 21, 2)))
print(list(range(1, 20, 2)))
For Loop in Python
The for loop is used to repeat a specific block of code which you want to repeat a fixed number of
times. The for loop is a control flow statement that is used to repeatedly execute a group of
statements as long as the condition is satisfied.
Syntax:
for variable_name in sequence :
body of loop
This program is a Python script that demonstrates the use of the for loop and the built-in range()
function.
• The first for loop uses the range() function to create an iterator that generates a sequence of
numbers from 0 (inclusive) to 21 (exclusive) with a step of 2. The for loop iterates over the numbers
in the sequence and prints each one to the screen.
• The second for loop uses the range() function to create an iterator that generates a sequence of
numbers from 0 to 4. The for loop iterates five times, each time prompting the user to input a
number using the built-in input() function.
• The values entered by the user are stored in variables a and b, and then the program print the sum
of a and b as output. So the program is using the for loop and the range() function to iterate over a
sequence of numbers and for each iteration, it prompts the user to enter two numbers and print the
sum of those numbers.
• The first for loop iterates over a sequence of even numbers and the second for loop iterates 5 times
and each iteration it prompts user to enter two numbers.
Source Code
# For Loop in Python
for i in range(0, 21, 2):
print(i)
for i in range(5):
a=int(input("Enter a No : "))
b=int(input("Enter a No : "))
print(a+b)
Output
Enter a No : 2
0 Enter a No : 2
2 4
4 Enter a No : 3
6 Enter a No : 3
8 6
10 Enter a No : 3
12 Enter a No : 3
14 6
16 Enter a No : 3
18 Enter a No : 3
20 6
Enter a No : 3
Enter a No : 2
5
Nested For Loop in Python
The nested loop refers to a loop within a loop, an inner loop within the body of an outer one. Nested loops
are useful when for each pass through the outer loop, you need to repeat some action on the elements in
the outer loop. The nested loop is a one iteration of the outer loop is first executed, after which the inner
loop is executed. The execution of the inner loop continues till the condition described in the inner loop is
satisfied.
Syntax:
// outer for loop
for variable_name in sequence :
// inner for loop
for variable_name in sequence :
// body of loop
This program is a Python script that demonstrates the use of nested for loops and the built-in range()
function.
The program contains three main parts, each one using a different approach to accomplish different
tasks.
In the first part of the program, there is a nested for loop where the outer loop uses the range() function to
create an iterator that generates a sequence of numbers from 0 to 5. The inner for loop uses the same
function to create an iterator that generates a sequence of numbers from 0 to the current value of the
outer loop variable. The inner loop prints an asterisk character (*) for each value of the inner loop variable.
The inner print statement uses the end parameter to specify that no newline character should be added
after the asterisk. As a result, the program prints a right-angled triangle pattern of asterisks.
In the second part of the program, there is another nested for loop where the outer loop uses the range()
function to create an iterator that generates a sequence of numbers from 5 to 1 with a step of -1. The
inner for loop uses the same function to create an iterator that generates a sequence of numbers from 0
to the current value of the outer loop variable. As in the first part, the inner loop prints an asterisk
character (*) for each value of the inner loop variable. The inner print statement uses the end parameter
to specify that no newline character should be added after the asterisk. As a result, the program prints
another right-angled triangle pattern of asterisks, but this time in reverse order.
In the third part of the program, there is another nested for loop where the outer loop uses the range()
function to create an iterator that generates a sequence of numbers from 65 to 69. The inner for loop uses
the same function to create an iterator that generates a sequence of numbers from 65 to 69. The inner
loop prints a character represented by the ASCII code of the current value of the inner loop variable using
the built-in chr() function. The inner print statement uses the end parameter to specify that no newline
character should be added after the character. As a result, the program prints a matrix of 5x5 containing
the characters A, B, C, D and E.
Source Code
# Nested For Loop for i in range(6):
""" for j in range(i):
* print("*",end="")
** print("")
*** print("----------------")
****
***** for i in range(5,0,-1):
for j in range(i):
***** print("*",end="")
**** print("")
*** print("----------------")
**
* for i in range(65,70,1):
ABCDE for j in range(65,70,1):
ABCDE print(chr(j),end="")
ABCDE print("")
ABCDE
ABCDE
A-Z => 65-90
a-z=> 97-122
"""
Output
*
**
***
****
*****
----------------
*****
****
***
**
*
----------------
ABCDE
ABCDE
ABCDE
ABCDE
ABCDE
While Else and For Else in Python
Else block will be executed only if the loop isn't terminated by a break statement. The else clause executes after
the loop completes normally. This means that the loop did not encounter a break statement. They are really useful
once you understand where to use them.
This program demonstrates the use of the else block in both while loops and for loops in Python.
The first block of code is a while loop that starts with the variable "i" equal to 1 and continues to run until "i" is no
longer less than or equal to 5. The loop prints the value of "i" on each iteration, and then increments "i" by 1. After
the while loop completes its iterations, the else block is executed and prints the message "Loop Completed".
The second block of code is a for loop that uses the range() function to iterate over the numbers from 1 to 20. On
each iteration, the value of the iterator variable "i" is printed. After the for loop completes its iterations, the else
block is executed and prints the message "For Loop Completed".
Both While and for loop checks for the condition inside the loop and runs the loop until the condition is true. In the
given code, we don't have any condition to break the loop that's why the both loops are running completely and
printing "Loop Completed" or "For Loop Completed" respectively
Syntax:
while condition :
while block statement Source Code
else :
else block statement
Syntax: # While Else & For Else
for variable_name in sequence :
for block statement i=1
else : while i<=5:
else block statement #if(i==4):
#break
print(i)
i+=1
else:
print("Loop Completed")
for i in range(1,21):
#if i==5:
#break
print(i)
else:
print("For Loop Completed")
Output
9
1
10
2
11
3
12
4
13
5
14
Loop Completed
15
1
16
2
17
3
18
4
19
5
20
6
For Loop Completed
7
8
List in Python
Lists are used to store multiple items in a single variable.To separate two items, you use a comma ( , ) . List
uses the square brackets [ ]. Lists are one of 4 built-in data types in Python used to store collections of data,
the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
• Sequence Type
• Element of the list can access by index They are mutable
• This program demonstrates various built-in functions and methods that can be used with lists in Python.
The first block of code shows how to create a list and access its elements using indexing. It also shows how
to change the value of an element in a list using indexing.
The second block of code shows how to create a list with different data types and how to access the
elements of the list and their types.
The third block of code demonstrates how to use the clear() method to remove all elements from a list, the
copy() method to create a copy of a list, the count() method to count the number of occurrences of an
element in a list, the index() method to find the index of an element in a list, the len() function to find the
length of a list, the max() and min() functions to find the maximum and minimum element in a list, the pop()
method to remove an element from a list using an index, and the remove() method to remove an element
from a list using its value.
• The fourth block of code shows how to use the append() method to add elements
to a list, the extend() method to add elements from another list, and the insert()
method to insert an element at a specific index in a list.
• The fifth block of code demonstrates how to use the range() function to create a
list of numbers, the list() function to convert a string to a list, and the sort()
method to sort the elements of a list in ascending or descending order. It also
shows how to use the key parameter to sort the elements based on a specific key
and the reverse parameter to sort the elements in descending order.
Source Code
# List in Python
"""
Sequence Type
Mutable
a[5]
a={1,2,3,4,5}
a[0]
"""