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

Python Unit 1

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991, known for its readability and efficiency. It has a rich history with multiple versions released, including Python 3.10.3 in March 2022, and is widely used in various applications such as web development, data analysis, and machine learning. Key features include being easy to learn, open-source, portable, and supporting both object-oriented and procedural programming paradigms.

Uploaded by

gajanankhasawat5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Unit 1

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991, known for its readability and efficiency. It has a rich history with multiple versions released, including Python 3.10.3 in March 2022, and is widely used in various applications such as web development, data analysis, and machine learning. Key features include being easy to learn, open-source, portable, and supporting both object-oriented and procedural programming paradigms.

Uploaded by

gajanankhasawat5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Unit 1: Introduction Subject: Python BCA III

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.

3. Free and Open-Source


Python is freely available. You can download it from the Python Official Website.
It is open-source. This means that its source code is available to the public. You can download it, change it, use
it, and distribute it.
This is called FLOSS(Free/Libre and Open Source Software).

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.

10. Large Standard Library


Python downloads with a large library that you can use so you don’t have to write your own code for every
single thing.
There are libraries for regular expressions, documentation-generation, unit-testing, web browsers, threading,
databases, CGI, email, image manipulation, and a lot of other functionality.

11. GUI Programming


Software is not user-friendly until its GUI is made. A user can easily interact with the software with a GUI.
Python offers various libraries for making Graphical user interface for your applications.
For this, you can use Tkinter, wxPython or JPython. These toolkits allow you for easy and fast development of
GUI.

12. Dynamically Typed


Python is dynamically-typed. This means that the type for a value is decided at runtime, not in advance.
This is why we don’t need to specify the type of data while declaring it.

What can I do with Python?


In addition to being a well-designed programming language, Python is useful for accomplishing real-world tasks.

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.

Numeric and Scientific Programming


Python is also heavily used in numeric programming. NumPy high-performance numeric programming
extension for Python mentioned earlier includes such advanced tools as an array object, interfaces to standard
mathematical libraries, and much more. By integrating Python with numeric routines coded in a compiled
language for speed, NumPy turns Python into a sophisticated yet easy-to-use numeric programming tool that
can often replace existing code written in traditional compiled languages such as FORTRAN or C++.

And More: Gaming, Images, Data Mining, Robots, Excel...


Python is commonly applied in more domains than can be covered here. For example, you’ll find tools that
allow you to use Python to do:
• Game programming and multimedia with pygame, cgkit, pyglet, PySoy, Panda3D, and others
• Serial port communication on Windows, Linux, and more with the PySerial extension
• Image processing with PIL and its newer Pillow fork, PyOpenGL, Blender, Maya, and more
• Robot control programming with the PyRo toolkit
• Natural language analysis with the NLTK package
• Instrumentation on the Raspberry Pi and Arduino boards
• Mobile computing with ports of Python to the Google Android and Apple iOS platforms
• Excel spreadsheet function and macro programming with the PyXLL or DataNitro add-ins
• Media file content and metadata tag processing with PyMedia, ID3, PIL/Pillow, and more
• Artificial intelligence with the PyBrain neural net library and the Milk machine learning toolkit
• Expert system programming with PyCLIPS, Pyke, Pyrolog, and pyDatalog
• Network monitoring with zenoss, written in and customized with Python
• Python-scripted design and modeling with PythonCAD, PythonOCC, FreeCAD, and others
4
Unit 1: Introduction Subject: Python BCA III

• 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.

Data Types in PYTHON


Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence we
do not need to define the type of the variable while declaring it. The interpreter implicitly binds the value with
its type.
a=5
The variable a holds integer value five and we did not define its type. Python interpreter will automatically
interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us the type() function,
which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


Python provides various standard data types that
define the storage method on each of them. The
data types defined in Python are given below.

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:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data.


Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no restriction on the
length of an integer. Its value belongs to int
Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto 15 decimal
points.
complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary
parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

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'.

The following example illustrates the string in Python.


str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
string using double quotes
A multiline
string
6
Unit 1: Introduction Subject: Python BCA III

Consider the following example of string handling.


str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
Output:

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.

Consider the following example.

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))

#Printing the list1


print (list1)

# List slicing
print (list1[3:])

# List slicing
print (list1[0:2])

# List Concatenation using + operator


print (list1 + list1)

# List repetation using * operator


print (list1 * 3)
Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 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.

Let's see a simple example of the tuple.

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repatation using * operator


print (tup * 3)

# Adding value to tup. It will throw an error.


t[2] = "hi"
Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

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 {}.

Consider the following example.

8
Unit 1: Introduction Subject: Python BCA III

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())
Output:
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
1st name is Jimmy
2nd name is mike
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

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.

# Python program to check the boolean type


print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

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.

# Creating Empty set


set1 = set()
set2 = {'James', 2, 3,'Python'}
print(set2) #Printing Set value
set2.add(10) # Adding element to the set
print(set2)
set2.remove(2) #Removing element from the set
print(set2)
Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

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)

>>> f.write('Hello\n') # Write strings of characters to it

>>> f.write('world\n') # Return number of items written in Python 3.X

>>> f.close() # Close to flush output buffers to disk

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:

>>> f = open('data.txt') # 'r' (read) is the default processing mode

>>> text = f.read() # Read entire file into a string

>>> text

'Hello\n world\n'

>>> print(text) # print interprets control characters

Hello

world

>>> text.split() # File content is always a string

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

1. name = "Thomas" # Assigning string value to the name variable


We can add comment in each line of the Python code.
1. Fees = 10000 # defining course fees is 10000
2. Fees = 20000 # defining course fees is 20000

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.

Declaring Variable and Assigning Values


Python does not bind us to declare a variable before using it in the application. It allows us to create a variable
at the required time.

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

2. Assigning multiple values to multiple variables:


Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.

Python Variable Types


There are two types of variables in Python - Local variable and Global variable.
Local Variable
Local variables are the variables that declared inside the function and have scope within the function. Let's
understand the following example.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()
Output:
The sum is: 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

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda

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 assigns the value of the right expression to the left operand.

+= 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.

~+- The negation, unary plus, and minus.

* / % // The multiplication, divide, modules, reminder, and floor division.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater than, greater then equal
to).

<> == != Equality operators.

= %= /= //= -= Assignment operators


+=
*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

17
Unit 1: Introduction Subject: Python BCA III

Python Input and Output Statements


Input : Any information or data sent to the computer from the user through the keyboard is called input.
Output: The information produced by the computer to the user is called output.

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.

Python-2 supports the raw_input() function and input() function


Python-3 supports only for input() function .

The following example will read two inputs from the keyboard and print the sum

x=input("Enter First number:")


y=input("Enter Second Number:")
i=int(x)
j=int(y)
print("The Sum:", i+j)

Or else even we can simplify the above program:


x=int(input("Enter Fisrt number:"))
y=int(input("Enter Second Number:"))
print("The Sum:", i+j)

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.

eno=int(input("Enter the Emplyoyee number:"))


ename=input("Enter the Employee name:")
esal=float(input("Enter the employee salary:"))
eaddr=input("Enter the employee address:")
married=bool(input("Is employee married?[True|False]:"))

print("Please confirm your provided information")

18
Unit 1: Introduction Subject: Python BCA III

print("Emplyoyee number:", eno)


print("Employee name:", ename)
print("Employee salary:", esal)
print(" Employee address:", eaddr)
print("Employee married?:", married)

Python If-else statements


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 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.

The syntax of the if-statement is given below.

if expression:
statement
Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")
Output:

enter the number?10


Number is even

Example 2 : Program to print the largest of the three numbers.


a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
19
Unit 1: Introduction Subject: Python BCA III

if b>a and b>c:


print("b is largest");
if c>a and c>b:
print("c is largest");
Output:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in the false case
of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.


if condition:
#block of statements
else:
#another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.


age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
Output:
Enter your age? 90
You are eligible to vote !!

Example 2: Program to check whether a number is even or not.


num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")
Output:

enter the number?10


Number is even

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our program
depending upon our need. However, using elif is optional.

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

The syntax of the elif statement is given below.

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:

Enter the number?15


number is not equal to 10, 50 or 100

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.

Why we use loops in python?

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

There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).

There are the following loop statements in Python.

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).

Python for loop

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.

The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)

Example-1: Iterating string using for loop

str = "Python"

for i in str:

print(i)

Example- 2: Program to print the table of the given number .

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 sum is: 183


For loop Using range() function

The range() function

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 start represents the beginning of the iteration.


23
Unit 1: Introduction Subject: Python BCA III

 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.

Consider the following examples:

Example -2: Program to print table of given number.


n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)

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

Example-2: Program to print even number using step size in range().

n = int(input("Enter the number "))


for i in range(2,n,2):
print(i)

Output:
Enter the number 20
2
4
6
8
10
12
14
16
18

Nested for loop in python


Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number of times
for every iteration of the outer loop. The syntax is given below.

Syntax

24
Unit 1: Introduction Subject: Python BCA III

for iterating_var1 in sequence: #outer loop


for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements

Example- 1: Nested for loop


# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()
Output:

Enter the rows:5


*
**
***
****
*****

Example-2: Program to number pyramid.


rows = int(input("Enter the rows"))
for i in range(0,rows+1):
for j in range(i):
print(i,end = '')
print()
Output:

1
22
333
4444
55555

Python While loop

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.

The syntax is given below.


while expression:
statements
Here, the statements can be a single statement or a group of statements. The expression should be any valid
Python expression resulting in true or false. The true is any non-zero value and false is 0.

25
Unit 1: Introduction Subject: Python BCA III

Loop Control Statements


We can change the normal sequence of while loop's execution using the loop control statement. When the
while loop's execution is completed, all automatic objects defined in that scope are demolished. Python offers
the following control statement to use within the while loop.

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:

# prints all letters except 'a' and 't'


i=0
str1 = 'javatpoint'

while i < len(str1):


if str1[i] == 'a' or str1[i] == 't':
i += 1
continue
print('Current Letter :', a[i])
i += 1
Output:

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'

while i < len(str1):


if str1[i] == 't':
i += 1
26
Unit 1: Introduction Subject: Python BCA III

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

while i < len(str1):


i += 1
pass
print('Value of i :', i)
Output:

Value of i : 10

Example-1: Program to print 1 to 10 using while loop


i=1
#The while loop will iterate until condition becomes false.
While(i<=10):
print(i)
i=i+1
Output:
1
2
3
4
5
6
7
8
9
10

Example -2: Program to print table of given numbers.


i=1
number=0
b=9
number = int(input("Enter the number:"))
while i<=10:
print("%d X %d = %d \n"%(number,i,number*i))

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

Infinite while loop


If the condition is given in the while loop never becomes false, then the while loop will never terminate, and it
turns into the infinite while loop.
Any non-zero value in the while loop indicates an always-true condition, whereas zero indicates the always-false
condition. This type of approach is useful if we want our program to run continuously in the loop without any
disturbance.

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

Program to print Fibonacci numbers to given limit


terms = int(input("Enter the terms "))
a=0
b = 1 # first two intial terms
count = 0
if (terms <= 0): # check if the number of terms is Zero or negative
print("Please enter a valid integer")
elif (terms == 1):
print("Fibonacci sequence upto",limit,":")
print(a)
else:
print("Fibonacci sequence:")
while (count < terms) :
print(a, end = ' ')
c=a+b
a=b
b=c # updateing values
count += 1
Output:
Enter the terms 10
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34

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

You might also like