0% found this document useful (0 votes)
9 views

UNIT 1-2

This document serves as an introduction to Python programming, covering fundamental concepts such as syntax, variables, data types, and operators. It emphasizes Python's readability, versatility, and its use in data analysis through various libraries. The document also discusses the importance of indentation and operator precedence in Python code structure.

Uploaded by

Aarush Chauhan
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)
9 views

UNIT 1-2

This document serves as an introduction to Python programming, covering fundamental concepts such as syntax, variables, data types, and operators. It emphasizes Python's readability, versatility, and its use in data analysis through various libraries. The document also discusses the importance of indentation and operator precedence in Python code structure.

Uploaded by

Aarush Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Department of Computer Science

IMS Engineering College

UNIT – 1
INTRODUCTION TO PYTHON

Course Outcome: Interpret the fundamental python syntax and semantics and be fluent in the
use of python control flow statements.

Topic Coverage
Python Variables, Python Basic Operators, Understanding Python Blocks, Python Data Types,
Declaring and Using Numeric Data Types: int, float etc.

Introduction

Python is a powerful and flexible high-level programming language. It is an interactive


programming language that uses concise and easy-to-learn syntax. It enables programmers to
develop complex programs in a much shorter time. Python was developed in 1991 by Guido
Van Rossum in National Research Institute for Mathematics and Computer Science,
Netherlands. The programming language was named Python after the comedy show Monty
Python’s Flying Circus. The main emphasis in Python is on code readability, shorter codes and
ease of writing. Programmers can express logical concepts in fewer lines of code and can use
several inbuilt functions and libraries provided by Python. Various versions of the Python have
been released till date ranging from version 1.0. The recent version of Python is version 3.

Python is a versatile programming language that offers powerful libraries and frameworks for
data analysis, such as NumPy, Pandas, Matplotlib and Scikit-learn. These libraries provide
efficient data structures, advanced statistical analysis capabilities and extensive data
visualization options. It can handle large datasets, performing complex data transformations
and implementing sophisticated statistical models and machine learning algorithms. It offers a
wide range of tools and packages for data exploration, pre-processing, modelling and
evaluation. Python promotes automation, reproducibility and scalability. It allows user to write
reusable code, create workflows and automate repetitive tasks, making it suitable for large-
scale data analytics projects.

Python IDLE
IDLE stands for Integrated Development and Learning Environment. Python IDLE consist of
Python shell and Python Editor. Python shell is an interactive interpreter that reads the Python
code typed by the user and when user press enter key, displays the output. Figure 1 represents
the home screen of Python shell. The variables and functions declared and defined in the shell
exist only during IDLE session. When user exit the IDLE session and start another session, all
computations need to be done again. However, this is not the convenient way of writing code
that needs to be reused later.
Python Editor allows user to work in script mode. User can write the code/program in the editor
and save it in a file, called source file or source code, for later use. Python source files must be
saved with .py or .pyw extension.
Python Programming 1 HUNNY GAUR
(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Fig 1. Python Shell Home Screen

Python Variables and Assignment Statements

A variable is a name given to a value so that it can be used and manipulated later. A program
generally carries out variable manipulations to carry out desired result. For example, if the
program is required to store the marks of a student in various subjects, then it can be achieved
by using the following statement in Python:

When this statement will be executed, python will associate the variable maths with the value
98. Such a statement that assigns a value to a variable is called assignment statement. The right-
hand side of the assignment statement can be an expression also. For example, if the statement
is required to calculate the sum of the marks scored in two subjects and assigning the sum to a
variable then it can be done as:

The syntax of the assignment statement is as follows:


Variable = value or expression
Python also allows multiple assignments in a single statement. The above example can be
executed as:

Python also allow assigning a common value to multiple variables.

Python impose certain rules while declaring any name as variable. These are:
• A variable name must begin with a lowercase, uppercase character or special character
_ (underscore).
• A variable name may contain any number of characters, digits or underscore.
• A variable name cannot contain any other special character.
• A variable name having more than one word cannot contain space between words.

Python Programming 2 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Python Basic Operators

Operators are the foundations of any programming language. Python supports following set of
operators:

• Arithmetic Operators: Used to perform basic mathematical operations.

Operator Form Operation Example


Addition Adds value of y to value of
x+y
(+) x.
Subtraction Subtract value of y from
x-y
(-) value of x.
Multiplication Multiplies value of x with
x*y
(*) value of y.
Division Divides value of x by value
x/y
(/) of y and gives quotient.
Divides value of x by value
Floor Division of y and gives quotient in
x // y
( // ) which decimal part is
removed.
Modulus Divides value of x by value
x%y
(%) of y and gives remainder.
Exponentiation Calculates x raise to the
x ** y
( ** ) power y.

• Relational Operators: Used to compare values and return Boolean value (True or
False).

Operator Form Operation Example


Greater than Return True if x is greater than
x>y
(>) y, otherwise False.
Greater than or
Return True if x is greater than
equal to x >= y
or equal to y otherwise False.
( >= )
Less than Return True if x is less than y,
x<y
(<) otherwise False.
Less than or
Return True if x is less than or
equal to x <= y
equal to y, otherwise False.
(<= )
Equal to Return True if x and y are
x == y
(==) equal, otherwise False.

Python Programming 3 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Not Equal to Return True if x and y are not


x != y
( != ) equal, otherwise False.

• Logical Operators: Used to join multiple conditions, where each condition returns
either True or False. The output of the logical operators is either True or False.

Operator Form Operation Example

Return True if both


Logical AND
x and y conditions x and y are True,
( and )
otherwise False.

Return True if either of the


Logical OR
x or y conditions x or y is True,
( or )
otherwise False.

Return True if the condition


Logical NOT
not x x is False and return False if
( not )
the condition x is True.

• Bitwise Operators: operates on integers interpreted as strings of binary digits 0 and 1.


The input and output of the bitwise operator is integer.

Operator Form Operation Example


10 & 6 gives 2:

10: 00001010
A bit in x & y is 1 if bits
Bitwise AND 6: 00000110
x&y in each of x and y is 1,
(&) ------------------
otherwise 0.
2: 00000010
------------------

10 | 6 gives 14:

A bit in x | y is 1 if at 10: 00001010


Bitwise OR least one of the bits 6: 00000110
x|y
(|) either in x or y is 1, ------------------
otherwise 0. 14: 00001110
------------------

Bitwise A bit in ~x is 1 if bit in ~11 gives -12:


Complement ~x x is 0.
(~) A bit in ~x is 0 if bit in 11: 00001011

Python Programming 4 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

x is 1. ------------------
The result obtained ~11: 11110100
from the operation is - -------------------
x-1. Here, 11110100
is the 2’s
complement of
12: 00001100

10 ^ 6 gives 12:
A bit in x ^ y is 1 if bits 10: 00001010
Bitwise Exclusive in x and y are opposite
6: 00000110
OR x^y to each other. If bits in x
(^) and y are same, the ------------------
output is 0. 12: 00001100
------------------

Bits in binary
representation of x are 5 << 2 gives 20:
shifted left by y places.
Rightmost y bits of the
Left Shift 5: 00000101
x << y result are filled with
( << ) ------------------
zeros.
20: 00010100
The result obtained
from this operation is ------------------
x*2y .
Bits in binary
representation of x are
shifted right by y 5 >> 2 gives 1:
places.
Right Shift Leftmost y bits of the 5: 00000101
x >> y
( >> ) result are filled with ------------------
sign bit. 1: 00000001
The result obtained ------------------
from this operation is
x/2y .

Operator Precedence and Associativity

Operators have different levels of precedence that determines the order in which operators are
evaluated. When multiple operators are present in an expression, operators having higher
precedence are evaluated first. However, if two or more operators have same precedence then
their associativity determines the order of evaluation.

Precedence Operator Associativity


1 Parentheses ( ) Left to Right
2 Exponential (**) Right to Left
3 Positive (+), Negative (-), Bitwise NOT (~) Right to Left

Python Programming 5 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

4 Multiplication (*), Division (/), Floor Division (//), Left to Right


Modulus (%)
5 Addition (+), Subtraction (-) Left to Right
6 Left shift (<<), Right shift(>>) Left to Right
7 Bitwise AND (&) Left to Right
8 Bitwise XOR (^) Left to Right
9 Bitwise OR ( | ) Left to Right
10 Membership (in, not in), Comparison (is, is not, <, Left to Right
<=, >, >=, !=, = =)
11 Boolean Not (not) Right to Left
12 Boolean And (and) Left to Right
13 Boolean Or (or) Left to Right

Understanding Python Blocks – Indentation

Indentation is important in Python because it determines the structure and readability of the
code. In Python, indentation has semantic meaning and directly impacts how the code is
executed.
Few reasons that why indentation plays a vital role in Python are:
• Python enforces indentation as part of its syntax rules. The Python interpreter expects
consistent indentation levels to interpret the code correctly. The standard convention is
to use 4 spaces for each level of indentation.
• Python uses indentation to define code blocks, such as loops, conditional statements
and function definitions. By indenting a block of code, it is specified that the statements
belongs to a particular structure. For example, in an if block, the indented code block
following the if condition is executed only if the condition is true. Without proper
indentation, the code block will not be recognized.

• Indentation helps in avoiding ambiguity and improves code clarity. Without


indentation, it can be challenging to differentiate between blocks of code, especially
when dealing with nested structures.

Python Data Types

A data type is a classification of the type of data that a variable can hold in a computer program.
Data types are an important factor in all computer programming languages. Every value in
Python has a data type. Following standard built-in data types are supported by Python:
1. Numbers
i. Integer Numbers (int and long)
ii. Real/Floating point Numbers (float)

Python Programming 6 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

iii. Complex Numbers (complex)


2. Boolean (bool)
3. Sets
4. Sequence
i. String (str)
ii. List (list)
iii. Tuple (tuple)
5. Dictionary (dict)
6. Special Data Type – None

Numbers:
• Numbers data types are used to store numeric values that include integer numbers,
floating point numbers and complex numbers.
• Integer numbers are numbers without a decimal point. An integer number consists of a
sequence of digits preceded by an optional sign (plus + or minus -). Integers can be of
any length and are only limited by the memory available in the computer system. They
are defined as int class in Python. For Example, 3007, -1278, 38261661.
• Real/Floating point numbers are numbers with a fractional part followed by an optional
exponent part. A floating point number can have up to 16 decimal places. They are
defined as float class in Python. For example, 92.45, -3211.43, 0.667.
• Complex numbers are represented in Python in the form a + bi where a and b are
integer/floating point numbers and i is the imaginary part. Number a represents the real
part of the complex number and b represents the imaginary part of the complex number.
They are defined as complex class in Python. For example, 4+8i, -3.7-2.9i, 3+0i.

Boolean:
• Boolean data types represents truth values True and False. It is defined as bool class in
Python.
• Bool type is considered as a subtype of int where Boolean value False behave as value
0 and Boolean value True behave as value 1.
• If used in arithmetic expression, during evaluation of arithmetic expression, value 0 is
used at the place of False and value 1 is used at the place of True.
• For example, the expression 7 + True will result as 8. And the expression 6 + False
will result as 6.

Sets:
• A set is a collection of unique elements that are not in a particular order.
• In Python, set has same definition with the following additional conditions:
• The elements of the sets cannot be modified (but set as a whole is mutable).

Python Programming 7 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• No index is attached with the set elements, hence, it does not support slicing and
indexing operation.
• Set in Python is represented within a pair of curly braces. And is created using the set()
function (which create empty set) or by defining the elements of the set within a pair of
curly braces.
• For example:
• Creating empty set:

• Defining elements of a set

• type(variable name) function can be used to check the data type of the variable.

Sequence:
• In Python, sequence is a generic term for an ordered set of elements.
• Three types of sequences in Python are: String, List and Tuple.
• String:
• A string is a sequence of characters. Single quotes or double quotes can be used to
represent string. Multi-line strings can be represented using triple quotes. They are
defined as str class in Python.
• For example:

• List:
• A list is an ordered sequence of heterogeneous items (items with different data
types) enclosed in square brackets. They are defined as list class in Python.
• A list can be modified. New items can be added, existing items can be deleted or
changed.
• Empty list can be created by either assigning blank pair of square brackets to the
variable or by calling the list( ) function.
• List with elements can be created by defining elements within a pair of square
brackets.

Python Programming 8 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• For example:

• Tuple:
• A tuple is also an ordered collection of heterogeneous items but enclosed in
brackets.
• A tuple is non-editable i.e., tuple is immutable. Once created, it cannot be modified.
• Tuples are mainly used to write-protect data and are usually much faster than list
because it cannot change dynamically.
• Empty tuple can be created by either assigning blank pair of brackets to the variable
or by calling the tuple( ) function.
• Tuple with elements can be created by defining elements within a pair of brackets.
• A tuple containing only one element is called singleton tuple and is defined by
attaching a comma with the element. If comma is not attached with element then
the element is considered as int or float.
• For example:

Python Programming 9 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Dictionary:
• A dictionary is an unordered collection of key-value pairs, enclosed within a pair of
curly brackets. The key-value pairs are separated by comma.
• The values in the dictionary are accessed by their keys. However, keys cannot be
accessed by using the values.
• Keys in the dictionary are similar to the indexes in the sequence.
• They are defined as dict class in Python.
• An empty dictionary can be created by defining opening and closing curly braces or by
calling the dict( ) function.
• Dictionary with elements can be created by defining elements (key-value pair) within
a pair of curly brackets.
• For example:

Special Data Type:


• None is a special data type in Python.
• None data type has no value.
• It is useful when a function returns no specific value. In such a scenario, None is
returned by the function.

Keywords

Keywords are the reserved words already defined by programming language for specific uses.
Keywords cannot be used for any other purpose. Therefore, programmers need to be careful
while writing the code that none of the user defined names used in the program should match
with the keywords.

Python Programming 10 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

The following words are defined as keywords in Python:


if elif else def return class
while and or del import as
finally is nonlocal global from raise
break continue pass try lambda not

assert True False with yield for


except None in

Comments in Python

• Single line comments are given in python using ‘#’ (hash) symbol.
• For multi-line comments triple-quotes are used.

Python Programming 11 HUNNY GAUR


(BCC302) Assistant Professor

You might also like