Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Unit 1

The document provides an introduction to Python, covering its features, applications, and installation process, as well as basic programming concepts such as identifiers, keywords, and control flow statements. It highlights Python's simplicity, versatility, and extensive libraries, making it suitable for various applications including web development, data science, and automation. Additionally, it outlines the steps for installing Python and creating a simple program using an IDE.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Unit 1

The document provides an introduction to Python, covering its features, applications, and installation process, as well as basic programming concepts such as identifiers, keywords, and control flow statements. It highlights Python's simplicity, versatility, and extensive libraries, making it suitable for various applications including web development, data science, and automation. Additionally, it outlines the steps for installing Python and creating a simple program using an IDE.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Introduction to Feat ures and Applications of Pytho n; Python Versions; Installat ion of Pytho n;

Python Command Line mode and Python IDEs; Simple Python Program.

Python Basics: lde ntifiers; Keywords; Statements and Ex pressions; Variables; Operators;
Precedence and Assoc iat ion; Data Ty pes; Inde ntatio n; Comments; Built-in Functions- Console
Input and Console 0 ut put, Ty pe Conversions; Python Libraries; Importing Libraries with
Examples.

Python Control FloW: Ty pes of Control Flow; Control Flow State ments- if, else, elif, while loop,
b reak, cont inue statements, for loop State ment; range () and ex it () functio ns.

BCA-IV 1
UNIT-I

Introduction to Python:
Python is a high-leve 1, interpreted, object-oriented programming language that is
widely used for developing various types of applications including web development,
data scie nce, artificial intelligence, and automatio n.

It was created by Guido van Rossum in the late 1980s.

Features of Python:

2. xpresaiVe: Language

p t 3. lnlerpreted Lan
n

5. Free and Open


SouroB

1. Simple and easy-to-learn syntax: Python has a simple and readable sy ntax,
making it easy to learn and use, especially for beginne rs.

2. Interpreted language: Pyt lion is an interpr eted language, which means t hat it
does not requir e compilation befo re execution, making it faste r and e asie r to
de bug.

3. Object-oriented programming: Python supports obje ct-o riented progr amming,


allowing deve lo pe rs to c reate reusable and modular code.

4. Dynamic typing: Pytho n is dy namically type d, which means that variable types
are determined at runtime, allowing for more flexible and adaptable code.

5. Extensive standard library: Pyt lio n comes wit li a large standar d library that
provide s a wide range of tools and modtiles for various tasks, from handling
regtilar expressions to netw ork pro gramming.

5. Cross-platform: Pyt lion code c an be run on multiple operating systems,


including Windows, L inux, and maco S, making it a versatile language for
deve loping applicatio ns.

B CA- IV
UNIT-I

7. Large and active community: Python has a large and active community of
deve lopers who co ntribtite to o pen-source projects and provide suppor t to
beginne rs.

8. Third-party packages: Python has a va st collectio n of third-party packages


available on the Pyt lion Package Iride x (PyPI) t hat can be easily installed using
the pip package manager, making it easy to add functionality to your code.

9. High-level language: Python is a high-level language, meaning it provides


abstractions that simplify complex tasks and make it easier to write code.

1.0. Integration capabilities: Pyt lion ran easily inte grate with other languages and
technologies, including C/C++, Java, and .NET, making it a popular choice for
deve loping applications wit li dive rse ter linology stacks.

Applicafions of Python:
1. Web development: Python is widely used for web develop me nt, with po pular
web framew orks suc li as Django and Flask that allow developers to create
dy namic and scalable we b applications.

2. D ata science: Pytlion is a popular language for data science and macliine
learning, wit li librarie s sticli as N umPy, P andas, and Scikit-learn t liat provide
powerftil tools for data analysis and inacliine learning.

3. Scientific computing: Pyt ho n is widely used in scientific co mptiting, with


libraries such as SciPy, Mat plotlib, and IPython that provide tools for scientific
and engine ering calculations.

4. Artificial intelligence and robotics: Pytho n is used in artificial inte lligerice and
robotics, wit li libraries such as TensorF low, Keras, and PyTorcli t hat provide
powerftil tools for deep le arning and artificial intelligerice.

5. Desktop applications: Pyt lion can be used to create desktop applications using
tools such as Py Qt, wxPyt hon, and Py GTK.

6. Game development: Pyt hon can be used in game deve lo pme nt, wit li libraries
such as Py game that pro vide too1s for creating 2D games.

7. Automation: Python can be used for automation tasks, with tools such as
Selenium and Beatitiful Soup that pro vide web scraping and automation
c apabilities.

8. Scripting: Pyt lion is widely used for scripting tasks, wit li too1s such as Fabric
and Ansible that pro vide automation capabilities for system administration and
netwo rk manage ment.

B CA- IV 3
UNIT-I

Python Versions:
The curre nt stable version of Python as of my knowledge ctito ff date (Septembe r 202 1)
is Pyt lion 3.1 1.2, which was released on 0 cto ber 4, 2.0.2.1. Some of the major versions of
Pyt lion include:

1. Python 1.x: The first version of Python, which was re le ased in 19.9.1.

2. Python 2.x: The second major version of Pytho n, which was released in 2.0.0.0. It
was wide ly used for many years, but its development was discontinued on
January 1, 2.0.2.0.

3. Python 3.x: The third major ve rsion of Pytho n, which was released in 2.0.0.8. It
introduced many new features and impro vements, but also introduced some
bac kward- inc ompatible changes. Pyt lion 3.x is the current and reromme rided
versio n of Pyt lio n for new develo pme nt.

Each major versio n of Python has multiple minor versions, which include bug fixes, improve
me nts, and new fe attires. For example, Pytho n 3. 7, Python 3.8, Pytho n 3.9, and Python
3.10 are all mino r versions of Python 3.x, with earli version introducing new features and
improvements.

lnstallafion of Python:
To install Pyt lion on your c omptite r, you can fo llow t liese general steps:

1. Go to the official Python website at python.org and downlo ad the latest ve rsion
of Pyt lio n that is compatible wit li yo tir operating system (Windows, Mar, or
L inlix).
L ink : https:/ /www.uvthon.o rz/ downloads /

2. Run the downloaded installation file and fo llow the installation wizard. Make
sure to select the optio us yo u want, such as adding Pytho n to your system path
or installing I liird-party libraries.

3. 0 rice the installation is complete, ope n a command prompt (Windows) or


terminal (Mac/Linux) and type python to start the Pytho n interprete r. If Python
is installed correctly, yo ti should see the Python prompt (>>>) in the command
prompt/terminal window.

You can also use a text editor or integrated development environme nt (IDE) to write
and run Python code. Popular text edito rs and ID Es for Pytho n include Visual Studio
Code, PyCharm, Tlionny, Python ID LE, Atom, and S ublime Text.

B CA- IV 4
UNIT-I

IDE: Python Command Line mode and Python IDEs;

Default IDEs:

0 pen cmd -> Type py or Pyt lio n


0 pen ID LE (P yt ho n 3.11)

O ther IDEs ->

Tlionny ( L ink: littus: / /zithub. rom /thoririv /tlio ririv / releases /taz/v4.0.2)
Pyc harm
Vistial Sttidio Code
S tiblime Text

Simple Python Program.


An example of a simple Pyt lion program t hat you can create and run using the Tlionny
IDE:

1. 0 pen Tlionny ID E and create a new file by clic king on 'F ile' > 'New' or using the
keyboard shortcut Ctrl+ N (Windows/Linux) or Command +N (Mar).

2. Type the following code into the new file:

# This is a simple Python program


print('H ello, w orld!')

3. Save the file by clic king on 'File' > 'Save' or using the keyboard slio rtctit Ctrl+S
(Windows/L inux) or Command +S (Mac). Clioo se a filename and lo ratio n on yo
tir c omptiter to save the file.

4. Run the program by clic king on 'Run' > 'R tin curre nt script' or using the
keyboard shortcut F5. This will open a new window calle d 'Slie11' at the botto m of
the IDE and display the out put of the program, which slio uld be 'Hello, world!'.

B CA- IV 5
UNIT-I

Python Basics: some of the basic concepts we must practice are,

1. Ide ntifie rs
2. Keywo rds
3. Statements and Expressions
4. Variables
5. 0 perat ors
6. P recede rice and Association
7. Data Types
8. Iride ntation
9. Comme nts
1. Iden tifiers: Ide ntifie rs in Python are name s given to variables, ftinctio us, classes,
modtiles, and other o bjects in the code. An identifie r is a sequence of letters, digits, and
tmdersco res ( ) t hat be gins wit li a letter or tmderscore.

Rules for naming identifiers in Python:


1. An ide ntifie r must start with a letter (a to z, A to Z) o r underscore ( ) character.
2. The second character onwards, it can have letters (a to z, A to Z), digits (0 to 9),
o r underscore ( ) character.
3. P yt lion identifiers are case-sensitive. For example, my var and My Var are two
diffe rent identifiers.
4. T here are some reserved words that cannot be used as identifiers, such as if, else,
while, fo r, and, or, not, class, def, import, from, in, is, try, exce pt, raise, wit li, and
yield.
5. I de ntifiers can be of any length, but it is rec omme ride d to keep t Item short and
me aningftil.
6. Avoid tising special cliaracters suc h as !, @, #, $, %, ^, &, *, (. ) -. + - I. 1 [. ] l \. :
, ', ”, <, >, „ ., ?, / in ide ntifie rs.
Validation ->

Keyw ordS: Keywords in Pyt lion are reserved words that have a special meaning,
functionality and pin po se in the language.

They are used to define the syntax and structure of the code and cannot be use d as
variable names or identifie rs. Pyt ho n has 3.5 keyw ords, as of versio n 3.10:

B CA- IV 6
UNIT-I

Statements: a state me nt is a unit of code t hat performs a specific action. A pro gram is
made tip of one or more statements. A statement can be a single line of code or a group
of lines of code t hat pe rform a specific task.

1. Assignment statements: Assign a value to a variable. F or example, x = 5.


2. Conditional statements: Control the flow of exectitio n based on a condition. For
example,
if x > 0:
print(”x is positive”).
3. Looping statements: Repeat a blo ck of code while a ro ndition is true. For
example,
while x > 0:
print(x);
x -= 1.
4. Function and method calls: Call a funr tion or metlio d to perfo rm a specific task.
F or example,
print(”H ello, Wo rld!”).
5. Import statements: Import modules or specific functions from modtiles. For
example,
import math oi from ra ndo m import rand int.

Expressions: an expre ssion is a rombination of value s, variables, o perators, and


ftinctio ri calls t liat prod tices a restilt.

An expression can be as simple as a single valtie or as complex as a multi- level function


c all that uses variables and operato rs to maniptilate data.

Here are some examples of expressions in Python:

1. Numeric expressio us: 2 + 3, 5 * 5, 10 / 2, etc.


2. String expressions: ”H ello, ” + ”World!”, ”Pyt lion” * 3, etc.
3. Boolean expre ssions: 5 > 3, x == 10, etc.
4. Variable expressions: x, y + 5, z * (x + y), etc.
5. F tinction call expressio us: len(”H ello”), math.sqrt(2 5), etc.

In Python, expressio us are evaluated to produce a value. The value of an expression can
be stored in a variable or used in other expressions or statements.

B CA- IV 7
UNIT-I

Var tables: a variable is a named locatio n in memory that stores a value. The value of a
variable can be change d during the execution of a program. Variables can be used to
store differe nt types of data, including numbe rs, strings, and boolean values.

To create a variable in Pyt lion, yo ti simply clio ose a name for the variable and use the
assign ment o perator (=) to assign a value to it. Here are so me examples:

x=5 # x is assigned the value 5


y = ”Hello” # y is assigned the string value ”He llo”
z = Trm e # z is assigned the boo le an value True

O perators: 0pe rators in Pytlio n are symbols or special keywords that perfo rm
o perations o n valties or variables. Pytlio n stippo rts a wide range of o pe rators,
including

1. Arit hmetic operator s


2. Comparison o perators
3. Logical operato rs
4. B itwise operato rs
5. Assign ment operators.

1. Arithmetic operators: + (addition), - (stibtractio n), * (multiplication), / (division),


% (modulus) , ** (expone ntiation), // (floor divisio n)
2. Comparison operators: == (equal to), != (not e dual to), < (less than) , > (gre ater
than), <= (less t Iran or e qtial to), >= (greater than or equal to)
3. Logical operators: and, or, not
4. Bitwise operators: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), (bitwise
NOT), << (left shift), >> [right shift)
5. Assignment operators:
= (simple assignment) ,
+= (addition assign me nt),
(subtraction assign me nt),
*= (multiplication assignment),
/= (division assignment) ,
%= (modulus assign me nt),
**= (expo nentiation assignment),
//= (floor division assignment)

B CA- IV 8
UNIT-I

Example code:

x = 10

# Arithmetic operators
print(x + y) # outputs 13
print(x - y) # outputs 7
print(x * y) # out puts 30
print(x / y) # outputs 3. 3333333333333335
print(x % y) # outputs 1
print(x ** y) # o ut puts 1000
print(x // y) # o ut puts 3

# Comparison o perators
print(x == y) # outputs False
print(x != y) # o ut puts True
print(x < y) # outputs False
print(x > y) # outputs True
print(x <= y) # outputs False
print(x >= y) # outputs True

# Logical operato rs
a = Tr tie
b = False
print(a and b) # outputs False
print(a or b) # outputs Tr tie
print(not a) # out puts False

# B itwise operators
m = 60 # 60 = 0011 1100
n = 13 # 13 = 0000 110 1
print(in & n) # outputs 12 (12 = 0000 1 100)
print(= I n) # o lit puts 61 (61 = 001 1 1101)
print(in ^ n) # o ut puts 49 (49 = 0011 0001)
print(-m) # outputs -6 1 (-6 1 = 1100 00 11)
print(m << 2) # outputs 2 40 (2 40 = 1111 0000)
print(m >> 2) # outputs 15 (15 = 0000 1111)

# Assignment operators
x+=5

B CA- IV 9
Python Programming

print(x) # outputs 15
print(y) # o tit puts 6

Precedence and Associafion:

Precedence refers to the order in which o pe rators are evaluated. 0 per ato rs with higher
precede rice are evaluated first, while ope rators wit li lowe r precede rice are evaluated
later.

multiplication (*) Iras a liiglie r precede rice t han addition (+), so in the expression 3 + 4 *
5, the multiplication is performe d first, giving 3 + 2.0, wliir li evaluates to 2.3.

Here's a table of the o perat or prece de rice in Pyt lion, fro m highest to lowest:

Association re fers to the order in which operators with the same precede rice are
evaluated. 0 perato rs can be le ft-associative (evaluated from left to right) or right-
associative (evaluated from right to left).

F or example, the addition operator (+) is le ft-associative, so in the expression 3 + 4 + 5,


the leftmo st + is evaluated first, giving (3 + 4) + 5, which evaluates to 12.
UNIT-I

Data Types: Python has several built-in data types that are used to represent
diffe rent kinds of data.

Numeric

Boolean

Sst

Sequence
Type

1. Numeric : N timeric data types:

int: inte ger s, for example 42 or -3.


float: floating-point num be rs, for example 3.14 or -0.5.
complex: complex numbers, for example 1 + 2j or -3j.
2. Dictionary : Mapping data type: dict
dict: tinorde red co llection of key-value pairs, for example {'name': 'John', 'age': 30}.

3. Boolean : boot
boo1: repre se nts truth values, e itlier True or False.

4. Set: set
set: tinordered collection of unique items, for example {1, 2, 3} or {'apple', 'banana',
'clierry'}.

S. Sequence Type:

list: ordered and mtitable collection of items, for example [1, 2, 3] or ['apple', 'banana',
'cherry'].
tuple: ordere d and immutable collectio n of items, for example ( 1, 2, 3) or ('apple',
'banana', 'cherry').
range: immutable seqtie rice of numbers, for example range(0, 10, 2) re presents the
sequence 0, 2, 4, 6, 8.
String:
str: a string of c liaracters, for example ”Hello, world!” or 'Python is fun'.

B CA- IV 11
UNIT-I

I nd en tation : In Python, indentation is used to indicate a block of code. Python does


not use r tirly braces or ot lie r symbols to indir ate the be ginriing and end of a blo ck
of c ode, instead it uses indentatio n to group statements into a blo ck.

The standar d indentation in Python is four spaces.

Commen Is: In Pyt lion, romments are used to add explanatory or informative note s to
your code. Comments in Pyt lio n are not execute d by the interpreter, and they are
ignore d when the program runs.

To add a co mment in Python, yo ti can use the # symbol. Everyt liing t hat comes after the
# symbol on a line is co nside red a co mme nt and will be ignored by the interpr ete r. For
example:

# T his is a roimne nt in Pyt li on


print(”H ello, w orld!”) # T his is also a roinrne nt

single- line co mments start wit li the # sy mbo1 and are used to provide brief explanations
of the code. They are often used to make the code mo re readable and tmde rstandable to
other programmers who may be working on the c ode. Single-line ro mments can appear
on the ir own line or at the end of a line of c ode.

M tilti-line co mme nts in Pyt ho n are also known as docstrings. They are used to provide
mo re detailed explanations of the code and are typically used for docume uting
functio us, rlasse s, and modules. Multi-line comments start and end with three double
quotes (”””) and can span multiple lines.

This is a multi-line comment.

It can span multiple line s and is often used to

provide detailed explanations of functio us, classes, and mo dules.

B CA- IV 12
UNIT-I

Func tions: A function is a block of reusable code that performs a specific task.
F tinrtions help to make yo tir rode more modular, reusable, and easier to read and
maintain.

To define a function in Pyt lion, you use the def ke yw ord followe d by the name of the
functio n, the input paramete rs (if any) , and a colo n (:). The body of the function is t lien
indented, and can contain any valid Pyt lio n code.

hX:

de f add numbers(a, b) :
resii lt = a + b
rettn n re stilt

Built-in Func fions:


Pyt lion comes with several built-in functions that are available for use wit lio tit the
need to impo rt any external libraries. The se functions are built into the Pyt lion
interpr eter and can be used to perform a wide range of co mmon tasks. Here are some
examples of built-in functions in Pyt lion:

print(} : This function is used to display o ut put to the console.

input(): This function is use d to get input from the user t lirotigli the console.

len(): This function is use d to get the lengt li of a seque rice such as a string, list, or tuple.

type(): This function is used to get the type of a Python object.

int(), float(), and str(): Tliese functions are use d to co nve rt o bjects to inte ge rs,
floating-po int numbers, and strings, respectively.

range(): This functio n is used to generate a sequence of numbe rs.

max() and min(): Tliese functions are use d to get the maximum and minimum values
in a sequence, respective ly.

sum[): This function is used to get the sum of all the elements in a sequence.

sorted() : This function is used to sort a sequerice.

abs(): This function is used to get the absolute value of a ntimbe r.

BCA-IV 1.3
UNIT-I

Console Input and Console Output:


Console input and out put are essential aspects of many Pyt lio n pro grams. They allow
users to interact with the program and pro vide input, and t hey allow the pro gram to
display out put to the user. He re's how to perfo rm co nso le input and out put in Python:

Console Output:

To display output to the console in Pyt lio n, you can use the print() function. The syntax
for print() is as follows:

print(value1, value2, ..., sep=’ ', end='\n', file=sys.stdout, flush=FaIse)

Here, value1, value2, etc. are the values t hat you want to display. You can pass any
number of values to the print() ftinctio n, se parated by commas. The sep argtime nt is
used to specify the se parator between the value s (default is a single space). The end
argume nt is used to specify what to appe nd at the e nd of the o tit put (default is a ne
wline c liaracter).

Examples:

# Mii ltiple values example


a = 10
b = 2.0
pi int(”a = ”, a, ”b = ”, b, sep= ' I ', end= '\n\n')
print(”The sum of a and b is:”, a + b)

Console Input:
To get input from the console in Pyt lio n, you can use the input() function. The syntax for
input() is as fo llows:

input([prompt])
H ere, pro mpt is an o ptional string that is displayed to the use r before in put is requested.
Whe n the input() function is called, the user will be prompted to e nter a value, and that
value will be returne d by the function.

Example:

# S iinple console input example


name = input(”E riter yoIn name: ”)
pi int(”H ello, ” + name + ”!”)

B CA- IV 14
UNIT-I

Type Conversions: Conversion of one data type to anot lie r using type conve rsion
functio us. Here are some common type co nversio n functions in Python:

int() : T his function is used to convert a value to an integer.

float() : T his function is used to convert a value to a flo ating- point number.

str() : T his function is used to convert a value to a string.

boo1() : This functio n is used to conve rt a value to a boolean (T rue or False) value.

Example:

# co nve rting to integer


ntim str = ”10”
nnm int = int(num str)
print(type(nmm int)) # 0 utput: < class 'int'>

# co nve rting to float


hmm stl’ = ” 10.5”
ntim float = float(num str)
print(type(nma float)) # 0 utput: <class 'float'>

# co nve rting to string


nma int = 10
nilm str = str(ntim int)
print(type(ntim str)) # 0 utput: <r lass 'str'>

# co nve rting to boo le


an num = 10
boo1 val = bool(rim m)
print(bo ol val) # 0 tit put: True

B CA- IV 15
Python Libraries: Pyt lion libraries are colle ctions of pre -writte n code that provide a
set of functio us and tools t hat yo ti can use in your Python programs. Pytho n has a large
and active community of develo pe rs, which has led to the rreatio n of a vast numbe r of
libraries covering a wide range of applicatio us. He re are some of the mo st po pular
Pyt lion libraries:

NumPy: NiimPy is a library for working with large, multi-dime nsio nal arrays and
matrices, and provides a wide range of mat lie matical functio us to operate on them.

Pandas: Pandas is a library for data analysis and maniptilation, providing tools for
handling tabular data, time serie s, and mo re.

Matplotlib: Matplot lib is a libr ary for c reating static, animated, and interactive
vistializatio us in Pyt lio n, and provides a wide range of customizable plot type s.

SQLIte: for interaction with SQL ite database s.

Impor fing Libraries with Examples.


In Python, libraries are collections of pre-existing code that allow you to perfo rm
specific tasks without having to write the code fro m scratch. He re are some examples of
how to impo rt commonly use d libraries in Python:

N umPy: N timPy is a libr ary use d for ntimerical operations and scientific computing.
You c an import it with the following command:

Example:

import ntimpy as np
# Creating an array
my array = np.array( [1,2,3,4])
print(”Arra U sing ntimpy : ”,rny array)

BCA-IV 1.6
Python Con trot FloW: Python contro 1 flow allows yo ti to contro 1 the orde r of
execution of the code based on certain ro nditions or events. The re are several ways to
implement control flow in Pyt lion:

Types of Control Flow;

Branching statements/Control Flow Statements/conditional


statements

1. Îf: The if state me nt is use d to cliec k if a condition is true, and exectite a block of
code if the co ndition is true. He re's an example:

x=5
if x > 0:
print(”x is positive”) #out put x is positive

2. if else: The if else statement is used to execute one block of code if a condition is
true, and another block of code if the condition is false. He re's an example:

bX:

x = 10
if x > 5:
print(”x is greate r tlian 5”)
e lse:
print(”x is less t han or equal to 5”)

3. if elif else: elif ladder:


In Python, the elif ladde r is a construct that allows yo ti to chain multiple if and else
state me nts toget her. The elif state me nt is short for ”else if,” and it allows you to clie
ck for additional conditions afte r the initial if statement.

U sing an e lif ladder can be a more e fficient way of testing multiple conditions than using
separate if statements for each co ndition.

hX:

x = 10
if x > 2.0:
print(”x is great er than 20”)
e lif x > 15:
print(”x is great er than 15 but less than or equal to 2.0 ”)
e lif x > 10:
print(”x is great er than 10 but less t han or eEu al to 15”)
e lse:

BCA-IV 1.7
print(”x is less t han or eqdial to 10”)
I terations/Looping: iterations or loo ps are used to execute a block of code
repeatedly. The re are two main types of loops in Pyt lion: for loops and while loo ps.

4. while loop: A while loop is used to execute a blo ck of code repeatedly as long as a
c ertain condition is true.

Syntax:

while condition:
# code blo ck to be executed

c ount = 0
while roii nt < 10:
print(rotmt)
count += 1
5. ION IOO/: The for loop in Python is use d to iterate over a sequence (such as a list,
tuple, or string) and execute a block of code for e acli item in the sequerice. The basic
syntax of a for loop is as follows:

Syntax:

for variable in seque nre/range() :


# c od e block to be exectited

fruits = [”apple”, ”banana”, ”clie rry”]


for fruit in fruits:
print(fruit)

6. break: the break statement is used to imme diately exit a loop, regardless of whether
the loop's conditio n has been satisfied or not. Wlie n the break statement is
executed inside a loop, the loop is terminate d and the program continues executing the
code after the loop. Syntax:

while condition:
# c ode block
if so me ronditio n:
break
# mo re rode

BCA-IV 1.8
i=0
while i < 10:
print(i)
i + -- 1
if i == 5:
break
Output:

7. confinue statements: the continue statement is used to skip over the current
iteration of a loop and move on to the next iteration. Wlie n the co ntintie statement is
executed inside a loop, the code in the loo p's body that follows the continue statement is
skipped, and the loo p pro ceeds wit li the next iteration.

syntax of the co ntintie state me nt:

while condition:
# c od e blor k
if so me conditio n:
continue
# mo re code

i=0
while i < 10:
i + -- 1
if i % 2 == 0:
continue
print(i)
Output:

range () and exit () functions:


range() : The range() function is used to gene rate a sequerice of numbe rs. It returns a
sequerice of number s starting fro m 0 (by default) and incre ments by 1 (by default), and
stops before a specified ntimbe r.

Syntax:

range (sto p)
range (start, stop, step)
Example:
for i in range(5) :
print(i)

Output:

19
exit() : The exit() function is use d to immediately te rminate the Pytho n inte rpreter. It
takes an o ptional integer argument that can be used to specify an exit status.

E x:

print(”B efore exit”)


exit()
print(”Aftei exit”)

20

You might also like