Python Tutorials
Python Tutorials
Python Introduction
What is Python?
Python is a popular programming language (OOP). It was created by Guido van Rossum, and
released in 20th February, 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as
it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional
way.
Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability
only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example:
if 5 > 2:
print("Five is greater than two!")
print(“Thank u for using Python”)
Python Variables
In Python, variables are created when you assign a value to it:
Example
Variables in Python:
x=5
y = "Hello, World!"
print(y)
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore
it, and you have made a multiline comment.
Python Variables
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type
after they have been set.
Example
x=4 # x is of type int
x = "Anu" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a both are different variable
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
ExampleGet your own Python Server
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output: Orange
Banana
Cherry
Note: Make sure the number of variables matches the number of values, or else you will get
an error.
Output : Orange
Orange
Orange
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values
into variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output :
apple
banana
cherry
Output Variables
The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:
Example:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Output:
Python is awesome
Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".
For numbers, the + character works as a mathematical operator:
Example
x=5
y = 10
print(x + y)
Output: 15
In the print() function, when you try to combine a string and a number with the + operator,
Python will give you an error:
Example
x=5
y = "John"
print(x + y)
===========================================================================
=======================
Class – 2
Python Data Types
Built-in Data Types
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Example:
x=5
print(type(x))
Python Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them
Example:
x=1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example:
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
Example:
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example:
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(x)
print(y)
print(z)
Output:
35000.0
120000.0
-8.77e+101
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example
y = 2.8 # float
z = 1j # complex
a = float(x)
b = int(y)
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
Random Number
Python does not have a random() function to make a random number, but Python has a
built-in module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.
• int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
x = float(1) # x will be 1.0
Strings:
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
Example
print("Hello")
print('Hello')
Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
print(a)
However, Python does not have a character data type, a single character is simply a string
with a length of 1.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
for x in "banana":
print(x)
Output:
b
String Length
To get the length of a string, use the len() function.
Example
a = "Hello, World!"
print(len(a))
Output: 13
===========================================================================
=================
Class – 3
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
print("free" in txt)
Output: True
if "free" in txt:
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword
not in.
Example
Specify the start index and the end index, separated by a colon, to return a part of the
string.
Example
b = "Hello, World!"
print(b[2:5])
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Python Method/Function
i) Upper Case
upper()
Example:
a = "Hello, World!"
print(a.upper())
Example
a = "Hello, World!"
print(a.lower())
iii) Remove Whitespace
strip()
Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
Example:
The strip() method removes any whitespace from the beginning or the end:
Example
a = "Hello, World!"
print(a.replace("H", "J"))
v) Remove white space from all.
rstrip()
x = txt.rstrip()
Example
x = txt.capitalize()
print (x)
vii) isdigit()
isdigit()
txt = "50800"
x = txt.isdigit()
print(x)
viii) isspace()
isspace()
x = txt.isspace()
print(x)
ix) lstrip()
lstrip()
x = txt.lstrip()
print("of all fruits", x, "is my favorite")
x) Centered string
center()
center()
Print the word "banana", taking up the space of 20 characters, with "banana" in the middle:
txt = "banana"
x = txt.center(20)
print(x)
print(txt.center(50,”=”))
xi) Count()
count()
Return the number of times the value "apple" appears in the string:
x = txt.count("apple")
print(x)
xii) Find() -> return position
find()
Searches the string for a specified value and returns the position of where it was found
Find()
x = txt.find("welcome")
print(x)
xiii) Format specified values in string
format()
Insert the price inside the placeholder, the price should be in fixed point, two-decimal
format:
print(txt.format(price = 49))
x = txt.title()
print(x)
Note that the first letter after a non-alphabet letter is converted into a upper case letter:
print(x)
Make the lower case letters upper case and the upper case letters lower case:
x = txt.swapcase()
print(x)
xvii) strip()
strip()
x = txt.strip()
txt = "50"
x = txt.zfill(10)
print(x)
===========================================================================
=======
Class -4
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
a = "Hello"
b = "World"
c=a+b
print(c)
a = "Hello"
b = "World"
c=a+""+b
print(c)
Escape Characters
To insert characters that are illegal in a string, use an escape character.
Example:
You will get an error if you use double quotes inside a string that is surrounded by double
quotes:
Example:
The escape character allows you to use double quotes when you normally would not be
allowed:
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
Example:
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example:
print(10 + 5)
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Now we give code examples of arithmetic operators in Python. The code is given below
-
1. a = 32 # Initialize the value of a
2. b = 6 # Initialize the value of b
3. print('Addition of two numbers:',a+b)
4. print('Subtraction of two numbers:',a-b)
5. print('Multiplication of two numbers:',a*b)
6. print('Division of two numbers:',a/b)
7. print('Reminder of two numbers:',a%b)
8. print('Exponent of two numbers:',a**b)
9. print('Floor division of two numbers:',a//b)
x = 15
y=2
print(x // y)
Output: 7
#the floor division // rounds the result down to the nearest whole number
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Example:
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
== Equal x == y
!= Not equal x != y
Now we give code examples of Comparison operators in Python. The code is given
below –
Output:
Now we compile the above code in Python, and after successful compilation, we
run it. Then the output is given below -
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
# returns False because x is not the same object as y, even if they have the same content
print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True
because x is equal to y
Example:
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
Operator Precedence
Operator precedence describes the order in which operations are performed.
Example:
Parentheses has the highest precedence, meaning that expressions inside parentheses must
be evaluated first:
print((6 + 3) - (6 + 3))
Output:
print((6 + 3) - (6 + 3))
"""
Parenthesis have the highest precedence, and need to be evaluated first.
The calculation above reads 9 - 9 = 0
"""
Example:
Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:
print(100 + 5 * 3)
Output:
print(100 + 5 * 3)
"""
Multiplication has higher precedence than addition, and needs to be evaluated first.
The calculation above reads 100 + 15 = 115
"""
The precedence order is described in the table below, starting with the highest precedence
at the top: Rules are (BADMAS)
Full Form of BADMAS isBrackets, orders, division, multiplication, addition, subtraction)
Operator Description
() Parentheses
** Exponentiation
^ Bitwise XOR
| Bitwise OR
and AND
or OR
Example:
print(100 - 3 ** 3)
"""
Exponentiation has higher precedence than subtraction, and needs to be evaluated first.
The calculation above reads 100 - 27 = 73
"""
Example:
print(100 + 5 * 3)
"""
Multiplication has higher precedence than addition, and needs to be evaluated first.
The calculation above reads 100 + 15 = 115
"""
Example:
print(5 + 4 - 7 + 3)
"""
Additions and subtractions have the same precedence, and we need to calculate from left to
right.
The calculation above reads:
5+4=9
9-7=2
2+3=5
"""
===========================================================================
========================
Class – 5
Python If ... Else
Python Conditions and If statements
• Equals: a == b
• Not Equals: a != b
These conditions can be used in several ways, most commonly in "if statements" and loops.
Example:
If statement:
a = 33
b = 200
if b > a:
In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than
33, and so we print to screen that "b is greater than a".
Indentation:
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.
elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then try
this condition".
Example:
a = 33
b = 33
if b > a:
elif a == b:
In this example a is equal to b, so the first condition is not true, but the elif condition is true,
so we print to screen that "a and b are equal".
else
The else keyword catches anything which isn't caught by the preceding conditions.
a = 200
b = 33
if b > a:
elif a == b:
else:
Example:
Ternary Operators
Example:
a=2
b = 330
You can also have multiple else statements on the same line:
Example:
a = 330
b = 330
Nested If
If with in a if is called nested if.
X=5
Y=9
# Example 1 : Number checker
num = 5
if num > 0:
else:
if num < 0:
else:
Example:
print("Hello World")
The print() function prints the specified message to the screen, or other standard output
device.
The message can be a string, or any other object, the object will be converted into a string
before written to the screen.
Example:
Example:
Print a tuple:
if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.
Example
a = 33
b = 200
if b > a:
pass
Guess what will be output:
str1=”Python World”
Print(str1*2)
??
The following example asks for the username, and when you entered the username, it gets
printed on the screen:
Example:
In Python, we use the input() function to take input from the user. Whatever you enter as
input, the input function converts it into a string. If you enter an integer value still input()
function converts it into a string.
The Python interpreter will not execute further lines until the user enters the input.
Example:
2. # a use of input()
Some Example:
1) WAP to input an age and check whether he is child/teenage/young/old according to the
following criteria.
if age< 13:
print("Child")
print("Teenage")
print("Young")
print("Old")
else:
Example-2:
Example-3:
WAP to input a student’s name and his 3 subject’s number. Finally print his name, total,
average and grade.
Grade calculation:
tot=sub1+sub2+sub3
avg=int(tot/3)
if avg<35:
grade="Fail"
grade="3rd Division"
grade="2nd Division"
grade="1st Division"
else:
grade="Excellent"
print(num1," is greater")
elif ((num2>num1 and num2>num3) and (num2 !=num1 and num2 !=num3)):
print(num2," is greater")
elif ((num3>num1 and num3>num2) and (num3 !=num1 and num3 !=num2)):
print(num3," is greater")
else:
Output:
999 is greater
=======================================================================
Class -6
Revision class
Revision previous class.
Class-7
Python placeholder
In Python, Placeholder is a word, characters or a string of characters to hold a
temporary place. The placeholder behaves as a dynamic place holder in such a way
that you can pass a particular value for that placeholder.
In this article, we show how to use placeholders in Python to serve as placeholders for
data, such as objects.
So if you have a variable in Python or any other type of data type, you can create a
placeholder, usually in a print function to reserve a spot for this variable before
explicitly saying what the variable is.
We then print out these variables with a print function using placeholders.
Example:
>>> amount= 3
>>> print ("I went to the {} and {} {} times this week". format (destination1,
destination2, amount))
We create 3 variables.
The first variable we create is destination1. We set this variable equal to "beach"
The second variable we create is destination2. We set this variable equal to "park"
Every time you see {} in the print statement, this represents a placeholder.
What a placeholder does is it holds a place for a variable. When we do the substition,
the variable will appear in the place of {}.
You see this 3 times in the print statement, meaning 3 places for variables are
reserved.
After we are done with the print statement ending with quotes (either single or
double), we put .format(destination1, destination2, amount), representing the 3
variables in order that we want substituted for the placeholders.
In the end, this gives us the output statement, " I went to the beach and park 3 times
this week"
Placeholders are great things to use in Python code especially if you are dealing with
different types of data.
For example, to create this same method the conventional way without placeholders,
we would have the following print line, shown below.
Example:
>>> print ("I went to the " + destination1 + " and " + destination2 + " " +
str(amount) + " times this week")
One thing is, we have to keep breaking the string apart every time we want to put in a
variable.
Second, we have to remember to put appropriate spaces between variables, which can
be very annoying.
Lastly, for strings taking in different data types, such as int, we have to explicitly make
the variable a string with the str() function, or else Python will throw an error.
You simply put the placeholder, without any care to the different data types, close the
string, put . format() with the names of the variables within the format function, and
that is it.
Syntax: { }.format(value)
Parameters:
Returntype: Returns a formatted string with the value passed as parameter in the
placeholder position.
name = "Ram"
age = 22
number.".format(name, age)
print(message)
or
Example:
Ouput:
Example:
Output:
Python World
Python World
Pytho
The release of Python version 3.6 introduced formatted string literals, simply called “f-
strings.” They are called f-strings because you need to prefix a string with the letter
'f' to create an fstring. The letter 'f' also indicates that these strings are used for
formatting. Although there are other ways for formatting strings, the Zen of Python
states that simple is better than complex and practicality beats purity--and f-strings
are really the most simple and practical way for formatting strings. They are also
faster any of the previous more commonly used string.
This document will explain how to use the many options available with f-strings.
Alignment There are several ways to align variables in f-strings. The various alignment
options are as follows:
Forma
Description Example
t
print("The value is :
{:f}".format(40))
Output:
print("The value is :
{:x}".format(500))
This will output hex format
:x
in lowercase Output:
print("The value is :
{:X}".format(500))
This will output hex format
:X
in uppercase. Output:
print("The value is :
{:n}".format(500.00))
This will output number
:n
format. Output:
print("The value is : {:
%}".format(0.80))
Output:
This will give the output in
a percentage format. The value is : 80.000000%
By default it will give 6
decimal places for the This example shows how to skip
:% the decimal places by using
percentage output, in case
you don’t want any {:.0%} inside the placeholder.
decimal value you can use
print("The value is :
period with 0 i.e (:.0%).
{:.0%}".format(0.80))
Output:
print("The value is
This will output an
{:_}".format(1000000))
underscore as a thousand
:_
separator. It is available Output:
from python 3.6+.
The value is : 1_000_000
Forma
Description Example
t
print("The value is :
{:,}".format(1000000))
Output:
This will output comma as
:,
a thousands separator The value is : 1,000,000
The comma(,) is added , as a
thousand separator as shown in
the output.
Output:
Output:
Output:
Output:
Output:
This will center align the
:^
final result The value 40 is a positive
value
My grocery list will be printed after 30 spaces. Note : is the value seperator
Output:
My Grocery List
print(f'{"Welcome to SSPM":^100s}')
Print(“=”,50)
Output: ==============================================
Example of “f-strings.”
The F-string offers a convenient way to embed Python expression inside string literals
for formatting. print(f"{val}for{val} is a portal for {val}.") print(f"Hello, My name is
{name} and I'm {age} years old.")
Name=”Rakesh Sharma”
Age=69
Rating=985.8721
Print(f”My name is {Name}, I’m {Age} years old and My rating is {Rating}”)
value=11/7
print(f"Value = {value:.2f}")
print(f"Value = {value:.3f}")
print(f"Value = {value:3.5f}")
Output:
Value = 1.57
Value = 1.571
Value = 1.57143
%s is a placeholder for string datatype. Placeholder is the concept picked up from the
C language. They are used in format strings to represent a variable whose type will be
determined in runtime. Placeholders are represented as a character or a set of
characters used after a % symbol. % represents the placeholder and the following
character or set of characters represents the data type of the value that will replace
the placeholder. For integers, there’s %d, for float there’s %f, and for strings, there is
%s.
Example:
name="Mohit Dhar"
age=54
rating=6.75
name="Ramu Singh"
age=86
rat=695.6943
print("My name is {} and age is {}".format(name,age))
# of datetime library
import datetime
today = datetime.datetime.today()
Example:
In below example will add space inside the Placeholder using the format(). To add
space, you have to specify the number of spaces inside curly brackets after the
colon(:). So the Placeholder will look like {:5}.
Output:
You can also give the index inside the placeholder for example: {0:5} where 0 will
refer to the first value inside format.
Output:
====================================================
===================================
word="anaconda"
print (letter)
Output:
d
a
The reason why this loop works is because Python considers a “string” as a sequence
of characters instead of looking at the string as a whole.
print (word)
Output:
Apple
Banana
Car
Dolphin
Now, let’s move ahead and work on looping over the elements of a tuple
here.
nums = (1, 2, 3, 4)
sum_nums = 0
# Output
# Sum of numbers is 10
Consider the list example above. The for loop prints out individual words from the list.
But what if we want to print out the individual characters of each of the words within
the list instead?
This is where a nested for loop works better. The first loop (parent loop) will go over
the words one by one. The second loop (child loop) will loop over the characters of
each of the words.
How to use Python range() in for loop? The range() function is typically used with for
loop to repeat a block of code for all values within a range. Let’s discuss different
scenarios of using the range() function with for loop in Python. By specifying start,
stop, and step parameters, By excluding the start and step parameters and excluding
step parameters. We will also discuss how to pass the negative step value in the
range() function.
# Syntax
for element in range(start,stop,step):
statements...
Here start and step are optional. But stop are mandatory.
# Output:
# 1,2,3,4,5,6,7,8,9,
Here, I have specified the start as 1 and the stop as 10 on range(). The for loop will
iterate from 0 to 9 with the default step value as 1.
# Output:
# 0,1,2,3,4,5,6,7,8,9,
We specified the stop as 10. The for loop will iterate from 0 to 9. Inside the for loop, we
are displaying the values present in the range.
# Output:
# 1,3,5,7,9,
# Output:
# 20,17,14,11,
We have iterated from 20 to 10 (Reverse order) by decrementing 3 at each step. The
final iterated values are – 20,17,14 and 11.
Alternatively, to get a reverse range in Python, you can use the reversed() function in
combination with the range function. For example:
Break statement
Continue statement
Pass statement
for i in range(20):
if i==10:
break
else:
print(i)
# Python program to
# demonstrate continue
# statement
# loop from 1 to 10
for i in range(1, 11):
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
continue
else:
# otherwise print the value
# of i
print(i, end = " ")
Output:
1 2 3 4 5 7 8 9 10
# Pass statement
s="welcome"
for i in s:
if i == 'c':
print('Pass executed')
pass
print(i)
Output:
w
e
l
Pass executed
c
o
m
e
n=10
for i in range(10):
for j in range(n-i):
print("*",end="")
print()
2)
print(str[i], end="")
print("\n")
3) # Reverse a number
rev = 0
while(n != 0):
rem = n % 10
n = n // 10
print(rev)
# output
# 12534
x={40,15,23,60,17,19,82}
for i in x:
if i%2==0:
print(i,end=" ")
Output:
40 82 60
while condition:
n=1
while n<=10:
print(n)
n=n+1
Example:
n=5
while True:
print("Python")
if n>10:
break
else:
n+=1
These problems are nothing but Python while loop exercises. For example, the above
pattern can be printed using the following code:
Example:
n=1
while n <= 5:
print(str(n) * n)
n += 1
Output:
1
22
333
4444
55555
Example:
rows = 7
current_row = 1
while current_row <= rows:
print("*" * current_row)
current_row += 1
Output:
*
**
***
****
*****
******
*******
What Is the Difference Between a while Loop and a for Loop in
Python?
The main difference between a for and while loop in Python is the way they iterate. A
while loop continues executing as long as a condition remains true, whereas a for loop
iterates over a predefined sequence or collection of elements.
While loops are typically used when the number of iterations is not known in advance
or when a condition needs to be continuously monitored. On the other hand, for loops
are suitable for iterating over a known sequence, such as a list or a range of numbers.
Example:
import time
start = int(input('Enter countdown duration in seconds: '))
print(f'Blastoff in {start} seconds:')
count = start
while count >= 0:
time.sleep(1) # pauses for 1 second so humans can see the countdown
# there will be a 1s pause after 'blastoff in...' but less before 'BLASTOFF!'
print(f'T-{count}')
count -= 1
time.sleep(0.25)
print('BLASTOFF!')
Class-10 Exercise
We will solve some problems:
Input : 5
Expected output
Factorial is 120
Hint 1
Input : 6
Expected output
Factorial is 720
:: Solution ::
# Factorial of a number
else:
fact = 1
while(n):
fact *= n
n = n-1
# output
# Factorial is 120
fact=1
print(fact)
temp=n
n=m
m=temp
n=n+m
m=n-m
n=n-m
First_Val=0
Second_Val=1
for i in range(1,n):
if(n<=1): Output:
next=n Enter a range : 7
else: 0+1=1
next=First_Val+Second_Val 1+1=2
print(First_Val,"+ ",end='') 1+2=3
First_Val=Second_Val 2+3=5
print(next)
for i in range(2,n):
for j in range(2,i):
if i%j==0:
flag=1
break;
if flag==0:
print("Prime no "+str(i))
else:
flag=0
# output
# 0 7 14 21 28 35 42 49
pos = []
neg = []
Original List are [2, -7, -28, 190, 98
for i in range(len(n)): 97]
if n[i]<1: Positive numbers are : [2, 190, 98
neg.append(n[i]) Negative numbers are : [-7, -28,
else:
pos.append(n[i])
1) Exercise 8 : Write a program to filter even and odd number from a list.
2) Exercise 9 : Write a Python program to reverse a number.
3) Exercise 10 : Write a program to print n natural number in descending
order using a while loop.
Python Lists
Lists are used to store multiple items in a single variable.
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.
Lists are created using square brackets:
Create a List:
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the
order of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
Example
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Output: banana
1) append() method
Definition and Usage
fruits=["banana","cherry","apple"]
fruits.append("pineapple")
['banana', 'cher
print(fruits)
fruits.append(cars)
print(fruits)
fruits.clear()
x = fruits.count("cherry")
Output: 2
5) Python List extend() Method
Add the elements of cars to the fruits list:
The extend() method adds the specified list elements (or any iterable) to the end of
the current list.
The index() method returns the position at the first occurrence of the specified value.
What is the position of the value "cherry":
x = fruits.index("cherry")
Output: 2
The insert() method inserts the specified value at the specified position.
Syntax
list.insert(pos, elmnt)
Parameter Values
Parameter Description
Syntax
list.pop(pos)
fruits.pop(1)
print(fruits)
The remove() method removes the first occurrence of the element with the specified
value.
fruits.remove("banana")
print(fruits)
10) Python List reverse() Method
Definition and Usage
fruits.reverse()
print(fruits)
Syntax
list.sort(reverse=True|False, key=myFunc)
Parameter Values
Parameter Description
reverse Optional. reverse=True will sort the list descending. Default is reverse
number=[10,20,50,100,30]
tot=0 Output:
tot=tot+i
print("Total is ",tot)
number=[10,20,50,100,30]
max=0
Output:
Largest number is : 100
for i in number:
if i>max:
max=i
for x in fruits:
Output:
if "apple" in x:
['apple', 'red apple', 'pineapple', '
newlist.append(x)
print(newlist)
print(newlist) Output:
print(newlist)
['Green apple', 'Banana', 'Red cherr
print(newlist)
print(newlist)
7) WAP to create positive and negative list from list1 having approximately
10 positive and negative nos.
8) WAP to count no of digit.
10) WAP to create a unique list and duplicate list numbers from a list having
duplicate values.
list1=[10,30,50,20,90,10,100,50,10,30]
unique=[]
dupli=[] Output:
for i in list1: Unique list: [10, 30, 50, 20, 90
unique.append(i)
dupli.append(i)
print("*",end="")
print()
for i in range(row,0,-1):
for j in range(0,i-1):
print("*",end="")
print()
str2 = str1[::-1]
Output:
if str1 == str2:
Enter a string: madam
print(str1, "is a palindrome")
Madam is a palindrome
else:
index = vowels.index('e')
index = vowels.index('i')
for i in range(6):
print(list1[i])
Tuples can have any number of items and they may be of different types
(integer, float, list, string, etc.).
Tuples are created using parentheses, with the items separated by commas. For
example, (1, 2, 3) is a tuple of three integers.
Tuples can be accessed by index, starting with 0. For example, the first item in
the tuple (1, 2, 3) is 1.
Tuples can be sliced, just like lists. For example, (1, 2, 3)[1:] is a tuple of two
integers, 2 and 3.
Tuples can be concatenated, just like lists. For example, (1, 2, 3) + (4, 5, 6) is
a tuple of six integers, 1, 2, 3, 4, 5, 6.
Tuples can be used as keys in dictionaries. For example, {1: 'a', 2: 'b', 3: 'c'} is
a dictionary with three key-value pairs, where the keys are integers and the
values are strings.
Here are some of the key differences between Python tuples and lists:
Tuples Lists
Immutable Mutable
Here is a table summarizing the key differences between tuples and lists:
As you can see, tuples are immutable, meaning they cannot be changed once they are
created. This makes them ideal for storing data that should not be modified, such as
database records. Lists, on the other hand, are mutable, meaning they can be changed
after they are created. This makes them ideal for storing data that needs to be
updated, such as a list of items in a shopping cart.
Another key difference between tuples and lists is that tuples are faster than lists. This
is because tuples are stored in a contiguous block of memory, while lists are stored in
a non-contiguous block of memory. This means that accessing elements in a tuple is
faster than accessing elements in a list.
Finally, tuples use less memory than lists. This is because tuples are stored in a more
compact format than lists. This means that using tuples can help to improve the
performance of your program.
In general, tuples should be used when you need to store data that should not be
modified and when you need to improve the performance of your program. Lists
should be used when you need to store data that needs to be updated.
Disadvantages of tuples
We cannot add an element to tuple but we can add element to list.
We can't sort a tuple but in a list we can sort by calling "list. sort()" method.
Tuples creating
Create a Python Tuple With one Element
In Python, creating a tuple with one element is a bit tricky. Having one element within
parentheses is not enough.
x=("apple")
x=("apple",)
N.B.: If you want to create a single element tuple then you give a comma, after the
element otherwise it will treat as string.
print(my_tuple.count('p')) # prints 2
print(my_tuple.index('l')) # prints 3
Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert
it into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
tuples=("apple","banana","orange")
list1=list(tuples)
list1.append("Pine Apple")
list1.insert(1,"Cherry")
tuples=tuple(list1)
print(tuples)
Tuples are unchangeable, so you cannot remove items from it, but you can use the
same workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "orange", and convert it back into a tuple:
tuples=("apple","banana","orange","mango")
list1=list(tuples)
list1.remove("orange")
tuples=tuple(list1)
print(tuples)
Example
tuples=("apple","banana","orange","mango")
del tuples
print(tuples) #this will raise an error because the tuple no longer exists
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a
tuple:
Example
Packing a tuple:
Unpacking a tuple:
Example
Output:
apple
banana
cherry
Note: The number of variables must match the number of values in the tuple, if not,
you must use an asterisk to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the
variable name and the values will be assigned to the variable as a list:
print(green)
print(yellow)
print(red)
Output:
apple
banana
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
Example
Create a Set:
Example
Example
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
difference_update() Removes the items in this set that are also included in an
specified set
intersection_update() Removes the items in this set that are not present in oth
set(s)
symmetric_difference_update() inserts the symmetric differences from this set and anoth
update() Update the set with the union of this set and others
Return a set that contains the items that only exist in set x, and not in set y:
Example
x.difference_update(y)
print(x)
The difference_update() method removes the items that exist in both sets.
fruits.discard("banana")
print(fruits)
The discard() method removes the specified item from the set.
This method is different from the remove() method, because the remove() method will
raise an error if the specified item does not exist, and the discard() method will not.
Return a set that contains the items that exist in both set x, and set y:
x={"apple","banana","cherry","python"}
y={"google","microsoft","python","banana"}
z=x.intersection(y)
print(z)
fruits.pop()
print(fruits)
Return a set that contains all items from both sets, except items that are present in
both sets:
x={"apple","banana","cherry","python"}
y={"google","microsoft","python","banana"}
z=x.symmetric_difference(y)
print(z)
Return a set that contains all items from both sets, duplicates are excluded:
x={"apple","banana","cherry","python"}
y={"google","microsoft","python","banana"}
z=x.union(y)
print(z)
If an item is present in more than one set, the result will contain only one appearance
of this item.
x={"apple","banana","cherry","python"}
y={"google","microsoft","python","banana"}
x.update(y)
print(x)