0% found this document useful (0 votes)
4 views83 pages

Python Module 1

This document serves as an introduction to Python programming, covering its features, installation, syntax, data types, and applications. It highlights Python's advantages such as being beginner-friendly, versatile, and widely used in various domains like web development and machine learning. Additionally, it provides guidance on setting up the local environment, using Python IDEs, and writing basic Python programs.

Uploaded by

pokeb14730
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)
4 views83 pages

Python Module 1

This document serves as an introduction to Python programming, covering its features, installation, syntax, data types, and applications. It highlights Python's advantages such as being beginner-friendly, versatile, and widely used in various domains like web development and machine learning. Additionally, it provides guidance on setting up the local environment, using Python IDEs, and writing basic Python programs.

Uploaded by

pokeb14730
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
You are on page 1/ 83

Learn Python

from Start to End


Unit 1
Introduction to Python Programming
Contents

⮚ Features
⮚ How to install python interpreter
⮚ Basic Syntax
⮚ Variable and Data Types
⮚ Operator
⮚ Input-Output : standard input output
⮚ Conditional Statements
⮚ Looping
⮚ Control statements
⮚ Arrays vs lists
⮚ python data structures (list, tuple, dictionary)
What is python?

▪ It Is Fastest Growing Programming Language


▪ Multi-paradigm Programming Language
▪ Interpreted Language
▪ Supports Dynamic Data Type
▪ Independent From Platforms
▪ Focused On Development Time
▪ Simple & Easy Grammar
▪ Automatic Memory Management
▪ Its Free(open Source)
Python Versions

It was created by Guido van Rossum during


1985- 1990.

✔ Python 1.0 –January 1994


✔ Python 2.0 –October 2000
✔ Python 3.0 –December 2008
Where to use Python?

Python : Areas you can implemented


Machine Learning

GUI

Software Development

Web Development

Artificial Intelligence
Why to Learn Python?

✔ Python is a high-level(machine independent), interpreted, interactive and object-oriented


scripting language

✔ Python is designed to be highly readable

✔ It uses English keywords frequently where as other languages use punctuation, and it
has fewer syntactical constructions than other languages
Popular apps developed in Python

❖YouTube
❖Google
❖Dropbox
❖Quora
❖Instagram
❖Mozilla Firefox
Key advantages of learning Python:

⮚ Python is Interpreted − Python is processed at runtime by the interpreter. You do not


need to compile your program before executing it. This is similar to PERL and PHP.

⮚ Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.

⮚ Python is Object-Oriented − Python supports Object-Oriented style or technique of


programming that encapsulates code within objects.

⮚ Python is a Beginner's Language − Python is a great language for the beginner-level


programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
Characteristics of Python

Following are important characteristics of Python Programming −


• It supports functional and structured programming methods as well as OOP.

• It can be used as a scripting language

• It provides very high-level dynamic data types and supports dynamic type
checking.

• It supports automatic garbage collection.

• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java
(General purpose programming lang).
Hello World using Python

print ("Hello, Python!")


Applications of Python
• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the
student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on
UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
• Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.
• Scalable − Python provides a better structure and support for large programs.
Local Environment Setup
Open a terminal window and type "python" to find out if it is already installed and which version is
installed.
• Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)
• Win 9x/NT/2000
• Macintosh (Intel, PPC, 68K)
• OS/2
• DOS (multiple versions)
• PalmOS
• Nokia mobile phones
• Windows CE
• Acorn/RISC OS
• BeOS
• Amiga
• VMS/OpenVMS
• QNX
• VxWorks
• Psion
• Python has also been ported to the Java and .NET virtual machines
Getting Python

The most up-to-date and current source code, binaries, documentation, news, etc., is available on the
official website of Python https://www.python.org/

You can download Python documentation from https://www.python.org/doc/. The documentation is


available in HTML, PDF, and PostScript formats.
Installing Python

Windows Installation

Here are the steps to install Python on Windows machine.

• Open a Web browser and go to https://www.python.org/downloads/.

• Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to
install.

• To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save
the installer file to your local machine and then run it to find out if your machine supports MSI.

• Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just
accept the default settings, wait until the install is finished, and you are done.
Python IDEs

✔ Pydev
✔ Pycharm
✔ Sublime Text
✔ Visual Studio Code
✔ Vim
First Python Program

Interactive Mode Programming


Invoking the interpreter without passing a script file as a parameter brings up the following prompt −

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Type the following text at the Python prompt and press the Enter −

>>> print "Hello, Python!“


Output

If you are running new version of Python, then you would need to use print statement with parenthesis
as in print ("Hello, Python!"). However in Python version 2.4.3, this produces the following result −
Hello, Python!

Hello, Python!

Python version 3.0 onwards

>>> print ("Hello, Python!“)


Basic Syntax :Python Identifiers

▪ A Python identifier is a name used to identify a variable, function, class, module or other object.

▪ An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).

▪ Python does not allow punctuation characters such as @, $, and % within identifiers.

▪ Python is a case sensitive programming language. Thus, Manpower and manpower are two different
identifiers in Python.

Here are naming conventions for Python identifiers −


• Class names start with an uppercase letter. All other identifiers start with a lowercase letter
• An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name
• Keywords cannot be used as identifiers
• We cannot use special symbols like !, @, #, $, % etc. in our identifier
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use
them as constant or variable or any other identifier names. All the Python keywords contain
lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Lines and Indentation

Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount. For example −

if True:
print "True"
else:
print "False"
Multi-Line Statements

▪ Statements in Python typically end with a new line.


▪ Python does, however, allow the use of the line continuation character (\) to denote that the line
should continue.

For example −
total = item_one + \
item_two + \
item_three

▪ Statements contained within the [], {}, or () brackets do not need to use the line continuation
character.
For example −
days = ['Monday', 'Tuesday', 'Wednesday’,
'Thursday', 'Friday']
Quotation in Python

▪ Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string.

▪ The triple quotes are used to span the string across multiple lines.

For example, all the following are legal −

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is made up of multiple
lines and sentences."""
Comments in Python

▪ A hash sign (#) that is not inside a string literal begins a comment.

▪ All characters after the # and up to the end of the physical line are part of the comment and
the Python interpreter ignores them.

# First comment
print "Hello, Python!" # second comment

Multiline comment can start and end by '''

'''
This is a multiline comment.
'''
Variables

▪ Python variables do not need explicit declaration to reserve memory space.


▪ The declaration happens automatically when you assign a value to a variable.
▪ The equal sign (=) is used to assign values to variables.
▪ The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable.

For example −

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

a = b = c = 1

a,b,c = 1,2,"john"
Standard Data Types

Python has five standard data types −


✔ Numbers
✔ String
✔ List
✔ Tuple
✔ Dictionary
Python Numbers

Number data types store numeric values. Number objects are created when you
assign a value to them.

For example −

var1 = 1
var2 = 10
Cont…

Python supports four different numerical types −


✔ int (signed integers)
✔ long (long integers, they can also be represented in octal and hexadecimal)
✔ float (floating point real values)
✔ complex (complex numbers)

int long float complex


10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9-36j
080 0xDEFABCEC 32.3+e18 .876j
BDAECBFBAEl
Python Strings

▪ Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
▪ Python allows for either pairs of single or double quotes.
▪ Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
▪ The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.
For example −

str = 'Hello World!’


print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to
5th print str[2:] # Prints string starting from 3rd
character print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Cont..

This
Hellowill produce the following result −
World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists

▪ Lists are the most versatile of Python's compound data types.


▪ A list contains items separated by commas and enclosed within square brackets ([]).
▪ To some extent, lists are similar to arrays in C.
▪ One difference between them is that all the items belonging to a list can be of different data type.
▪ The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1.
▪ The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

For example − list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john’]
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Cont…

This produce the following result −

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john’]
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuples

▪ A tuple is another sequence data type that is similar to the list.


▪ A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are
enclosed within parentheses.
▪ The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated.
▪ Tuples can be thought of as read-only lists.
For example −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john’)
print tuple # Prints the complete tuple
print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd
print tuple[2:] # Prints elements of the tuple starting from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples
Cont…

This produce the following result −

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Python Dictionary

▪ Python's dictionaries are kind of hash table type(key-value pairs).


▪ A dictionary key can be almost any Python type, but are usually numbers or strings.
▪ Values, on the other hand, can be any arbitrary Python object.
▪ Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
For example −

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales’}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
Cont…

This produce the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john’}
['dept', 'code', 'name’]
['sales', 6734, 'john']
Types of Operator

Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Python language supports the following types of


operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplies values on either side of the operator a * b = 200


Multiplication
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20

// Floor Division - The division of operands where the 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -
result is the quotient in which the digits after the 4, -11.0//3 = -4.0
decimal point are removed. But if one of the operands
is negative, the result is floored, i.e., rounded away
from zero (towards negative infinity) −
Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
If the values of two operands are equal, then the condition (a == b) is not true.
== becomes true.
If values of two operands are not equal, then condition (a != b) is true.
!= becomes true.
If the value of left operand is greater than the value of right (a > b) is not true.
> operand, then condition becomes true.
If the value of left operand is less than the value of right (a < b) is true.
< operand, then condition becomes true.
If the value of left operand is greater than or equal to the (a >= b) is not true.
>= value of right operand, then condition becomes true.

If the value of left operand is less than or equal to the (a <= b) is true.
<= value of right operand, then condition becomes true.
Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −


perator Description Example
= Assigns values from right side operands to left side
operand c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign
the result to left operand c += a is equivalent to c =c+a
-= Subtract AND It subtracts right operand from the left operand and
assign the result to left operand c -= a is equivalent to c =c-a
*= Multiply AND It multiplies right operand with the left operand and
assign the result to left operand c *= a is equivalent to c =c*a
/= Divide AND It divides left operand with the right operand and
assign the result to left operand c /= a is equivalent to c =c/a
%= Modulus AND It takes modulus using two operands and assign the
result to left operand c %= a is equivalent to c =c%a
**= Exponent AND Performs exponential (power) calculation on operators
and assign value to the left operand c **= a is equivalent to c = c ** a
//= Floor Division It performs floor division on operators and assign
value to the left operand c //= a is equivalent to c = c // a
Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.
Following table lists out the bitwise operators supported by Python language with an
example each in those, we use the above two variables (a and b) as operands −

a = 0011 1100
b = 0000 1101
-----------------

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Cont…
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both
(a & b) (means 0000 1100)
operands
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011
1101)
^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49 (means 0011
both. 0001)
~ Binary Ones (~a ) = -61 (means 1100
Complement 0011 in 2's complement form
It is unary and has the effect of 'flipping' bits.
due to a signed binary
number.
<< Binary Left Shift The left operands value is moved left by the a << 2 = 240 (means 1111
number of bits specified by the right operand. 0000)
>> Binary Right Shift The left operands value is moved right by the a >> 2 = 15 (means 0000
number of bits specified by the right operand. 1111)
Python Logical Operators

here are following logical operators supported by Python language. Assume variable a holds 10 and variable b
holds 20 then
Operator Description Example

and Logical AND If both the operands are true then (a and b) is true.
condition becomes true.

or Logical OR If any of the two operands are (a or b) is true.


non-zero then condition becomes
true.
not Logical NOT Used to reverse the logical state not(a and b) is false.
of its operand.
Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −

Operator Description Example

in Evaluates to true if it finds a variable in


the specified sequence and false x in y, here in results in a
otherwise. 1 if x is a member of
sequence y.

not in Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and results in a 1 if x is not a
false otherwise. member of sequence y.
Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
Operator Description Example

is Evaluates to true if the


variables on either side of
the operator point to the x is y, here is results in 1 if id(x)
same object and false equals id(y).
otherwise.
is not Evaluates to false if the
variables on either side of
x is not y, here is not results in 1 if
the operator point to the
id(x) is not equal to id(y).
same object and true
otherwise.
Python Operators Precedence

The following table lists all operators from highest precedence to lowest.
Sr.No. Operator & Description
1 ** 7 ^|
Exponentiation (raise to the power) Bitwise exclusive `OR' and regular `OR'
2 ~+- 8 <= < > >=
Comparison operators
Complement, unary plus and minus (method
9 <> == !=
names for the last two are +@ and -@)
Equality operators
3 * / % // 10 = %= /= //= -= += *= **=
Multiply, divide, modulo and floor division Assignment operators
4 +- 11 is is not
Addition and subtraction Identity operators
5 >> << 12 in not in
Right and left bitwise shift Membership operators
6 & 13 not or and
Logical operators
Bitwise 'AND'
Standard Input-Output

1.Python Output- print() function.


2.Python Input- input() function.
3.Output Formatting – format()
function.
Python Output- print() function.

In python, for printing something on the console or the standard output screen, we use a
simple print() function.
For example, if you want to print some messages on the console, you can print it by using a
print() function.
Syntax of print() function is- print(message)
Let’s have a look>>>x=56
in the example-
>>>print("Your age is",x)

OUTPUT-
Your age is 56.
Python Input- input() function.

Till now, we are providing value to the program, but if you want that user will give input
value, then there is a function – input().
Input() function allows users to provide the value of their choice.
Let’s take a look in the example-
>>>age= input("Tell your Age:")
Tell your Age: 25
>>>print(age)
>>>age

OUTPUT- 25
‘25’
But, here the value entered by the user as an age “25” is a string, it is not a number. Because
input () function return type is string.
For converting this into a number, int() or float() functions are there.
>>>int('25’)

OUTPUT- 25
Output Formatting – format() function.

In a normal way, we write our code in a print() statement, but we can use format()
method to make our output more attractive and structured.
Let’s see in the example, how to use format() method.
>>> num1=5
>>> num2=7
>>> print('value of num1 is{0} and num2 is {1}'.format(num1,num2))

OUTPUT- value of num1 is 5 and num2 is 7

Here {0} represents index value 0, and {1} represents index value 1.

>>> num1=5
>>> num2=7
>>> print(f'value of num1 is{num1} and num2 is {num2}')
Cont…

>>> a=3.14254678
>>> b=10.2903348
>>>print('value of a is {0:.3} and b is {1:.3}'.format(a,b))

OUTPUT- value of a is 3.14 and b is 10.3

• Here, in {0:.3} the .3 decides the decimal limit to- .3


• It prints only 3.14 which is .3 decimal place.
• If you want that it will consider 3.14 as float, then
you can write it as- {0:.3f}
Cont…

▪ The format() method formats the specified value(s) and insert them inside the string's
placeholder.
▪ The placeholder is defined using curly brackets: {}. Read more about the placeholders in the
Placeholder section below.
▪ The format() method returns the formatted string.

Syntax : string.format(value1, value2...)


Example
Using different placeholder values:
txt1 = "My name is {fname}, I'am {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'am {1}".format("John",36)
txt3 = "My name is {}, I'am {}".format("John",36)
Decision Making(Conditional Statement)

▪ Decision making is anticipation of conditions occurring while


execution of the program and specifying actions taken according to
the conditions.
▪ Decision structures evaluate multiple expressions which produce
TRUE or FALSE as outcome. You need to determine which action
to take and which statements to execute if outcome is TRUE or
FALSE otherwise.
Following is the general form of a typical decision making structure
found in most of the programming languages −

Python programming language assumes any non-zero and non-


null values as TRUE, and if it is either zero or null, then it is
assumed as FALSE value.
Cont…

1 if statements
An if statement consists of a boolean expression followed by one or more
statements.

2 if...else statements
An if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.

3 nested if statements
You can use one if or else if statement inside another if or else if
statement(s).
Single Statement Suites

var = 100
if ( var == 100 ) : print ("Value of expression is 100“)
print ("Good bye!“) ))

When the above code is executed, it produces the following result −

Value of expression is 100.


Good bye!
Loops
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement −
Cont…

Python programming language provides following types of loops to handle looping


requirements.
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.

2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.

3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

Example
Print i as long as i is less than 6:

i = 1 initialization
while i < 6: Condition
print(i)
i += 1 Increment/decrement

Note: remember to increment i, or else the loop will continue forever.


The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1.
for Loop

▪ A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
▪ This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object-orientated programming languages.
Syntax:
for variable_name in sequence:
statement_1
statement_2
....
Examples
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"] for x in "banana":
for x in fruits: print(x)
print(x)

The for loop does not require an indexing variable to set beforehand.
Cont…

The range() Function


▪ To loop through a set of code a specified number of times, we can use the range() function,
▪ The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

for x in range(6):
print(x)

Output: 0

2
Note that range(6) is not the values of 1 to 6, but the values 0 to 5.
3
Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.

1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.

3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do
not want any command or code to execute.
break statement

▪ The break statement is used to exit a for or a while loop.

▪ The purpose of this statement is to end the execution of the loop (for or while) immediately and the
program control goes to the statement after the last statement of the loop.

▪ If there is an optional else statement in while or for loop it skips the optional clause also.

Syntax :
while (expression1):
statement_1
statement_2
......
if expression2 :
break
Example

1) for letter in 'Python': # First Example


if letter == 'h':
break
print ('Current Letter :', letter)

2) var = 10 # Second Example


while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
continue Statement

▪ The continue statement in Python returns the control to the beginning of the while loop. The continue
statement rejects all the remaining statements in the current iteration of the loop and moves the
control back to the top of the loop.

▪ The continue statement can be used in both while and for loops.
Example

1) for letter in 'Python': # First Example


if letter == 'h':
continue
print ('Current Letter :', letter)

2) var = 10 # Second Example


while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print ("Good bye!“)
pass Statement

▪ The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.

▪ The pass statement is a null operation; nothing happens when it executes. The pass is also useful in
places where your code will eventually go, but has not been written yet
Example

for letter in 'Python':


if letter == 'h':
pass
print ('This is pass block’)
print ('Current Letter :', letter)

print ("Good bye!“)


List vs Array
List:
A list is a built-in Python data structure that can store a collection of items. It is
ordered, mutable, and can contain elements of different data types.

Example : Output:
my_list = [10, "apple", 3.14, True] [10, 'apple', 3.14, True]
print(my_list)

Applications: 1. Storing and manipulating mixed data (e.g., student records with ID, name, marks)
2. Creating dynamic lists from user input or file data
3. Web scraping results collection
4. Temporary storage of varied data types (e.g., settings, logs, configurations)
List vs Array
List:

Example : Output:
my_list = [2, 1, 1, 0, 2,1] [2, 1, 1, 0, 2,1]
print(my_list)

Applications:

1. Storing and manipulating mixed data (e.g., student records with ID, name, marks)
2. Creating dynamic lists from user input or file data
3. Web scraping results collection
4. Temporary storage of varied data types (e.g., settings, logs, configurations)
List vs Array
Array:
An array is a collection of items stored at contiguous memory locations, typically of the
same data type. Unlike lists, arrays are more memory-efficient and faster for numeric data
operations.

Arrays can be used via:


1.The built-in array module (basic)
2.The NumPy library (advanced and widely used in industry)

Example : Output:
import array array('i', [10, 20, 30, 40])
my_array = array.array('i’, [2, 1, 1, 0, 2, 1])
print(my_array)
List vs Array
Array:
Applications: Use in Industry:
1. Data Science & Machine Learning: Arrays using
1. Numerical computations (large datasets)
NumPy for datasets, feature matrices
2. Image processing (pixel arrays)
2. Finance: Stock data analysis, financial modeling
3. Signal processing
using numerical arrays
4. Scientific computing
3. Healthcare & Bioinformatics: Medical imaging
5. Time series or sensor data
data, ECG signal arrays
4. Engineering: Simulation data, IoT sensor
readings, CAD geometry data
5. Gaming Industry: Graphics and sound data
arrays
Example: Multiply a sequence by 2
Using List:
my_list = [1, 2, 3]
result = my_list * 2
print(result)

Output
[1, 2, 3, 1, 2, 3] # Repeats the list

Using NumPy Array:


import numpy as np
my_array = np.array([1, 2, 3])
result = my_array * 2
print(result)
Output [2 4 6] # Multiplies each element by 2
Practicals

✔ Write a python programs to understand different decision making statements,


looping & functions.

✔ Write a python programs to understand different standard input-output and File


handling operations

✔ Write program to study manipulations of strings in Python

✔ Write Python code to demonstrate handling of different data structures: Lists,


Tuple and Dictionary.

You might also like