0% found this document useful (0 votes)
10 views43 pages

Python Unit1 Part1

The document provides an overview of Python, highlighting its features such as being free, easy to read, and object-oriented. It discusses various applications of Python, including web development, GUI applications, and scientific computing, as well as its versions and IDEs. Additionally, it covers Python keywords, identifiers, and types of expressions, illustrating their usage with examples.

Uploaded by

Chaya Anu
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)
10 views43 pages

Python Unit1 Part1

The document provides an overview of Python, highlighting its features such as being free, easy to read, and object-oriented. It discusses various applications of Python, including web development, GUI applications, and scientific computing, as well as its versions and IDEs. Additionally, it covers Python keywords, identifiers, and types of expressions, illustrating their usage with examples.

Uploaded by

Chaya Anu
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

Ⅳ SEM BCA PYTHON

Unit 1
Introduction Python

Python is a general purpose, dynamic, high-level, and interpreted programming


language. It supports Object Oriented programming approach to develop applications.
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.

Features in Python

1. Free and Open Source


Python language is freely available at the official website. Download Python Since it is
open-source, this means that source code is also available to the public. So you can
download it, use it as well as share it.

2. Easy to code
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc.

3. Easy to Read
Learning Python is quite simple. Python‟s syntax is really straightforward. The code
block is defined by the indentations rather than by semicolons or brackets.

4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports
object-oriented language and concepts of classes, object encapsulation, etc.

5. GUI Programming Support


Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python. PyQt5 is the most popular option for creating graphical
apps with Python.

6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need
to remember the system architecture, nor do we need to manage the memory.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 1


Ⅳ SEM BCA PYTHON

7. Extensible feature
Python is an Extensible language. We can write some Python code into C or C++
language and also we can compile that code in C/C++ language.

8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and
correct the majority of your program‟s issues once you understand how
to interpret Python‟s error traces.

9. Python is a Portable language


Python language is also a portable language. For example, if we have Python code for
windows and if we want to run this code on other platforms such as Linux, Unix, and
Mac then we do not need to change it, we can run this code on any platform.

10. Python is an Integrated language


Python is an Integrated language because we can easily integrate Python with other
languages like C, C++, etc.

11. Interpreted Language:


Python is an Interpreted Language because Python code is executed line by line at a
time. like other languages C, C++, Java, etc. there is no need to compile Python code
this makes it easier to debug our code. The source code of Python is converted into
an immediate form called byte code.

12. Large Standard Library


Python has a large standard library that provides a rich set of modules and functions
so you do not have to write your own code for every single thing.

13. Dynamically Typed Language


Python is a dynamically-typed language. That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance because of this
feature we don‟t need to specify the type of variable.

15. Allocating Memory Dynamically


In Python, the variable data type does not need to be specified. The memory is
automatically allocated to a variable at runtime when it is given a value. Developers
do not need to write int y = 18 if the integer value 15 is set to y. You may just type
y=18.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 2


Ⅳ SEM BCA PYTHON

APPLICATION OF PYTHON
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle
internet protocols such as HTML and XML, JSON, Email processing etc. One of
Python web-framework named Django is used on Instagram. Python provides many
frameworks, and these are given below:
 Django and Pyramid framework(Use for heavy applications)
 Flask and Bottle (Micro-framework)
 Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications


The GUI stands for the Graphical User Interface, which provides a smooth interaction
to any application. Python provides a Tk GUI library to develop a user interface.
Some popular GUI libraries are given below.
 Tkinter or Tk
 wxWidgetM
 Kivy (used for writing multitouch applications )
 PyQt or Pyside

3) Console-based Application
Console-based applications run from the command-line or shell. These applications
are computer program which are used commands to execute. Python provides many
free library or module which helps to build the command-line apps.

4) Software Development
Python is useful for the software development process. It works as a support
language and can be used to build control and management, testing, etc.
 SCons is used to build control.
 Buildbot and Apache Gumps are used for automated continuous compilation
and testing.
 Round or Trac for bug tracking and project management.

5) Scientific and Numeric


This is the era of Artificial intelligence where the machine can perform the task the
same as the human. Python language is the most suitable language for Artificial
intelligence or machine learning. It consists of many scientific and mathematical
libraries, which makes easy to solve complex calculations.
Implementing machine learning algorithms require complex mathematical
calculation. Python has many libraries for scientific and numeric such as Numpy,

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 3


Ⅳ SEM BCA PYTHON

Pandas, Scipy, Scikit-learn, etc. Few popular frameworks of machine libraries are
given below.
 SciPy
 Scikit-learn
 NumPy
 Pandas
 Matplotlib

6) Business Applications
E-commerce and ERP are an example of a business application. This kind of
application requires extensively, scalability and readability, and Python provides all
these features.
Oddo is an example of the all-in-one Python-based application which offers a range of
business applications. Python provides a Tryton platform which is used to develop
the business application.

7) Audio or Video-based Applications


Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python
are TimPlayer, cplay, etc. The few multimedia libraries are given below.
 Gstreamer
 Pyglet
 QT Phonon
8) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or
an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.

9) Image Processing Application


Python contains many libraries that are used to work with the image. The image can
be manipulated according to our requirements. Some libraries of image processing
are given below.
OpenCV
Pillow
SimpleITK

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 4


Ⅳ SEM BCA PYTHON

PYTHON VERSIONS

Version Release Date Important features

Python 0.9.0 February 1991  Classes with inheritance exception handing


 Functions
 Modules

Python 1.0 January 1994 Functional programming tools(lambda, map, filter and reduce)

 Support for complex numbers.


 Functions with keyword arguments

Python 2.0 October 2000  List comprehension

Python 2.7.0 July 2010  Cycle-detecting garbage collector.

EOL-Jan 2020  Support for Unicode. Unification of data types and classes

Python 3 December 2008  Backward incompatible.

Python 3.6 December 2016  Print keyword changed to print() function

Python3.6.5 March 2018  raw_input() function depreciated


 Unified str()/Unicode types.
 Unititles for automatic conversion of Python 2.x code

Python 3.7.0 May 2018  New C API for thread-local-storage


 Built-in breakpoint()
 Data classes
 Context variables
 More…

Python 3.8 October 2019  Assignment Expression


 Positional-only parameters
 Parellel file system cache for compiled bytecode files
 More….

Python3.9-current October 2020  Dictionary Merge &Update Operators


version  New removeprefix() and remove suffix() string methods
 Bultin Generic Types

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 5


Ⅳ SEM BCA PYTHON

PYTHON IDES
Integrated Development Environments (IDEs) are coding tools that make writing,
debugging, and testing your code easier. Many provide helpful features like code
completion, syntax highlighting, debugging tools, variable explorers, visualization tools,
and many other features.

PYTHON COMMAND LINE

Python has two basic modes: script and interactive. The normal mode is the mode where
the scripted and finished .py files are run in the Python interpreter. Interactive mode is
a command line shell which gives immediate feedback for each statement, while running
previously fed statements in active memory. As new lines are fed into the interpreter, the
fed program is evaluated both in part and in whole.
Interactive mode is a good way to play around and try variations on syntax.
On macOS or linux, open a terminal and simply type "python". On Windows, bring up the
command prompt and type "py", or start an interactive Python session by selecting "Python
(command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI
which includes both an interactive mode and options to edit and run files.

Python Keywords

Keywords are predefined, reserved words used in Python programming that have special
meanings to the compiler. We cannot use a keyword as a variable name, function name, or
any other identifier. They are used to define the syntax and structure of the Python
language.

All the keywords except True, False and None are in lowercase and they must be written as
they are. The list of all the keywords is given below.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 6


Ⅳ SEM BCA PYTHON

Python Keywords List

False await else import pass

None break except in raise

True class finally is return

And continue for lambda try

As def from nonlocal while

Assert del global not with

Async elif if or yield

Python Identifiers

Identifiers are the name given to variables, classes, methods, etc. For example,

language = 'Python'.

Here, language is a variable (an identifier) which holds the value 'Python'.

We cannot use keywords as variable names as they are reserved names that are built-in to
Python. For example,

continue = 'Python'

The above code is wrong because we have used continue as a variable name.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 7


Ⅳ SEM BCA PYTHON

Rules for Naming an Identifier

 Identifiers cannot be a keyword.

 Identifiers are case-sensitive.

 It can have a sequence of letters and digits. However, it must begin with a letter
or _. The first letter of an identifier cannot be a digit.
 It's a convention to start an identifier with a letter rather _.
 Whitespaces are not allowed.

 We cannot use special symbols like !, @, #, $, and so on.

Some Valid and Invalid Identifiers in Python

Valid Identifiers Invalid Identifiers

score @core

return_value return

highest_score highest score

name1 1name

convert_to_string convert to_string

Things to Remember

 Python is a case-sensitive language. This means, Variable and variable


are not the same.
 Always give the identifiers a name that makes sense. While c = 10 is a
valid name, writing count = 10 would make more sense, and it would be

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 8


Ⅳ SEM BCA PYTHON

easier to figure out what it represents when you look at your code after a
long gap.
 Multiple words can be separated using an underscore,
like this_is_a_long_variable.

Expression in Python?

A combination of operands and operators is called an expression. The


expression in Python produces some value or result after being interpreted by
the Python interpreter. An expression in Python is a combination of operators
and operands.

Example :

x = 25 # a statement
x = x + 10 # an expression

print(x)

Output :

35

An expression in Python is very different from statements in Python. A


statement is not evaluated for some results. A statement is used for
creating variables or for displaying values.

An expression in Python can contain identifiers, operators, and operands.

Types of Expression in Python

We have various types of expression in Python, let us discuss them along with
their respective examples.

1. Constant Expressions

A constant expression in Python that contains only constant values is known


as a constant expression. A constant is a value that cannot be changed after its
initialization.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 9


Ⅳ SEM BCA PYTHON

Example :

x = 10 + 15

# Here both 10 and 15 are constants but x is a variable.


print("The value of x is: ", x)

Output :

The value of x is: 25

2. Arithmetic Expressions

An expression in Python that contains a combination of operators, operands,


and sometimes parenthesis is known as an arithmetic expression. Example :

x = 10

y=5

addition = x + y

subtraction = x - y

product = x * y

division = x / y

power = x**y

print("The sum of x and y is: ", addition)

print("The difference between x and y is: ", subtraction)

print("The product of x and y is: ", product)

print("The division of x and y is: ", division)

print("x to the power y is: ", power)

Output :

The sum of x and y is: 15


The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 10
Ⅳ SEM BCA PYTHON

x to the power y is: 100000

3. Integral Expressions

An integral expression in Python is used for computations and type


conversion (integer to float, a string to integer, etc.). An integral expression
always produces an integer value as a resultant.

Example :

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the floating-point number into an integer or vice versa for
summation.
result = x + int(y)

print("The sum of x and y is: ", result)

Output :

The sum of x and y is: 15

4. Floating Expressions

A floating expression in Python is used for computations and type conversion


(integer to float, a string to integer, etc.). A floating expression always
produces a floating-point number as a resultant.

Example :

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the integer number into a floating-point number or vice


versa for summation.
result = float(x) + y

print("The sum of x and y is: ", result)

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 11


Ⅳ SEM BCA PYTHON

Output :

The sum of x and y is: 15.0

5. Relational Expressions

A relational expression in Python can be considered as a combination of two


or more arithmetic expressions joined using relational operators. The overall
expression results in either True or False (boolean result). We have four types
of relational operators in Python (�.�.>,<,>=,<=)(i.e.>,<,>=,<=).

A relational operator produces a boolean result so they are also known


as Boolean Expressions.

Example :

a = 25
b = 14
c = 48
d = 45

# The expression checks if the sum of (a and b) is the same as the difference of (c
and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)

Output :

Type: <class 'bool'>


The result of the expression is: False

6. Logical Expressions

As the name suggests, a logical expression performs the logical computation,


and the overall expression results in either True or False (boolean result). We
have three types of logical expressions in Python.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 12


Ⅳ SEM BCA PYTHON

Operator Syntax Working


and �x and �y The expression return True if both �x and �y are true,
else it returns False.
or �x or �y The expression return True if at least one
of �x or �y is True.
not not �x The expression returns True if the condition
of �x is False.

Note :
In the table specified above, �x and �y can be values or another expression as
well.

Example :

from operator import and_

x = (10 == 9)
y = (7 > 5)

and_result = x and y
or_result = x or y
not_x = not x

print("The result of x and y is: ", and_result)


print("The result of x or y is: ", or_result)
print("The not of x is: ", not_x)

Output :

The result of x and y is: False


The result of x or y is: True
The not of x is: True

7. Bitwise Expressions

The expression in which the operation or computation is performed at the bit


level is known as a bitwise expression in Python. The bitwise expression
contains the bitwise operators.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 13


Ⅳ SEM BCA PYTHON

Example :

x = 25
left_shift = x << 1
right_shift = x >> 1

print("One right shift of x results: ", right_shift)


print("One left shift of x results: ", left_shift)

Output :

One right shift of x results: 12


One left shift of x results: 50

8. Combinational Expressions

As the name suggests, a combination expression can contain a single or


multiple expressions which result in an integer or boolean value depending
upon the expressions involved.

Example :

x = 25
y = 35

result = x + (y << 1)

print("Result obtained : ", result)

Output :

Result obtained: 95

Whenever there are multiple expressions involved then the expressions are
resolved based on their precedence or priority. Let us learn about the
precedence of various operators in the following section.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 14


Ⅳ SEM BCA PYTHON

Variables

Python Variable is containers that store values. Python is not “statically typed”.
We do not need to declare variables before using them or declare their type. A
Python variable is a name given to a memory location.

Var = "Sapient"
print(Var)

Rules for Python variables

 A Python variable name must start with a letter or the underscore


character.
 A Python variable name cannot start with a number.
 A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
 Variable in Python names are case-sensitive (name, Name, and NAME
are three different variables).
 The reserved words(keywords) in Python cannot be used to name the
variable in Python.

Variables Assignment in Python

Here, we have assigned a number, a floating point number, and a string to a


variable such as age, salary, and name.

# An integer assignment

age = 45

# A floating point

salary = 1456.8

# A string

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 15


Ⅳ SEM BCA PYTHON

name = "John"

print(age)

print(salary)

print(name)

Output:

45

1456.8

John

Declaration and Initialization of Variables

Let‟s see how to declare the variable and print the variable.

# declaring the var

Number = 100

# display

print( Number)

Output:

100

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 16


Ⅳ SEM BCA PYTHON

Python Assign Values to Multiple Variables

Also, Python allows assigning a single value to several variables simultaneously


with “=” operators.
For example:

a = b = c = 10

print(a)

print(b)

print(c)

Output:

10

10

10

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 17


Ⅳ SEM BCA PYTHON

Assigning different values to multiple variables

Python allows adding different values in a single line with “,” operators.

a, b, c = 1, 20.2, "Sapient"

print(a)

print(b)

print(c)

Output:

20.2

Sapient

Python Operators

The operator is a symbol that performs a certain operation between two


operands, according to one definition. In a particular programming language,
operators serve as the foundation upon which logic is constructed in a
programme. The different operators that Python offers are listed here.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 18


Ⅳ SEM BCA PYTHON

Arithmetic Operators

Arithmetic operations between two operands are carried out using arithmetic
operators. It includes the exponent (**) operator as well as the + (addition), -
(subtraction), * (multiplication), / (divide), % (reminder), and // (floor division)
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 = 10, b = 10 => a+b = 20

- (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 = 5 => a - b = 15

/ (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
(Multiplication) = 4 => a * b = 80

% (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) As it calculates the first operand's power to the second operand, it is an


exponent operator.

//(Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 19


Ⅳ SEM BCA PYTHON

Comparison operator

Comparison operators compare the values of the two operands and return a true
or false Boolean value in accordance. The following table lists the comparison
operators.

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.

<= The condition is met if the first operand is smaller than or equal to the second
operand.

>= The condition is met if the first operand is greater than or equal to the second
operand.

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

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 20


Ⅳ SEM BCA PYTHON

Assignment Operators

The right expression's value is assigned to the left operand using the
assignment operators. The following table provides a description of the

Operator Description

= It assigns the value of the right expression to the left operand.

+= By multiplying the value of the right operand by the value of the left operand,
the left operand receives a changed value. 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.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 21


Ⅳ SEM BCA PYTHON

Bitwise Operators

The two operands' values are processed bit by bit by the bitwise operators.
Consider the case below.

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 A 1 is copied to the result if both bits in two operands at the same location
and) are 1. If not, 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 If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)

~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the
next bit will be 1, and vice versa.

<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of
the value of the left operand.

>> (right The left operand is moved right by the number of bits present in the right
shift) operand.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 22


Ⅳ SEM BCA PYTHON

Logical Operators

The assessment of expressions to make decisions typically makes use of the


logical operators. The following logical operators are supported by Python.

Operator Description

and The condition will also be true if the expression is true. If the two expressions
a and b are the same, then a and b must both be true.

or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.

not If an expression a is true, then not (a) will be false and vice versa.

Membership Operators

The membership of a value inside a Python data structure can be verified using
Python membership operators. The result is true if the value is in the data
structure; otherwise, it returns false.

Operator Description

in If the first operand cannot be found in the second operand, it is evaluated to


be true (list, tuple, or dictionary).

not in If the first operand is not present in the second operand, the evaluation is
true (list, tuple, or dictionary).

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 23


Ⅳ SEM BCA PYTHON

Operator Description

is If the references on both sides point to the same object, it is determined to be


true.

is not If the references on both sides do not point at the same object, it is
determined to be true.

Precedence and Associativity of Operators in Python


When dealing with operators in Python we have to know about the concept of
Python operator precedence and associativity as these determine the priorities
of the operator otherwise, we‟ll see unexpected outputs.

Operator Precedence: This is used in an expression with more than one


operator with different precedence to determine which operation to perform
first.
-

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 24


Ⅳ SEM BCA PYTHON

Example: Solve
10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30

Code:

# Precedence of '+' & '*'

expr = 10 + 20 * 30

print(expr)

Output:
610

Operator Associativity: If an expression contains two or more operators with


the same precedence then Operator Associativity is used to determine. It can
either be Left to Right or from Right to Left.
Example: „*‟ and „/‟ have the same precedence and their associativity
is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) *
10”.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 25


Ⅳ SEM BCA PYTHON

Code:

# Left-right associativity

# 100 / 10 * 10 is calculated as

# (100 / 10) * 10 and not

# as 100 / (10 * 10)

print(100 / 10 * 10)

Output:
100

Operators Precedence and Associativity are two main characteristics of


operators that determine the evaluation order of sub-expressions in
absence of brackets.
Example: Solve
100 + 200 / 10 - 3 * 10

100 + 200 / 10 - 3 * 10 is calculated as 100 + (200 / 10) - (3 * 10)

and not as (100 + 200) / (10 - 3) * 10

Please see the following precedence and associativity table for reference. This
table lists all operators from the highest precedence to the lowest precedence.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 26


Ⅳ SEM BCA PYTHON

Operator Description Associativity

() Parentheses left-to-right

** Exponent right-to-left

* / % Multiplication/division/modulus left-to-right

+ – Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to


left-to-right
> >= Relational greater than/greater than or equal to

== != Relational is equal to/is not equal to left-to-right

is, is not Identity


left-to-right
in, not in Membership operators

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 27


Ⅳ SEM BCA PYTHON

Operator Description Associativity

not Logical NOT right-to-left

and Logical AND left-to-right

or Logical OR left-to-right

= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
right-to-left
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

Data types

Data types are the classification or categorization of data [Link] following are the
standard or built-in data types in Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
Binary Types( memory view, byte array, bytes)

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 28


Ⅳ SEM BCA PYTHON

Numeric Data Type in Python


The numeric data type in Python represents the data that has a numeric value. A
numeric value can be an integer, a floating number, or even a complex number..
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an
integer value can be.
Float – This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific
notation.
Complex Numbers – Complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j.
For example – 2+3j
'float'>
Sequence Data Type in Python
The sequence Data Type in Python is the ordered collection of similar or different data
types.. There are several sequence types in Python –
 Python String
 Python List
 Python Tuple

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 29


Ⅳ SEM BCA PYTHON

String Data Type


Strings in Python are arrays of bytes representing Unicode characters. A string is a
collection of one or more characters put in a single quote, double-quote, or triple-
quote.. It is represented by str class.

List Data Type


Lists are just like arrays, declared in other languages which is an ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.

Creating List :
Lists in Python can be created by just placing the sequence inside the square
brackets[].

List = ["Geeks", "For", "Geeks"]

Tuple Data Type


Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples cannot be
modified after it is created. It is represented by a tuple class.

Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by a „comma‟
with or without the use of parentheses for grouping the data sequence. Tuples can
contain any number of elements and of any data type (like strings, integers, lists, etc.).

Note: Tuples can also be created with a single element, but it is a bit tricky. Having
one element in the parentheses is not sufficient, there must be a trailing „comma‟ to
make it a tuple.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 30


Ⅳ SEM BCA PYTHON

# Creating a Tuple with

# the use of Strings

Tuple1 = ('Geeks', 'For')

print("\nTuple with the use of String: ")

print(Tuple1)

# Creating a Tuple with the

# use of built-in function

Tuple1 = tuple('Geeks')

print("\nTuple with the use of function: ")

print(Tuple1)

Tuple with the use of String:


('Geeks', 'For')
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')

Boolean Data Type in Python


Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy(true), and those equal to False are falsy (false). But non-
Boolean objects can be evaluated in a Boolean context as well and determined to be
true or false. It is denoted by the class bool.
Note – True and False with capital „T‟ and „F‟ are valid booleans otherwise python will
throw an error.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 31


Ⅳ SEM BCA PYTHON

defined
Set Data Type in Python
In Python, a Set is an unordered collection of data types that is iterable, mutable and
has no duplicate elements. The order of elements in a set is undefined though it may
consist of various elements.

Create a Set in Python


Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by a „comma‟. The
type of elements in a set need not be the same, various mixed-up data type values can
also be passed to the set.

# Python program to demonstrate

# Creation of Set in Python

# Creating a Set

set1 = set()

print("Initial blank Set: ")

print(set1)

# Creating a Set with

# the use of a String

set1 = set("GeeksForGeeks")

print("\nSet with the use of String: ")

print(set1)

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 32


Ⅳ SEM BCA PYTHON

Output:

Initial blank Set:


set()

Set with the use of String:


{'F', 'o', 'G', 's', 'r', 'k', 'e'}
alues
Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data
values like a map, unlike other Data Types that hold only a single value as an element,
a Dictionary holds a key: value pair.

Create a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly
{} braces, separated by „comma‟. Values in a dictionary can be of any datatype and can
be duplicated, whereas keys can‟t be repeated and must be immutable. The dictionary
can also be created by the built-in function dict(). An empty dictionary can be created
by just placing it in curly braces{}. Note – Dictionary keys are case sensitive, the same
name but different cases of Key will be treated distinctly.

# Creating an empty Dictionary

Dict = {}

print("Empty Dictionary: ")

print(Dict)

# Creating a Dictionary

# with Integer Keys

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 33


Ⅳ SEM BCA PYTHON

print("\nDictionary with the use of Integer Keys: ")

print(Dict)

Output:
Empty Dictionary:
{}

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Python Indentation

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for


readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Syntax Error:

if 5 > 2:
print("Five is greater than two!")

You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:

Example

Syntax Error:

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 34


Ⅳ SEM BCA PYTHON

if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!"

Comments

Comments in Python are the lines in the code that are ignored by the interpreter
during the execution of the program. Comments enhance the readability of the code
and help the programmers to understand the code very carefully.
There are three types of comments in Python:
 Single line Comments
 Multiline Comments
 Docstring Comments

Types of Comments in Python:

Single-Line Comments in Python


Python single-line comment starts with the hashtag symbol (#) with no
white spaces and lasts till the end of the line.

Multi-Line Comments in Python


Python does not provide the option for multiline comments. We can use multiple
hashtags (#) to write multiline comments in Python. Each and every line will be
considered as a single-line comment.

# Python program to demonstrate

# multiline comments

print("Multiline comments")

Docstring in Python
Python docstring is the string literals with triple quotes that are appeared right after
the function. It is used to associate documentation that has been written with Python
modules, functions, classes, and methods. It is added right below the functions,

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 35


Ⅳ SEM BCA PYTHON

modules, or classes to describe what they do. In Python, the docstring is then made
available via the __doc__ attribute.
Example:

def multiply(a, b):

"""Multiplies the value of a and b"""

return a*b

# Print the docstring of multiply function

print(multiply.__doc__)

Output:
Multiplies the value of a and b

Advantages of comments in Python


 Comments are generally used for the following purposes:
 Code Readability
 Explanation of the code or Metadata of the project
 Prevent execution of code
 To include resources

Console Input and Console Output

The interactive shell in Python is treated as a console. We can take the user
entered data the console using input() function.

Example

# taking input from the user


a = input(print(“enter any text”))
# printing the data
print("User data:-", a)

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 36


Ⅳ SEM BCA PYTHON

Output

If you run the above code, then you will get the following result.

Enter any text: Sapient


User data:- Sapient
The data that is entered by the user will be in the string format.

Console Output

To print strings to console or echo some data to console output, use Python
inbuilt print() function.

print() function can take different type of values as argument(s), like string,
integer, float, etc., or object of a class type.

The following is a simple demonstration of how to use print() function in a


Python shell.

>>> print("Hello World.")

Hello World.

>>> print(10)

10

Type Conversion in Python

Type conversion is the transformation of a one type of data into another type
of data.

In Python, there are two kinds of type conversion:

o Explicit Type Conversion-The programmer must perform this task


manually.
o Implicit Type Conversion-By the Python program automatically.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 37


Ⅳ SEM BCA PYTHON

Implicit Type Conversion

Implicit character data conversion is the term used in Python when a data type
conversion occurs whether during compilation or even during runtime. We do
not need to manually change the file format into some other type of data
because Python performs the implicit character data conversion

Without user input, the Programming language automatically changes one data
type to another in implicit shift of data types.

1. x = 20
2. print("x type:",type(x)
3. y = 0.6
4. print("y type:",type(y))
5. a=x+y
6. print(a)
7. print("z type:",type(z))

Output:

x type: <class 'int'>


y type: <class 'float' >20.6
a type: <class 'float'>

Explicit Type Conversion:

To change a number from a higher data type to a lower data type. Implicit type
conversion is ineffective in this situation, as we observed in the previous
section. Explicit type conversion, commonly referred to as type casting, now
steps in to save the day. Using built-in Language functions like str() to convert
to string form and int() to convert to integer type, a programmer can explicitly
change the data form of an object by changing it manually.

num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 38


Ⅳ SEM BCA PYTHON

num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Run Code

Output

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

Python Libraries

A Python library is also a group of interconnected modules. It contains code


bundles that can be reused in a variety of programs. It simplifies and facilitates
Python programming for programmers. Because then we won't have to write
the very same code for different programs. Machine learning, computer science,
data visualization, and other fields rely heavily on Python libraries.

The library files have a DLL extension in the MS Windows environment


(Dynamic Load Libraries). When we import a library to our program and run it,
the linker looks for that library automatically. It extracts the library's functions
and then interprets the program accordingly. This is how we use library
methods in our program.

Standard Libraries of Python

Matplotlib

The plotting of numerical data is the responsibility of this library. It's for this
reason that it's used in analysis of data.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 39


Ⅳ SEM BCA PYTHON

NumPy

NumPy ,focuses on mathematical and scientific [Link] Python, NumPy


is recommended over lists because it uses less memory, is faster, and is more
convenient.

Pandas

In the domain of data science, this well-known library is widely used. They're
mostly used for analysis, manipulation, and cleaning of data,

SciPy

It is an open-source library, especially designed for scientific computing,


information processing, and high-level computing.

Scikit- learn

Scikit-learn is also an open-source machine learning library based on Python.


Both supervised and unsupervised learning processes can be used in this
library. Popular algorithms and the SciPy, NumPy, and Matplotlib packages are
all already pre-included in this library. The most well-known Scikit-most-learn
application is for Spotify music recommendations.

Seaborn

Visualization of statistical models is possible with this package. The library is


largely based on Matplotlib and enables the formation of statistical graphics
via:

Tens or Flow

Tens or Flow is an open-source numerical calculation library with high


performance. Deep learning and ML algorithms make use of it as well.

Keras

Keras is a Python-based open-source neural network library that makes it


possible for us to examine deep neural networks deeply

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 40


Ⅳ SEM BCA PYTHON

Scrapy

Scrapy is a web scraping tool that scrapes multiple pages in under a minute.
Scrapy is also an open-source Python library framework for extracting data
from websites.

PyGame

This library provides a simple interface for the graphics, audio, and input
libraries of the Standard Direct media Library (SDL) which can work on any
platform. It's used to make video games with the Python programming
language and computer graphics and acoustic libraries.

PyBrain

PyBrain is a fast and simple machine learning library compared to the other
Python learning libraries. PyBrain is also an open-source library for ML
algorithms for every entry-level scholar in research from the available Python
libraries.

Statsmodels

Statsmodels is a Python library that helps with statistical model analysis and
estimation. The library is used to run statistical tests and other tasks, resulting
in high-quality results.

Importing Libraries

Import in python is similar to #include header_file in C/C++. Python modules


can get access to code from another module by importing the file/function
using import.

import module_name

When the import is used, it searches for the module initially in the local scope
by calling __import__() function. The value returned by the function is then
reflected in the output of the initial code.

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 41


Ⅳ SEM BCA PYTHON

import math

pie = [Link]

print("The value of pi is : ",pie)

Output:

The value of pi is : ', 3.141592653589793

import module_name.member_name

In the above code module, math is imported, and its variables can be accessed
by considering it to be a class and pi as its object.
The value of pi is returned by __import__(). pi as a whole can be imported into
our initial code, rather than importing the whole module.

from math import pi

# Note that in the above example,

# we used [Link]. Here we have used

# pi directly.

print(pi)

Output:

3.141592653589793

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 42


Ⅳ SEM BCA PYTHON

from module_name import *

In the above code module, math is not imported, rather just pi has been
imported as a variable. All the functions and constants can be imported using
*.

from math import *

print(pi)

print(factorial(6))

Output

3.14159265359

720

ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 43

You might also like