0% found this document useful (0 votes)
3 views115 pages

Combined Python

The document provides an overview of Python programming, covering its features, character sets, data types, and operators. It explains the importance of identifiers, variables, and literals, detailing how to create and manipulate them in Python. Additionally, it introduces different data types such as strings, lists, tuples, and dictionaries, along with their respective operations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views115 pages

Combined Python

The document provides an overview of Python programming, covering its features, character sets, data types, and operators. It explains the importance of identifiers, variables, and literals, detailing how to create and manipulate them in Python. Additionally, it introduces different data types such as strings, lists, tuples, and dictionaries, along with their respective operations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction

Features

Areas of
python

Program

Learning
Programming
Introduction

Features

Areas of
python

Program

Learning
Programming
Introduction

Features

S Areas of
python

Program

Learning
Programming
Introduction

Features

Areas of
python

Program

Learning
Programming
Introduction

Features

Areas of
python

Program

Learning
Programming
Code &
Environment

Modes in
python

Interactive
mode

Scripting
Mode

THANKS for
watching
Code &
Environment

Modes in
python

Interactive
mode

Scripting
Mode

THANKS for
watching
Code &
Environment

Modes in
python

Interactive
mode

Scripting
Mode
Code &
Environment

Modes in
python

Interactive
mode

Scripting
Mode

THANKS for
watching
Code &
Environment

Modes in
python

Interactive
mode

Scripting
Mode

THANKS for
watching
Code &
Environment

Modes in
python

Interactive
mode

Scripting
Mode

THANKS
Introduction

Features

Areas of
python

Program

Learning
Programming
Character
Set
 Letters A-Z, a-z
 Digits 0-9 Keywords
 Special symbols space+*/ **\O]0// = != ==
< , > .*" &#= >=@_(underscore)
 Whitespaces Blank space, tabs (), carriage
return (-), newline, form feed.
Identifiers
 Other characters Python can process all
ASCII and Unicode characters as part of data or
literals .
Variable
Every component of a Python program is created using
the character set, be it statements or expressions or
other components of a program. Variable
example
Character
Set
 Keywords are reserved words.

 Each keyword has a specific meaning to the Python Keywords


interpreter.
 As Python is case sensitive, keywords must be written
exactly as they are Identifiers

Variable

Variable
example
Character
Set
Identifiers are names used to identify a variable,
function, or other entities in a program.
The rules for naming an identifier in Python are as Keywords
follows:
 The name should begin with an uppercase or a lowercase
alphabet or an underscore sign (_). This may be followed
by any combination of characters a-z, A-Z, 0-9 or Identifiers
underscore (_). Thus, an identifier cannot start with a
digit.
 It can be of any length. (However, it is preferred to
keep it short and meaningful). Variable
 It should not be a keyword or reserved word given in
Table.
 We cannot use special symbols like !, @, #, $, %, etc. in Variable
identifiers. example
Character
Set
marksMaths marksEnglish
marksIP MYFILE Keywords
avg _DS
Marks_IP chk189
Valid identifiers
Identifiers

Marks-Maths 2marksEnglish
break for Variable
[Link] 231ww

invalid identifiers Variable


examples
Character
Set
Variable is an identifier whose value can change.
For example variable age can have different value for different
person. Variable name should be unique in a program.
Value of a variable can be string (for example, ‘b’, ‘Global Citizen’),
Keywords
number (for example 10,71,80.52) or any combination of
alphanumeric (alphabets and numbers for example ‘b10’) characters.
In Python, we can use an assignment statement to create new
variables and assign specific values to them. Identifiers
gender = 'M'
message = "Keep Smiling"
price = 987.9 Variable
Variables must always be assigned values before they are used in the
program, otherwise it will lead to an error. Wherever a variable name
occurs in the program, the interpreter replaces it with the value of Variable
that particular variable. examples
Character
Set
#To find the sum of two given numbers
num1 = 10
10 20 30
num2 = 20 Keywords
result = num1 + num2 num1 num2 result
print(result)
#print function in python displays the output
Output: Identifiers
30
#To find the area of a rectangle
10 20
length = 10
breadth = 20 length breadth Variable
area = length * breadth
print(area) 200
Output: area Thanks
200
Character
Set

Keywords

Identifiers

Variable

Thanks
Data Types

Data type identifies the type of data which a variable can


hold and the operations that can be performed on those Literals/Values
data.

String literals

Numeric Literals

Thanks
Data Types

Literals means constant values are the data Literals/Values


items that have fixed value .
Python allows several kinds of literals:
String literals
 String Literals
 Numeric Literals
 Boolean Literals Numeric Literals
 Special Literal None

Thanks
Data Types

Literals/Values

String literals

Numeric Literals

Thanks
Data Types

String literal enclosed text in quotes single Literals/Values


quote ‘a’ Double quotes ”gender”,
We can also assign strings in triple quotes
Example String literals
Str1=‘’’ hello welcome
To python ‘’’
Str2=“ “ “ hello welcome Numeric Literals
To python “ “ “

Thnaks
Data Types

Determining character size in string example


Literals/Values
“abc” contain 3 characters
“alpha” contains 5 characters
String literals
len() is a function that is used to determine
length of string.
Numeric Literals
Example
Str1= “hello “
len(Str1) Thanks
Data Types

The Numeric literals in Python can be Literals/Values

of three numerical types:


String literals
int : integers
Float : real numbers written in decimals
Complex numbers written in 2+3j Numeric Literals

Thanks
Character
Set

Keywords

Identifiers

Variable

Thanks
Data Types

Data type identifies the type of data which a variable can


hold and the operations that can be performed on those Literals/Values
data.

String literals

Numeric Literals

Thanks
Data Types

Literals means constant values are the data Literals/Values


items that have fixed value .
Python allows several kinds of literals:
String literals
 String Literals
 Numeric Literals
 Boolean Literals Numeric Literals
 Special Literal None

Thanks
Data Types

Literals/Values

String literals

Numeric Literals

Thanks
Data Types

String literal enclosed text in quotes single Literals/Values


quote ‘a’ Double quotes ”gender”,
We can also assign strings in triple quotes
Example String literals
Str1=‘’’ hello welcome
To python ‘’’
Str2=“ “ “ hello welcome Numeric Literals
To python “ “ “

Thnaks
Data Types

Determining character size in string example


Literals/Values
“abc” contain 3 characters
“alpha” contains 5 characters
String literals
len() is a function that is used to determine
length of string.
Numeric Literals
Example
Str1= “hello “
len(Str1) Thanks
Data Types

The Numeric literals in Python can be Literals/Values

of three numerical types:


String literals
int : integers
Float : real numbers written in decimals
Complex numbers written in 2+3j Numeric Literals

Thanks
Data Types

Integer data type contains all negative ,zero and


positive integer numbers. Literals/Values
Examples of integer literals

A=10
B=15 String literals
C=35
D=1234
Numeric Literals
Note don’t start number with zero like 012 because it is
treated as octal not simple number.

Thanks
Data Types
Float data type contains fractional form and exponential
form numbers . It is real literal.
Examples of float literals fractional form Literals/Values
A=2.0
B=17.5
C=-13.0
D=0.3 String literals
Note if no decimal then it is not real literal examples
7
+17/2 Numeric Literals
[Link] All are invalid
17,250.25

Thanks
Data Types
Float data type contains fractional form and exponential
form numbers . It is real literal.
Examples of float literals exponential form Literals/Values
Exponential examples 0.58E01 can be written as
A=152E05
B=1.52E07
C=152E+8 String literals

1.7E ( no exponent)
0.17E2.3 ( exponent can’t have
fractional part) All are invalid Numeric Literals
17,25E25 ( No Comma allowed)

Thanks
Data Types
A Boolean literal in Python represent two types of values
True or False
Example Literals/Values
Markgiven=True
Markgiven=Flase
Test it like this
type(Markgiven) String literals
You will get its datatype as bool.

None is special literal that means no value or unassigned


Example Numeric Literals
Value=None
Test it like this
type(Value)
You will get its datatype as None. Thanks
Character
Set

Keywords

Identifiers

Variable

Thanks
Data Types

Data type identifies the type of data which a variable can


hold and the operations that can be performed on those Numeric Data
data. type

Sequence
String

Sequence
List, Tuple

Mapping
Dictionary
Data Types

Number data type stores numerical values only. It is


Numeric
further classified into three different types:
Data Type
 int
 float
 complex Sequence
String

Sequence
List ,Tuple
Boolean data type (bool) is a subtype of integer. It is a unique
data type, consisting of two constants, True and False.
Boolean True value is non-zero. Boolean False is the value
Thanks
zero.
Data Types

Variables of simple data types like integer, float, Boolean


Numeric
etc. hold single value.
Data type
But such variables are not useful to hold multiple data values,
for example, names of the months in a year, names of Sequence
students in a class, names and numbers in a phone book or String
the list of artifacts in a museum.

For this, Python provides sequence data types like Sequence


 Strings, List , Tuple
 Lists,
 Tuples,
 and mapping data type Dictionaries. Mapping
Dictionary
(A) String Data Types
A Python sequence is an ordered collection of items, where
each item is indexed by an integer value. Three types of Numeric
sequence data types available in Python are Strings, Lists and Data type
Tuples. A brief introduction to these data types is as follows:
(A) String
String is a group of characters. These characters may be Sequence
alphabets, digits or special characters including spaces. String
String values are enclosed either in single quotation marks
(for example ‘Hello’) or in double quotation marks (for
example “Hello”). The quotes are not a part of the string, they Sequence
are used to mark the beginning and end of the string for the List ,Tuple
interpreter. For example,
>>> str1 = 'Hello Friend'
Mapping
>>> str2 = "452“
Dictionary
Numerical operations on strings, even when the string
contains a numeric value. For example str2 is a numeric string.
(B) LIST Data Types

List is a sequence of items separated by commas and items


are enclosed in square brackets [ ]. Note that items may be of Numeric
different date types. Data type

Example 3.2
#To create a list Sequence
String
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]

#print the elements of the list list1 Sequence


>>> list1 List ,Tuple
Output
[5, 3.4, 'New Delhi', '20C', 45] Mapping
Dictionary
(C) TUPLE Data Types

Tuple is a sequence of items separated by commas and items


are enclosed in parenthesis ( ). Numeric
This is unlike list, where values are enclosed in brackets [ ]. Data type
Once created, we cannot change items in the tuple.
Similar to List, items may be of different data types.
Example 3.3 Sequence
#create a tuple tuple1 String
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1) Sequence
Output List ,Tuple
(10, 20, "Apple", 3.4, 'a')
Mapping
Dictionary
Mapping (A) Dictionary Data Types
Mapping is an unordered data type in Python. Currently, there
is only one standard mapping data type in Python called
Dictionary. Numeric
Dictionary in Python holds data items in key-value pairs and
Items are enclosed in curly brackets { }. Dictionaries permit
Data type
faster access to data. Every key is separated from its value
using a colon (:) sign. The key value pairs of a dictionary can
be accessed using the key. Keys are usually of string type and Sequence
their values can be of any data type. In order to access any String
value in the dictionary, we have to specify its key in square
brackets [ ]. Example 3.4 #create a dictionary Sequence
>>> dict1 = {'Fruit':'Apple','Climate':'Cold', 'Price(kg)':120} List ,Tuple
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
#getting value by specifying a key Mapping
>>> print(dict1['Price(kg)'])
120 Dictionary
Data Type

Numeric
Data Type

Sequences

Mappings
Dictionary

Thanks
Operators

An operator is used to perform specific mathematical or


logical operation on values. Arithmetic
Operators
The values that the operator works on are called operands.
For example, in the expression 10 + num , the value 10, and
the variable num are operands and the + (plus) sign is an Relational
operator. Operators
Python supports several kind of operators, their
categorization is briefly explained in this section. Logical
 Arithmetic Operators Operators
 Relational Operators
 Logical Operators
 Membership Operators
Membership
Operators
Operators

Arithmetic
Operators

Relational
Operators

Logical
Operators

Membership
Operators
Operators

'+' operator can also be used to concatenate two strings on


either side of the operator. Arithmetic
>>> str1 = "Hello" Operators
>>> str2 = "India"
>>> str1 + str2
'HelloIndia' Relational
'*' operator repeats the item on left side of the operator if Operators
first operand is a string and second operand is an integer
value.
>>> str1 = 'India' Logical
>>> str1 * 2 Operators
'IndiaIndia‘
Operators (+) and (*) work in similar manner for other
sequence data types like list and tuples.
Membership
Operators
Operators

 Relational operator compares the values of the operands


on its either side and determines the relationship among Arithmetic
them. Operators
 Consider the given Python variables num1 = 10, num2 = 0,
num3 = 10, str1 = "Good", str2 = "Afternoon” Relational
Operators
 Similarly, there are other relational operators like <= and
>=.
Logical
Operators

Membership
Operators
Operators

Arithmetic
Operators

Relational
Operators

Logical
Operators

Membership
Operators
Operators

Arithmetic
Operators

Assignment
Operators

Logical
Operators

Membership
Operators
Operators

Arithmetic
Operators

Relational
Operators

Logical
Operators

Membership
Operators
Operators

Arithmetic
Operators

Relational
Operators

Logical
Operators

Membership
Operators
Data Type

Numeric
Data Type

Sequences

Mappings
Dictionary

Thanks
 An expression is defined as a combination of constants,
variables and operators.
 An expression always evaluates to a value.
 A value or a standalone variable is also considered as an
expression but a standalone operator is not an expression.
 Some examples of valid expressions are given below.
(i) num – 20.4
(ii) 3.0 + 3.14
(iii) 23/3 -5 * 7(14 -2)
(iv) "Global"+ "Citizen"
 An expression represents something ,a statement is a
programming instruction that does something i.e. ,some
action takes place .
 An expression always evaluates to a value. While statement
is executed i.e. takes action.
 It is not necessary that a statement results in a value ;it may
or may not yield a value .
 Some examples of valid statements are given below.
(i) a=15
(ii) b=a-10
(iii) print(a+3)
Precedence of Operators
When an expression contains more than one operator, their
precedence (order or hierarchy) determines which operator
should be applied first.
Higher precedence operator is evaluated before the lower
precedence operator.
In the an expression , '*'and '/' have higher precedence than
'+' and '-'.
Note:
a) Parenthesis can be used to override the precedence of
operators. The expression within () is evaluated first.
b) For operators with equal precedence, the expression
is evaluated from left to right
Precedence of Operators
Example 3.5 How will Python evaluate the following expression?
20 + 30 * 40
Solution:
#precedence of * is more than that of +
= 20 + 1200 #Step 1
= 1220 #Step 2

Example 3.6 How will Python evaluate the following expression?


(20 + 30) * 40
Solution:
= (20 + 30) * 40 # Step 1
#using parenthesis(), we have forced precedence of + to be more than that of *
= 50 * 40 # Step 2
= 2000 # Step 3
Precedence of Operators
Example 3.7 How will the following expression be evaluated?
15.0 / 4.0 + (8 + 3.0)
Solution:
= 15.0 / 4.0 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4

Example 3.8 How will the following expression be evaluated?


18.0 / 4.0 + (8 + 3.0)
Solution:
= 18.0 / 4.0 + (8.0 + 3.0) #Step 1
= 18.0 / 4.0 + 11.0 #Step 2
= 4.5 + 11.0 #Step 3
= 15.5 #Step 4
1. Assigning same value to multiple variables
Example
a=b=c=10
2. Assigning multiple values to multiple variables
x,y,z=10,20,30
x, y=25,50
print(x,y)
It will print result as 25 50
x,y= y, x
print(x,y)
Result will be 50 25
More examples …
b, c, a=6,12,6
print(a,b,c)
It will give result as 6, 6, 12

Find out the output for following

p,q= 3,5
q,r= p-2,p+2
print(p,q,r)
Result is 3,1,5
1. Write a program to input a welcome message and print it.
# Code starts here
message=input(“Enter welcome message:”)
print()
print( “Hello”, message)

Output
Enter welcome message : welcome to python class

Hello , welcome to python class


2. Program to obtain length and breadth of a rectangle and calculate its area.
# Program starts here
length = float ( input ("Enter length of the rectangle: "))
breadth = float ( input ("Enter breadth of the rectangle: "))
area = length * breadth
print ("Rectangle specifications ")
print("Length = ", length, end =' ' )
print (“Breadth = ", breadth)
print ("Area = ", area) Output
Enter length of the rectangle : 8.75
Enter breadth of the rectangle 35.0
Rectangle specifications
Length= 8.75 Breadth = 35.0
Area = 306.25
3. Write a program to input a value in kilometres and convert it into miles
(1 km=0.621371 miles)

# Program starts here


km = int( input ("Enter kilometres: "))
miles = km * 0.621371
print ("Kilometres:", km)
print ("Miles :", miles)

Output
Enter kilometres : 20
Kilometres: 20
Miles: 12.42742
4. Write a program to input a value in tonnes and convert it into quintals and
kilograms.
(1 tonne=10 quintals 1 tonne = 1000kgs, 1 quintal= 100kgs)
# Program starts here
tonnes = float ( input ("Enter tonnes: "))
quintals = tonnes * 10
kgs = quintals * 100
print(“Tonnes:", tonnes)
print("Quintals : ", quintals)
print ("Kilograms: ", kgs)
Output
Enter tonnes: 2.5
Tonnes: 2.5
Quintals: 25.0
Kilograms : 2500.0
5. Write a program to enter a small poem and print it.
# Program starts here
poem= input ("Enter a small poem: ")
print("The poem you entered")
print (poem)

Output
Enter a small poem : "Hope" is the thing with feathers- That perches in the
soul- And sings the tune without the words- And never stops at all -EMILY
DICKINSON
The poem you entered
"Hope" is the thing with feathers- That perches in the soul- And sings the
tune without the words- And never stops at all -EMILY DICKINSON
Debugging
Due to errors, a program may not execute or may
generate wrong output. :

i) Syntax errors
ii) Logical errors
iii) Runtime errors
Syntax Errors
Like any programming language, Python has rules that
determine how a program is to be written.
This is called syntax. The interpreter can interpret a statement of
a program only if it is syntactically correct.
For example , parentheses must be in pairs, so the expression
(10 +12) is syntactically correct, whereas (7 + 11 is not due to
absence of right parenthesis.
If any syntax error is present, the interpreter shows error
message(s) and stops the execution there.
Such errors need to be removed before execution of the
program.
Logical Errors
A logical error/bug (called semantic error) does not stop
execution but the program behaves incorrectly and produces
undesired /wrong output. Since the program interprets
successfully even when logical errors are present in it, it is
sometimes difficult to identify these errors.
For example, if we wish to find the average of two
numbers 10 and 12 and we write the code as 10 + 12/2,
it would run successfully and produce the result 16, which is
wrong. The correct code to find the average should have been
(10 + 12) /2 to get the output as 11.
Runtime Error
A runtime error causes abnormal termination of program while
it is executing. Runtime error is when the statement is correct
syntactically, but the interpreter can not execute it.

For example, we have a statement having division operation in


the program. By mistake, if the denominator value is zero then it
will give a runtime error like “division by zero”.
The process of identifying and removing logical errors and
runtime errors is called debugging. We need to debug a program
so that is can run successfully and generate the desired output.
Usually statements in a program are executed one
after another.

However, there are situations when we have more


than one option to choose from, based on the
outcome of certain conditions.

This can be done using if….else conditional


statements. Conditional statements allows us to
write program to do different tasks or take different
paths based on the outcome of the conditions.
Conditional Statements
Sequential Statements
Syntax of if statement:

There are three ways to write if.. else statements:


• if statement — executes the statement(s) inside if when the condition is
true.
age = int(input("Enter your age "))
if age >= 18: # use ‘:’ to indicate end of condition.
print("Eligible to vote")
• if...else statement executes the statement(s) inside if when the condition is
true, otherwise executes the statement(s) inside else (when the condition is
false)
#Program to subtract smaller number from the
#larger number and display the difference.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference of",num1,"and",num2,"is",diff)
Output:
Enter first number: 5
Enter second number: 6
The difference of 5 and 6 is 1
Python uses indentation for block as well as for nested block
structures. Leading whitespace(spaces and tabs) at the
beginning of a statement is called indentation .

In Python, the same level of indentation associates statements


into a single block of code.

The interpreter checks indentation levels very strictly and


throws up syntax errors if indentation is not correct.

It is a common practice to use a single tab for each level of


indentation.
• if...elif....else is use dot check multiple conditions and execute
statements accordingly . Meaning of elif is elseif.

Example
Check whether a number is positive, negative, or zero.

number = int(input("Enter a number: ")


if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
When the conditional statements appear, the Python
interpreter executes code inside one block that is selected
based on the condition.
Number of elif is dependent on the number of conditions to be
checked. If the first condition is false, then the next condition is
checked, and so on.
If one of the conditions is true, then the corresponding
indented block executes, and the if statement terminates.
After that, the statements outside the if..else are executed or
the program terminates if there are no further statements.
Program Examples
Program Examples
Program Examples
A function refers to a set of statements or instructions grouped under a
name that perform specified tasks. For repeated or routine tasks, we define a
function. A function is defined once and can be reused at multiple places in a
program by simply writing the function name, i.e., by calling that function.

Suppose we have a program which requires to calculate compound interest


at multiple places. Now instead of writing the formula to calculate the
interest every time, we can create a function called CalcCompInt and inside
that function we write the code to take inputs (like interest rate, duration,
principle), calculate interest, and display output.

We can simply call the function by writing the function name CalcCompInt
whenever compound interest is to be computed and thus reuse the code to
save time and efforts.
Python has many predefined functions called built-in functions. We have
already used two built-in functions print() and input(). A module is a python
file in which multiple functions are grouped together. These functions can be
easily used in a Python program by importing the module using import
command. Use of built-in functions makes programming faster and efficient.
To use a built-in function we must know the following about that function:
• Function Name — name of the function.
• Arguments — While calling a function, we may pass value(s), called
argument, enclosed in parenthesis, to the function. The function works
based on these values. A function may or may not have argument(s).
• Return Value − A function may or may not return one or more values. A
function performs operations on the basis of argument (s) passed to it and
the result is passed back to the calling point. Some functions do not return
any value.
Python has many predefined functions called built-in functions. We have
Let us consider the following Python program using three built-in functions

input(), int() and print():


#Calculate square of a number
num = int(input("Enter the first number"))
square = num * num
print("the square of", num, " is ", square)

Observe:
• Two built-in functions are used in the first statement, int() and input().
The third line has a function print().
• The input function accepts an argument, “Enter your name”. Argument(s)
is the value(s) passed within the parenthesis.
• Similarly the print function has four arguments "the square of", num, "is", square
separated by commas.
• The int function in the first line takes as argument the value entered by the user
from the keyboard and converts it into a string and returns it. Thus the return value
from the int() function is an integer.
Some of the most commonly used built-in functions in Python are listed in Table 3.8
under four broad categories.
To repeat certain things for a particular number of times. Iterative
statements are used.
For example, a program has to display attendance for every student of a
class. Here the program has to execute the print statement for every
student.

In programming, this kind of repetition is called looping or iteration, and it is


done using for statement. The for statement is used to iterate over a range of
values or a sequence. The loop is executed for each item in the range. The
values can be numeric, string, list, or tuple.

When all the items in the range are exhausted, the statements within loop
are not executed and Python interpreter starts executing the statements
immediately following the for loop.
While using for loop, we should know in advance the number of times the
loop will execute.
Syntax of the for Loop:
for <control-variable> in <sequence/items in range>:
<statements inside body of the
loop>
Program to print even numbers in a given sequence using for loop.
#Print even numbers in the given sequence
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
if (num % 2) == 0:
print(num,'is an even Number')
Output:
2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
10 is an even Number

Note: Body of the loop is indented with respect to the for statement.
The range() Function:
The range() is a built-in function in Python.

Syntax of range() function is:


range([start], stop[, step])

It is used to create a list containing a sequence of integers from the given


start value up to stop value (excluding stop value), with a difference of the
given step value.

If start value is not specified, by default the list starts from 0.


If step is also not specified, by default the value is incremented by 1 in each
iteration.
All parameters of range() function must be integers.
The step parameter can be a positive or a negative integer excluding zero.
The range() Function Example
The range() Function Example
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#start value is given as 2
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
#step value is 5 and start value is 0
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
#step value is -1. Hence, decreasing
#sequence is generated
>>> list(range(0, -9, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8]
The function range() is often used in for loops for generating a sequence of
numbers.
Program : Program to print the multiples of 10 for numbers in a given range.
Program : Program to print table of 5 .
Program : Program to print sum of natural numbers between 1 to 7.
Print the sum progressively i.e after adding each natural number ,print sum
so far.

Output
Program : Program to print sum of natural numbers between 1 to 7.

Output
A loop may contain another loop inside it. A loop inside another loop is called
a nested loop.

Program to demonstrate working of nested for loops.


for i in range(1,6):
for j in range(1,i):
print(“*”,end=‘ ‘)
print()

Output
*
**
***
****
#Demonstrate working of nested for loops
for var1 in range(3):
print( "Iteration " + str(var1 + 1) + " of outer loop")
for var2 in range(2): #nested loop
print(var2 + 1)
print("Out of inner loop")
print("Out of outer loop")
Output:
Iteration 1 of outer loop
12
Out of inner loop
Iteration 2 of outer loop
12
Out of inner loop
Iteration 3 of outer loop
12
Out of inner loop
Out of outer loop
A loop may contain another loop inside it. A loop inside another loop is called
a nested loop.

Program to demonstrate working of nested for loops.


for i in range(1,6):
for j in range(1,i):
print(“i”, end=‘ ‘)
print()

Output
?????
A loop may contain another loop inside it. A loop inside another loop is called
a nested loop.

Program to demonstrate working of nested for loops.


for i in range(1,6):
for j in range(1,i):
print(“j”, end=‘ ‘)
print()

Output
?????

You might also like