Python Unit 1
Python Unit 1
Introduction:
Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum
in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently. Python is a
high-level, 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.
History of Python:
Python was conceived in the late 1980s and was named after the BBC TV show Monty Python’s Flying
Circus.
Guido van Rossum started implementing Python at CWI in the Netherlands in December of 1989.
This was a successor to the ABC programming language which was capable of exception handling and
interfacing with the Amoeba operating system.
On October 16 of 2000, Python 2.0 released with many new features.
Then Python 3.0 released on December 3, 2008.
Python 3.10.0 released on 4 October 2021.
Latest version Python 3.10.3 released on 16 March 2022.
Applications of Python:
Python is easy to pick-up even if you come from a non-programming background. You can look at the code and
tell what’s going on.
Talking of Python applications, some of the cool things that you can do are –
Build a website using Python
Develop a game in Python
Perform Computer Vision (Facilities like face-detection and color-detection)
Implement Machine Learning (Give a computer the ability to learn)
Enable Robotics with Python
Perform Web Scraping (Harvest data from websites)
Perform Data Analysis using Python
Automate a web browser
Perform Scripting in Python
Perform Scientific Computing using Python
Build Artificial Intelligence
Python isn’t limited to these applications. If you’ve ever used services from brands like YouTube, Dropbox,
and Netflix, then you’ve been a consumer of Python.
The search-engine Google also made great use of this language in its initial stages.
1
Unit 1: Introduction Subject: Python BCA III
Features of Python:
1. Easy
When we say the word ‘easy’, we mean it in different contexts.
a. Easy to Code
Python is very easy to code as compared to other popular languages like Java and C++.
Anyone can learn Basic Python syntax in just a few hours. Thus, it is programmer-friendly.
b. Easy to Read
Being a high-level language, Python code is quite like English. Looking at it, you can tell what the code is
supposed to do.
Also, since it is dynamically-typed, it mandates indentation. This aids readability.
2. Expressive
Suppose we have two languages A and B, and all programs that can be made in A can be made in B using local
transformations.
However, there are some programs that can be made in B, but not in A, using local transformations. Then, B is
said to be more expressive than A.
Python provides us with a myriad of constructs that help us focus on the solution rather than on the syntax.
This is one of the outstanding python features that tell you why you should learn Python.
4. High-Level
Python is a high-level language. This means that as programmers, we don’t need to remember the system
architecture.
Also, we need not manage memory. This makes it more programmer-friendly and is one of the key python
features.
5. Portable
Let’s assume you’ve written a Python code for your Windows machine. Now, if you want to run it on a Mac, you
don’t need to make changes to it for the same.
In other words, you can take one code and run it on any machine. This makes Python a portable language.
6. Interpreted
Any languages like C++ or Java, you must first compile it, and then run it. But in Python, there is no need to
compile it.
Internally, its source code is converted into an immediate form called bytecode.
So, one need to to run Python code without worrying about linking to libraries, and a few other things.
By interpreted, it means the source code is executed line by line, and not all at once. Because of this, it is easier
to debug your code.
7. Object-Oriented
A programming language that can model the real world is said to be object-oriented. It focuses on objects and
combines data and functions.
Contrarily, a procedure-oriented language revolves around functions, which are code that can be reused.
Python supports both procedure-oriented and object-oriented programming which is one of the key python
features.
It also supports multiple inheritance, unlike Java.
2
Unit 1: Introduction Subject: Python BCA III
8. Extensible
If needed, you can write some of your Python code in other languages like C++.
This makes Python an extensible language, meaning that it can be extended to other languages.
9. Embeddable
We can put code in other languages in our Python source code.
However, it is also possible to put our Python code in a source code in a different language like C++.
This allows us to integrate scripting capabilities into our program of the other language.
Systems Programming
Python’s built-in interfaces to operating-system services make it ideal for writing portable, maintainable
system-administration tools and utilities (sometimes called shell tools). Python programs can search files and
directory trees, launch other programs, do parallel processing with processes and threads, and so on.
Python’s standard library comes with POSIX bindings and support for all the usual OS tools: environment
variables, files, sockets, pipes, processes, multiple threads, regular expression pattern matching, command-line
arguments, standard stream interfaces, shell-command launchers, filename expansion, zip file utilities, XML and
JSON parsers, CSV file handlers, and more. In addition, the bulk of Python’s system interfaces are designed to be
portable; for example, a script that copies directory trees typically runs unchanged on all major Python
platforms.
GUIs
Python’s simplicity and rapid turnaround also make it a good match for graphical user interface programming
on the desktop. Python comes with a standard object-oriented interface to the Tk GUI API called tkinter (Tkinter
in 2.X) that allows Python programs to implement portable GUIs with a native look and feel. In addition, the
wxPython GUI API, based on a C++ library, offers an alternative toolkit for constructing portable GUIs in Python.
Internet Scripting
Python comes with standard Internet modules that allow Python programs to perform a wide variety of
networking tasks, in client and server modes. Scripts can communicate over sockets; extract form information
sent to server-side CGI scripts; transfer files by FTP; parse and generate XML and JSON documents; send,
receive, compose, and parse email; fetch web pages by URLs; parse the HTML of fetched web pages;
communicate over XML-RPC, SOAP, and Telnet; and more. Python’s libraries make these tasks remarkably
3
Unit 1: Introduction Subject: Python BCA III
simple. In addition, full-blown web development framework packages for Python, such as Django, TurboGears,
web2py, Pylons, Zope, and WebWare, support quick construction of full-featured and production-quality
websites with Python.
Component Integration
Python’s ability to be extended by and embedded in C and C++ systems makes it useful as a flexible glue
language for scripting the behavior of other systems and components. For instance, integrating a C library into
Python enables Python to test and launch the library’s components, and embedding Python in a product
enables onsite customizations to be coded without having to recompile the entire product (or ship its source
code at all).
Tools such as the SWIG and SIP code generators can automate much of the work needed to link compiled
components into Python for use in scripts, and the Cython system allows coders to mix Python and C-like code.
Database Programming
For traditional database demands, there are Python interfaces to all commonly used relational database
systems—Sybase, Oracle, Informix, ODBC, MySQL, PostgreSQL, SQLite, and more. The Python world has also
defined a portable database API for accessing SQL database systems from Python scripts, which looks the same
on a variety of underlying database systems.
In the non-SQL department, Python’s standard pickle module provides a simple object persistence system—it
allows programs to easily save and restore entire Python objects to files and file-like objects.
Still other systems offer more specialized ways to store data, including the datastore in Google’s App Engine,
which models data with Python classes and provides extensive scalability, as well as additional emerging cloud
storage options such as Azure, PiCloud, OpenStack, and Stackato.
Rapid Prototyping
To Python programs, components written in Python and C look the same. Because of this, it’s possible to
prototype systems in Python initially, and then move selected components to a compiled language such as C or
C++ for delivery.
• Document processing and generation with ReportLab, Sphinx, Cheetah, PyPDF, and so on
• Data visualization with Mayavi, matplotlib, VTK, VPython, and more
• XML parsing with the xml library package, the xmlrpclib module, and third-party extensions
• JSON and CSV file processing with the json and csv modules
• Data mining with the Orange framework, the Pattern bundle, Scrapy, and custom code
Python Interpreter
An interpreter is a kind of program that executes other programs. When you write a Python program, the
Python interpreter reads your program and carries out the instructions it contains. In effect, the interpreter is a
layer of software logic between your code and the computer hardware on your machine.
When the Python package is installed on your machine, it generates a number of components— minimally, an
interpreter and a support library. Depending on how you use it, the Python interpreter may take the form of an
executable program, or a set of libraries linked into another program. Depending on which flavor of Python you
run, the interpreter itself may be implemented as a C program, a set of Java classes, or something else.
Whatever form it takes, the Python code you write must always be run by this interpreter. And to enable that,
you must install a Python interpreter on your computer.
Python itself may be fetched from the downloads page on its main website, http://www .python.org.
Numbers
Sequence Type
Boolean
Set
Dictionary
5
Unit 1: Introduction Subject: Python BCA III
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python Numbers data-type.
Python provides the type() function to know the data-type of the variable. Similarly, the isinstance() function is
used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In Python, we can
use single, double, or triple quotes to define a string.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python Python'.
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored in
the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition
operator (*) works with the list in the same way as they were working with the strings.
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
7
Unit 1: Introduction Subject: Python BCA III
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different
data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
# Tuple slicing
print (tup[1:])
print (tup[0:1])
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where
each key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python
object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
8
Unit 1: Introduction Subject: Python BCA III
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine the given
statement true or false. It denotes by the class bool. True can be represented by any non-zero value or 'T'
whereas false can be represented by the 0 or 'F'. Consider the following example.
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after creation), and
has unique elements. In set, the order of the elements is undefined; it may return the changed sequence of the
element. The set is created by using a built-in function set(), or a sequence of elements is passed in the curly
braces and separated by the comma. It can contain various types of values. Consider the following example.
9
Unit 1: Introduction Subject: Python BCA III
Files
File objects are Python code’s main interface to external files on your computer. They can be used to read and
write text memos, audio clips, Excel documents, saved email messages, and whatever else you happen to have
stored on your machine. To create a file object, you call the built-in open function, passing in an external
filename and an optional processing mode as strings.
For example, to create a text output file, you would pass in its name and the 'w' processing mode string to write
data:
>>> f = open('data.txt', 'w') # Make a new file in output mode ('w' is write)
This creates a file in the current directory and writes text to it (the filename can be a full directory path if you
need to access a file elsewhere on your computer). To read back what you just wrote, reopen the file in 'r'
processing mode, for reading text input —this is the default if you omit the mode in the call. Then read the file’s
content into a string, and display it. A file’s contents are always a string in your script, regardless of the type of
data the file contains:
>>> text
'Hello\n world\n'
Hello
world
Comments in Python
Comments are essential for defining the code and help us and other to understand the code. By looking the
comment, we can easily understand the intention of every line that we have written in code. We can also find
the error very easily, fix them, and use in other applications.
In Python, we can apply comments using the # hash character. The Python interpreter entirely ignores the lines
followed by a hash character. A good programmer always uses the comments to make code under stable. Let's
see the following example of a comment.
10
Unit 1: Introduction Subject: Python BCA III
Types of Comment
Python provides the facility to write comments in two ways- single line comment and multi-line comment.
Single-Line Comment - Single-Line comment starts with the hash # character followed by text for further
explanation.
1. # defining the marks of a student
2. Marks = 90
We can also write a comment next to a code statement. Consider the following example.
1. Name = "James" # the name of a student is James
Multi-Line Comments - Python doesn't have explicit support for multi-line comments but we can use hash #
character to the multiple lines. For example -
1. # we are defining for loop
2. # To iterate the given list.
3. # run this code.
We can also use another way.
1. """
2. This is an example
3. Of multi-line comment
4. Using triple-quotes
5. """
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also known as an identifier and
used to hold value.
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.
Variable names can be a group of both the letters and digits, but they have to begin with a letter or an
underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two different
variables.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The
rules to name an identifier are given below.
o The first character of the variable must be an alphabet or underscore ( _ ).
o All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z),
underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
11
Unit 1: Introduction Subject: Python BCA III
We don't need to declare explicitly variable in Python. When we assign any value to the variable, that variable is
declared automatically.
The equal (=) operator is used to assign value to a variable.
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also known as multiple
assignments.
1. Assigning single value to multiple variables
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
12
Unit 1: Introduction Subject: Python BCA III
Global Variables
Global variables can be used throughout the program, and its scope is in the entire program. We can use global
variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python provides the global keyword to
use global variable inside the function. If we don't use the global keyword, the function treats it as a local
variable. Let's understand the following example.
Example -
1. # Declare a variable and initialize it
2. x = 101
3.
4. # Global variable in function
5. def mainFunction():
6. # printing a global variable
7. global x
8. print(x)
9. # modifying a global variable
10. x = 'Welcome To python'
11. print(x)
12.
13. mainFunction()
14. print(x)
Output:
101
Welcome To python
Welcome To python
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
1. del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted variable x, and print it, we get
the error "variable x is not defined". The variable x will no longer use in future.
Example -
1. # Assigning a value to x
2. x=6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in
print(x)
NameError: name 'x' is not defined
13
Unit 1: Introduction Subject: Python BCA III
Python Keywords
Python Keywords are special reserved words that convey a special meaning to the compiler/interpreter. Each
keyword has a special meaning and a specific operation. These keywords can't be used as a variable. Following is
the List of Python Keywords.
True False None and as
Python Operators
The operator can be defined as a symbol which is responsible for a particular operation between two operands.
Operators are the pillars of a program on which the logic is built in a specific programming language. Python
provides a variety of operators, which are described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes + (addition),
- (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent (**) operators.
Consider the following table for a detailed explanation of arithmetic operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is
less than the second operand, the value results negative. For example, if a = 20, b =
10 => a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a *
(Multiplication) b = 200
% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a%b = 0
** (Exponent) It is an exponent operator represented as it calculates the first operand power to the
second operand.
14
Unit 1: Introduction Subject: Python BCA III
// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)
Comparison operator
Comparison operators are used to comparing the value of the two operands and returns Boolean true or false
accordingly. The comparison operators are described in the following table.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes
true.
>= If the first operand is greater than or equal to the second operand, then the condition
becomes true.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Assignment Operators
The assignment operators are used to assign the value of the right expression to the left operand. The
assignment operators are described in the following table.
Operator Description
+= It increases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to
a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to
a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be
equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the
reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a
= a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
15
Unit 1: Introduction Subject: Python BCA III
Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands. Consider the following
example.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the result.
and) Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit will be
0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit
will be 1 and vice versa.
<< (left shift) The left operand value is moved left by the number of bits present in the right operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision. Python supports the
following logical operators.
Operator Description
and If both the expression are true, then the condition will be true. If a and b are the two
expressions, a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b are the two
expressions, a → true, b → false => a or b → true.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
Python membership operators are used to check the membership of value inside a Python data structure. If
the value is present in the data structure, then the resulting value is true otherwise it returns false.
Operator Description
16
Unit 1: Introduction Subject: Python BCA III
in It is evaluated to be true if the first operand is found in the second operand (list, tuple, or
dictionary).
not in It is evaluated to be true if the first operand is not found in the second operand (list, tuple,
or dictionary).
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operator Description
is It is evaluated to be true if the reference present at both sides point to the same object.
is not It is evaluated to be true if the reference present at both sides do not point to the same
object.
Operator Precedence
The precedence of the operators is essential to find out since it enables us to know which operator should be
evaluated first. The precedence table of the operators in Python is given below.
Operator Description
** The exponent operator is given priority over all the others used in the expression.
<= < > >= Comparison operators (less than, less than equal to, greater than, greater then equal
to).
17
Unit 1: Introduction Subject: Python BCA III
Python provides us with the two inbuilt functions as input() and output().
The syntax for input is input (prompt_message); the python will automatically identify whether the user
entered a string, number, or list; if the input entered from the user is not correct, then python will throw a
syntax error.
And the syntax for the output in python is print(), normally used to print the output.
The following example will read two inputs from the keyboard and print the sum
Let us consider another example to know how we can use the input() function. The Following example read the
employee data from the keyboard and print that data.
18
Unit 1: Introduction Subject: Python BCA III
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 The if-else statement is similar to if statement except the fact that, it also provides the block
Statement 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
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a block of code
known as if-block. The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.
if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.
20
Unit 1: Introduction Subject: Python BCA III
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Output:
Example 2
marks = int(input("Enter the marks? "))
f marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
lif marks > 60 and marks <= 85:
print("You scored grade B + ...")
lif marks > 40 and marks <= 60:
print("You scored grade B ...")
lif (marks > 30 and marks <= 40):
print("You scored grade C ...")
lse:
print("Sorry you are fail ?")
Python Loops
21
Unit 1: Introduction Subject: Python BCA III
The flow of the programs written in any programming language is sequential by default. Sometimes we may
need to alter the flow of the program. The execution of a specific code may need
to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops
which are capable of repeating some specific code several numbers of times.
Consider the following diagram to understand the working of a loop statement.
The looping simplifies the complex problems into the easy ones. It enables
us to alter the flow of the program so that instead of writing the same code
again and again, we can repeat the same code for a finite number of times.
For example, if we need to print the first 10 natural numbers then, instead
of using the print statement 10 times, we can print inside a loop which runs
up to 10 iterations.
Advantages of loops
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part of the code until the
given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use
for loop if the number of iteration is known in advance.
while loop The while loop is to be used in the scenario where we don't know the number of iterations in
advance. The block of statements is executed in the while loop until the condition specified
in the while loop is satisfied. It is also called a pre-tested loop.
do-while loop The do-while loop continues until a given condition satisfies. It is also called post tested
loop. It is used when it is necessary to execute the loop at least once (mostly menu driven
programs).
22
Unit 1: Introduction Subject: Python BCA III
The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently
used to traverse the data structures like list, tuple, or dictionary.
str = "Python"
for i in str:
print(i)
list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
Output:
The range() function is used to generate the sequence of the numbers. If we pass the range(10), it will generate
the numbers from 0 to 9. The syntax of the range() function is given below.
Syntax:
range(start,stop,step size)
The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1 to 4
iterations. It is optional.
The step size is used to skip the specific numbers from the iteration. It is optional to use. By default, the
step size is 1. It is optional.
Output:
Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
Output:
Enter the number 20
2
4
6
8
10
12
14
16
18
Syntax
24
Unit 1: Introduction Subject: Python BCA III
1
22
333
4444
55555
The Python while loop allows a part of the code to be executed until the given condition returns false. It is also
known as a pre-tested loop.
It can be viewed as a repeating if statement. When we don't know the number of iterations then the while loop
is most effective to use.
25
Unit 1: Introduction Subject: Python BCA III
1. Continue Statement - When the continue statement is encountered, the control transfer to the beginning of
the loop. Let's understand the following example.
Example:
Current Letter : j
Current Letter : v
Current Letter : p
Current Letter : o
Current Letter : i
Current Letter : n
2. Break Statement - When the break statement is encountered, it brings control out of the loop.
Example:
# The control transfer is transfered
# when break statement soon it sees t
i=0
str1 = 'javatpoint'
break
print('Current Letter :', str1[i])
i += 1
Output:
Current Letter : j
Current Letter : a
Current Letter : v
Current Letter : a
3. Pass Statement - The pass statement is used to declare the empty loop. It is also used to define empty class,
function, and control statement. Let's understand the following example.
Example -
# An empty loop
str1 = 'javatpoint'
i=0
Value of i : 10
27
Unit 1: Introduction Subject: Python BCA III
i = i+1
Output:
Enter the number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Example 1
while (1):
print("Hi! we are inside the infinite while loop")
Output:
Hi! we are inside the infinite while loop
Hi! we are inside the infinite while loop
28
Unit 1: Introduction Subject: Python BCA III
Assignment 1:
Discuss features of python.
Explain uses of python.
Discuss Python Interpreter.
Explain data types in python.
Discuss how you write comments in Python.
Explain operators in Python.
Explain I/O statement in Python.
Discuss various looping statements with syntax and suitable example.
Discuss various decision making statement with syntax and suitable example.
29