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

Python_UNIT1_Finalversion

This document provides an overview of the Python programming language, covering its history, features, and applications. It explains key concepts such as identifiers, keywords, indentation, and the use of comments, as well as input/output operations and operators. The document serves as a foundational guide for understanding Python's syntax and functionality.

Uploaded by

Vinay RVIC
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 views19 pages

Python_UNIT1_Finalversion

This document provides an overview of the Python programming language, covering its history, features, and applications. It explains key concepts such as identifiers, keywords, indentation, and the use of comments, as well as input/output operations and operators. The document serves as a foundational guide for understanding Python's syntax and functionality.

Uploaded by

Vinay RVIC
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/ 19

1

UNIT-I

PARTS PYTHON PROGRAMMING LANGUAGE

Sahana patil | |VHD college


2

Introduction to Python: Python is a high-level, interpreted programming language that


emphasizes code readability and simplicity. It is widely used in areas such as data science, web
development, and automation.
Python is dynamically typed, meaning that the type of a variable is determined at runtime
rather than at compile time. This makes Python code more flexible and easier to write.

History of Python (FYI)


Python is a high-level, interpreted programming language that was created by Guido van
Rossum in the late 1980s. The language was named after the Monty Python comedy group,
with van Rossum stating that he wanted to choose a name that was "short, unique, and slightly
mysterious."

Python was first released in 1991, and its initial purpose was to serve as a scripting language
for UNIX/C programmers. The language quickly gained popularity due to its simplicity, ease of
use, and readability, and it was adopted by many programmers and organizations around the
world.

Today, Python is widely used in a variety of applications, including web development, scientific
computing, data analysis, artificial intelligence and machine learning, and more. Its popularity
continues to grow, and it is considered to be one of the most popular programming languages
in the world.

1.1.1 Features of Python


Python is a high-level, interpreted programming language that has many features,
including:

1. Easy-to-learn syntax: Python has a simple and easy-to-learn syntax that makes it an
excellent language for beginners to learn programming.
2. Object-oriented programming: Python supports object-oriented programming, which
allows developers to write code that is modular, reusable, and easy to maintain.
3. Easy to learn and Read
Python code looks like simple English words. There is no use of semicolons or brackets, and
the indentations define the code block. You can tell what the code is supposed to do simply
by looking at it.
4. Easy to maintain: Python’s source code is fairly easy to maintain
5. Python is interpreted: When a programming language is interpreted, it means that the
source code is executed line by line, and not all at once. Programming languages such as
C++ or Java are not interpreted, and hence need to be compiled first to run them. There is
no need to compile Python because it is processed at runtime by the interpreter.
6. Interactive Mode: In the interactive mode as we enter a command and press enter, the
very next step we get the output. Interactive mode is very convenient for writing very
short lines of code. [FYI: The other mode is Script mode a python program can be written
in a file. This file can then be saved and executed using the command prompt.]
7. A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
8. Python is Interactive: One can enter through python prompt with the interpreter directly
to write programs
9. Portable: Python can run on various hardware/software platforms and has same interface
on all platforms.
10. Extendable: One can add low level-modules to the python interpreter. These modules
enable programmers to add or customize their tools more efficiently.
Sahana patil | |VHD college
3

11. Databases: Python provides interfaces to all major commercial databases.


12. 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 etc.
13. Scalable: Python provides a better structure and support for large programs than shell
scripting.
14. Python provides very high-level dynamic data types and supports dynamic type checking.

Question: Python is an interpreted language. Justify


• When a programming language is interpreted, it means that the source code is executed
line by line, checks for syntax errors, and executes each line as it is encountered.
• As we know the computer can’t understand our language, it can only understand the
machine language i.e., binary language. So, the Python interpreter converts the code
written in python language to the language which computer hardwareor system can
understand. It does all the time whenever you run your python script.
• There is no need to compile Python because it is processed at runtime by the
interpreter.
• The Python interpreter first reads the command, then evaluates the command,prints
the results, and then again loops it back to read the command and because of this only
Python is known as REPL i.e., (Read, Evaluate, Print, Loop).

For example, consider the following Python code:


x=5
y = 10
print(x + y)
When this code is executed, the interpreter reads the first line and assigns the value 5 to the
variable x. Then, it reads the second line and assigns the value 10 to the variable y. Finally, it
executes the third line, which adds the values of x and y and prints the result to the console.

1.1.2 Applications of Python


1.Education post Industry
Administration, Homeland
security, public safety, Traffic
control, urban infrastructure.
2.Consumer goods industry,
Aviation, Medical, Industrial,
Financial services, GIS and
mapping, Marine
3.Customer relationship
management (CRM), E-
commerce
4.Biology, Geography,
language processing,
Astrology.
5.Data science, AI, natural
language generation, Neural
networks

Sahana patil | |VHD college


4

1.1.5 identifiers

A Python identifier is a name used to identify a variable, function, class, module orother object.
Rules of identifiers:
1. An identifier starts with a letter A to Z or a to z or an underscore(_)
2. If the identifier name is more than one character, the first character may be followed by zero
or more letters, underscores and digits (0 to 9).
3. Keyword cannot be used as identifier names
4. Python does not allow punctuation characters such as @, $, and % within identifiers.
5. Python is a case sensitive programming language.
Thus, Manpowerand manpower are two different identifiers in Python.

Here are naming conventions for Python identifiers −


1. Class names start with an uppercase letter. All other identifiers start witha lowercase letter.
2. Starting an identifier with a single leading underscore indicates that the identifier is private.
E.g., _sum
3. Starting an identifier with two leading underscores indicates as strongly private
identifier.
E.g., __sum
4. If the identifier also ends with two trailing underscores, the identifieris a language-defined
special name. E.g., foo__

1.1.6. Keywords
• A python keyword is a reserved word which you can’t use as a name of your variable,
class, function etc.
• These keywords have a special meaning and theyare used for special purposes in
Python programming language. For example– Python keyword “while” is used for
while loop thus you can’t name a variable withthe name “while” else it may cause
compilation error.
• All the keywords contain lower case letters only except True, False and None.
• The following code can retrieve the keywords in python at the prompt:
>> import keyword
>>print(keyword. kwlist)
[FYI]
Here's what each line of the code does:
1. import keyword - This line imports the keyword module into the current Python session.
The keyword module provides a list of all the keywords in the Python language.
2. print(keyword.kwlist) - This line prints out the list of Python keywords using the kwlist
attribute of the keyword module. The kwlist attribute contains a list of all the keywords
in Python.
When you run this code, you should see a list of the following keywords printed out to the
console:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

1.1.7 Lines and Indentation


In Python, lines and indentation are essential elements of the language's syntax.
Lines: Python programs are made up of a series of statements, and each statement typically
occupies a single line of code. However, a statement can span multiple lines if it is enclosed in
parentheses or brackets.

Sahana patil | |VHD college


5

For example, the following code creates a list of numbers on a single line:
numbers = [1, 2, 3, 4, 5]
The same list can also be created over multiple lines using parentheses:
numbers = (
1,
2,
3,
4,
5
)
Indentation: Unlike many other programming languages that use curly braces or other symbols
to delimit blocks of code, Python uses indentation.
• Indentation is used to indicate the scope of statements within a block of code.
• For example, the following code defines a function called multiply that takes two
arguments:
def multiply(x, y):
result = x * y
return result
• Here the result variable and the return statement are indented under the def
statement. This indentation tells Python that these statements are part of the
function's code block.
• Indentation must be consistent throughout a Python program. Typically, four spaces
are used for each level of indentation. Mixing tabs and spaces for indentation is not
allowed and can lead to errors in your code.
1.1.8 Statements

• A Python statement is an instruction that the Python interpreter can execute.


[There are different types of statements in Python language as Assignment statements,
Conditional statements, Looping statements, etc. The token character NEWLINE is used to
end a statement in Python. It signifies that each line of a Python script contains a statement.
These all help the user to get the required output.]

• Python allows the line continuation character(\) to denote that the line should
continue.
For example:
>>>> a=1+2+3+\
4+5+6
>>>>print(a)
Statements contained within the [] ,(),{} brackets do not need to use the line continuation
character.
>>>>a=(1+2+
3+4)
>>>>colors=[‘red’,’blue’,
‘green’]

Multiple statements on a single line


The semicolon(;) allows multiple statements on a single line, given that neither statement
starts a new code block.
>>a=1;b=2;c=3
>>print(a,b,c)
Sahana patil | |VHD college
6

Multiple statement groups as suites


A group of individual statements, which make a single code block are called suites in Python.
Compound or complex statements, such as if, while, def, and class require a header line and a
suite.
Header lines begin the statement (with the keyword) and terminate with a colon (: ) and are
followed by one or more lines which make up the suite.
example
if expr1==True:
stmt1
stmt2
elif expr2==True:
stmt3
stmt4
else:
stmt5
stmt6
1.1.9 Quotation in python
Quotation symbols are used to create string object in Python. Python recognizes single, double
and triple quoted strings. String literals are written by enclosing a sequence of characters in
single quotes ('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""").
1.1.10 Comments in python

• Comments in python describes what the source code has done. They are for
programmers to have better understanding of a program.
• It explains the basic logic behind why a particular line of code was written. Comments
can be used to prevent execution when testing code.
• Comments in Python are identified with a hash symbol, #, and extend to the end of the
line. Hash characters in a string are not considered comments, however. There are
three ways to write a comment - as a separate line, beside the corresponding statement
of code, or as a multi-line comment block.
Single-Line Comments
• Single-line comments begin with the “#” character. Anything that is written in a single
line after ‘#’ is considered as a comment.
• The syntax for writing single-line comments is:
# comments here
Multi-Line Comments
• Multiline comments can also be given as triple quoted string.
• It can also be used for long comments in code.
• As the name suggests its syntax consists of three consecutive single or double-quotes.

Syntax: “”” string””” or ”’ string”’

Sahana patil | |VHD college


7

1.1.11 Variables
1. Variable is a name which is used to refer memory location.
2. Python variable is also known as an identifier and used to hold value.
3. Python has no command for declaring a variable.
4. A variable is created the moment the value has been assigned to it.
5. In Python, we don't need to specify the type of variable because Python is a infer language
and smart enough to get variable type.
6. Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.
7. It is recommended to use lowercase letters for the variable name. Rahul and rahul both are
two different variables.

Variable assignment
variables do not need to be declared with any particular type, and can even change type after
they have been set.
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Multiple assignment: Python allows you to assign values to multiple variables in one line:
Example 1:
>>>x, y, z = "Orange", "Banana", 10
print(x)
print(y)
print(z)
Example2:
>>>x=y=z=10
print(x)
print(y)
print(z)

1.1.12 Input, Output and Import statements


Displaying the output:

• Python print() function prints the message to the screen or any other standard
output device.
• The Syntax of print function is:
print(EXPRESSION)
Here EXPRESSION is the variable of any data type or string value that we
want to display.
• print() automatically inserts a new line character at the end.

• String values:
print(“welcome to python”) // pair of double quotes
print(‘welcome to python’) // pair of single quotes

• Numeric values :
print(10) //Integer
print(2.55) //float value
Sahana patil | |VHD college
8

print(2.35E5) //output 235000.0 float value in scientific notation


print(True) //Boolean values
print(2+4i) //Complex numbers-2 is real part and I is imaginary

Output formatting: Format the output to make it look attractive.


• The str.format() method is used to format the output.
• Example1:
>>x=5;y=10;
Print(x,y)
5 10
The output of the above example can be formatted using {} called placeholders as
follows:
Print(‘The value of x={} and y={}’.format(x,y)) #default palceholders 0 and 1
The value of x=5 and y=10
Now,when placing value inside the curly braces,
Print(‘The value of x={1} and y={0}’.format(x,y))
The value of x=10 and y=5
Reading the Input

• Python provides built-in functions to read a line of text from standard input, which by
default comes from the keyboard. These functions are raw_input function is not
support by python3.
• The syntax for input() is: Input([prompt])
• Example:
Number=input(“Enter a number:”);
Print(“The number is:”,number)
Output:
Enter a number :20
The number is:20

Import statement
“Segments of code” frequently used are stored in a module. The module contains python
definitions and statements with the extension .py. These definition’s inside a module can be
imported to another module with the help of the ‘import’ keyword.
Example:
>> import math
>> print(math.pi)

1.1.13 Operators
Operators are used to perform operations on variables and values.
sum=b+c here b and c are called the operands and + = are called operators
Python contains the following set of operators
1.Airthmetic operators
2.comparison operators
3.Logical operators
4.Bitwise operators
5.Assignment operators

Sahana patil | |VHD college


9

6.Identity operators
7.Membership operators
1.Airthmetic operators: Arithmetic operators are used with numeric values to perform
common mathematical operations:

Operator Name Example Description


+ Addition x+y To perform the addition of two numbers
- Subtraction x-y To perform the subtraction of two numbers
* Multiplication x*y To perform the product of two numbers
/ Division x/y Gives quotient of two numbers
% Modulus x%y Gives remainder of two numbers division
** Exponent x ** y Calculates the first operand power to the
second operand
// Floor division x // y It gives the floor value of the quotient
Produced by dividing two operands

2.Comparison operators: Comparison operators are used to compare two values:

Operator Name Example Description


== Equal x == y True if both the operands are equal
!= Not equal x != y True if operands are not equal
> Greater than x>y True if the left operand is greater than the
right
< Less than x<y True if the left operand is less than the
right
>= Greater than x >= y True if the left operand is greater than
or equal to or equal to the right

<= Less than or x <= y True if the left operand is less than
equal to or equal to the right
3.Logical Operators: A logical operator are used to connect two or more conditional statements
or expressions. They return Boolean result either True or False.

Operator Operation Description

And Logical AND Returns true if both statements are True


Otherwise False
Or Logical OR Returns False when both statements are
false, else True
Not Logical Not Reverse the result and return false if the
result is True

Sahana patil | |VHD college


10

4.Bitwise Operators: bitwise operators are used to perform bitwise calculations on integers.
The integers are first converted into binary and then operations are performed on each bit or
corresponding pair of bits, hence the name bitwise operators. The result is then returned in
decimal format.

Operator Operation Description

& Bitwise AND Result bit 1, if both operand bits are 1; otherwise, results
bit 0.
| Bitwise OR Result bit 1, if any of the operand bit is 1; otherwise,
results bit 0.
^ Bitwise XOR Results bit 1, if any of the operand bit is 1 but not both,
otherwise results bit 0.
~ Bitwise NOT inverts individual bits ~x
<< Zero fill left The left operand’s value is moved toward left by the
shift or Bitwise number of bits
left shift
>> Signed right The left operand’s value is moved toward right by the
shift or Bitwise number of bits specified by the right operand.
right shift

5.Assignment Operators: assignment operator helps to assign values or expressions to the


left-hand-side variable. The assignment operator is represented as the "=" symbol used in
assignment statements and assignment expressions. In the assignment operator, the right-hand
side value or operand is assigned to the left-hand operand.

Operator Operation Description

= Simple Assignment

+= Addition assignment

-= Subtraction assignment

*= Multiplication
assignment

/= Division assignment

%= Modulus assignment

**= Exponentiation
assignment

//== Floor Division


assignment

Sahana patil | |VHD college


11

6.Identity Operators: We use identity operators to compare the memory location of two
objects.

Operator Syntax Description

is x is y This returns True if both variables are the same object

is not x is not y This returns True if both variables are not the same object

7.Membership Operators:

Membership operators are used to test if a sequence is presented in an object:

Operator Description
in Returns True if a sequence with the specified value is present in the object

not in Returns True if a sequence with the specified value is not present in the object
x not in y

1.1.14 Expressions, Operator Precedence and Associativity


• An expression is a collection of numbers, variables, operations, and built-in or user-
defined function calls. The Python interpreter can evaluate a valid expression.
• Python follows the same precedence rules for its mathematical operators that
mathematics does.
• Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want.
• The precedence of an operator specifies how "tightly" it binds two expressions
together.
The following table shows the precedence of Python operators. It's in reverse order (the upper
operator holds higher precedence than the lower operator).

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

Sahana patil | |VHD college


12

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not Comparisons, Identity, Membership operators
in

not Logical NOT

and Logical AND

or Logical OR

1.1.15 Data Types

• Data types specifies the data/value stored in the memory or variable.


• Python is dynamically typed language. Hence, we need not define the variable type
while declaring it.
• Variables can hold values of different data types.
• The interpreter implicitly binds the value with its type. It lets to check the type of the
variable used in the program.
• Python provides the type() function ,which returns the type of the variable passed.
Below are the built-in data types used in python

Text Type: Str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Python supports the following standard data types


1. Number -Stores Numeric values Ex: x=10
Python supports 3 different numeric data types
• int: whole number, positive or negative without decimals of unlimited length.
• Float: positive or negative number consisting of decimals and also scientific
numbers with “e” to indicate the power of 10.
• Complex: They are written with a real and “j” as the imaginary part.
Sahana patil | |VHD college
13

Ex:122.3 +12j,34.3j+1
Random numbers: Python has a built-in module called random that can be used to generate
random numbers. For example, refer python lab manual

2. String:

• A string is a collection of characters in single, double or triple quotes.


• It is a contiguous set of characters in quotation marks.
• Subsets of strings can be taken using the slice operator ([] and [:]), with indexes starting at
0 in the beginning of the string and from -1 at the end.
• A string is a data structure in Python that represents a sequence of characters. It is an
immutable data type, meaning that once you have created a string, you cannot change
it. Strings are used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and other types of data that can
be represented as text.
• The plus (+) sign is the string concatenation operator and the asterisk(*) is the repetition
operator.
3. List:
• Is an ordered collection of similar or different types of items separated by comma and
enclosed within brackets [].
• Ex: colors = [“red”,12]
4. Tuple:

•A tuple is an ordered sequence of items same as list. The difference here is that tuples
are immutable.i.e. e once created, cannot be modified. We use () to create a tuple in
python.
Ex: colors =(“blue”,12)
5. Dictionary:
• It is an unordered collection of items.It stores elements in key/value pairs.
• Keys are unique identifiers that are associated with each value.
• Ex: create a dictionary named capital_city
City={‘karnataka’:‘bangalore’,’nepal’:’kathmandu’}
Here the keys are Karnataka and Nepal .values are bangalore and Kathmandu.
6. Set:
• It is an unordered collection of unique items .
• Ex: emp_id={411,122,123,124,122}

1.1.18 Dynamic and strongly typed language


Python is both a strongly typed and a dynamically typed language.
• Strong typing means that variables do have a type and that the type matters when
performing operations on a variable.
• Dynamic typing means that the type of the variable is determined only during runtime.
other hand, types in Python are determined during run-time as opposed to compile-time
and thus programmers are not required to declare variables before using them in the
code. Technically, a variable is created when it is assigned a value for the first time in the
code.
• This means that a variable must first be assigned a value before it is referenced in the
code otherwise an error will be reported.
Sahana patil | |VHD college
14

• And as mentioned earlier, the variable assignment never comes with a type definition
since the type is stored with objects and not with variables/names.
• Every time a variable is identified, it automatically gets replaced with the object in
memory it references.

1.2 Control flow


1.2.1 Decision making
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular decision.
Here, the decisions are made on the validity of the particular conditions. Condition checking is
the backbone of decision making.
In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition is true, a
block of code (if-block) will be executed.

If-else statement The if-else statement is similar to if statement except the fact that, it also
provides the block of the code for the false case of the condition to be
checked. If the condition provided in the if statement is false, then the else
statement will be executed.

Nested if Nested if statements enable us to use if-else statement inside an outer if


Statement statement.
If…elif…else Multiple conditions can be specified for if and elif statements. Else will be
statement evaluated only when all the conditions are evaluated as FALSE

Syntax

If statement if expression: num = int(input("enter the number?")) if num%2 ==


statement 0:
print("Number is even")

If-else if condition: age = int (input("Enter your age? "))


#block of statements if age>=18:
else: print("You are eligible to vote !!");
#Another block of stateme else:
nts (else-block) print("Sorry! you have to wait !!");

If..elif..else number = int(input("Enter the number?"))


if expression 1:
# block of statements
Sahana patil | |VHD college
15

if number==10:
elif expression 2:
# block of statements print("number is equals to 10")

elif expression 3: elif number==50:

# block of statements print("number is equal to 50");


else: elif number==100:
# block of statements
print("number is equal to 100");

else:

print("number is not equal to 10, 50 or 100");

Nested if if (condition1): num = 15


# Executes when if num >= 0:
condition1 is true if num == 0:
print("Zero")
if (condition2):
else:
# Executes when print("Positive number")
condition2 is true
else:
# if Block is end here print("Negative number")

# if Block is end here

Flow charts:
If statement if else statement

Sahana patil | |VHD college


16

1.2.2 Looping
Python For Loops

• For loop is used to repeat the execution of a block of code for a fixed number of times.

• A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string).

• With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Synatx1:
for variable in range (val1,val2,inr):
#block of statements

In the above statement val1 and val2 represents the minimum and maximum number of the
specified range. The inr represents the increment value

Example:
a=int(input(“Enter the number:”))
for i in range(a):
Print(i)
Output:
0
1
2

Synatx2:
for item in sequence:
#body of for loop

• Item is the variable that takes the value of the item inside the sequence of each iteration.
The sequence can be a list, tuple, string, set etc.
• Loop continues until we reach the last item in the sequence.

Example: Print each fruit in a fruit list:


fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.
While loop is generally used when we don’t know the number of times to iterate in advance.

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

i=1
while i < 6:
print(i)
i += 1

Sahana patil | |VHD college


17

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.
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

1.2.3 Control statements


Loops are employed in Python to iterate repeatedly over a section of code.
In order to change the way a loop is executed from its usual behavior control statements are
used.

Break Statements
The break statement in Python is used to terminate or abandon the loop containing the
statement and brings the control out of the loop. It is used with both the while and the for loops,
especially with nested loops (loop within a loop) to quit the loop. It terminates the inner loop
and control shifts to the statement in the outer loop.

Code:
age = “\n Please enter your age: ”
while True:
age = input
if age >= 18:
break
else:
print (“You’re not eligible to vote”)
Output:
Please enter your age: 17 You’re not eligible to vote
Please enter your age: 18
In the above example, if the age entered is equal to or more than 18, it breaks out of the loop.

Sahana patil | |VHD college


18

Continue Statements:
When a program encounters a continue statement in Python, it skips the execution of the current
iteration when the condition is met and lets the loop continue to move to the next iteration. It
is used to continue running the program even after the program encounters a break during
execution.

Code
for letter in 'Flexi ple':
if letter == ' ':
continue
print ('Letters: ', letter)
Output:
Letters: F
Letters: l
Letters: e
Letters: x
Letters: i
Letters: p
Letters: l
Letters: e
In this example, the program will skip the space ‘ ‘ in the word and continue with the rest of the
iteration.
Pass Statements
The null statement is another name for the pass statement.
We can use the pass statement as a placeholder when unsure what code to provide. So, we only
have to place the pass on that line. Pass may be used when we don't wish any code to be
executed.
We can simply insert a pass in places where empty code is prohibited, such as loops, functions,
class definitions, or if-else statements.
Example of the Pass Statement
Code

# Python program to show how to use a pass statement in a for loop


'''''pass acts as a placeholder. We can fill this place later on'''
sequence = {"Python", "Pass", "Statement", "Placeholder"}
for value in sequence:
if value == "Pass":
pass # leaving an empty if block using the pass keyword
else:
print("Not reached pass keyword: ", value)
Output:

Not reached pass keyword: Python


Not reached pass keyword: Placeholder
Not reached pass keyword: Statement
The same thing is also possible to create an empty function or a class.

Sahana patil | |VHD college


19

Question Bank
1. Python is an interpreted language-Justify.
2. What are the key features of python?
3. What is the role of indentation in python? Explain with an example.
4. List few applications of python.
5. How do you write comments in python?
6. What is the difference between intermediate mode and script mode?
7. What are the rules of naming a variable?
8. What are keywords?
9. What are the rules for writing an identifier?
10. List the standard data types in Python.
11. What are the mutable and immutable data types? Give examples.
12. What are the python strings?
13. Write a short note on IDLE.
14. Explain Operator precedence and associativity.
15. Explain conditional statements.
16. Explain python looping statements.
17. Illustrate interpreter and interactive mode in python with an example.

Sahana patil | |VHD college

You might also like