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

Python 1st Unit

The document discusses various data types in Python including integers, floats, strings, lists, tuples, sets and dictionaries. It also covers operators in Python like arithmetic, comparison, logical, bitwise and assignment operators.

Uploaded by

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

Python 1st Unit

The document discusses various data types in Python including integers, floats, strings, lists, tuples, sets and dictionaries. It also covers operators in Python like arithmetic, comparison, logical, bitwise and assignment operators.

Uploaded by

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

B.

TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA


UNIT – II: Types, Operators and Expressions:

Types - Integers, Strings, Booleans:

Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.

There are various data types in Python. Some of the important types are listed below.

Python Numbers

Integers, floating point numbers and complex numbers falls under Python numbers category. They
are defined as int, float and complex class in Python.

We can use the type() function to know which class a variable or a value belongs to and the
isinstance() function to check if an object belongs to a particular class.

 Integers can be of any length, it is only limited by the memory available.


 A floating point number is accurate up to 15 decimal places. Integer and floating points are
separated by decimal points.
 Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.

Python List

 List is an ordered sequence of items.


 It is one of the most used datatype in Python and is very flexible.
 All the items in a list do not need to be of the same type.
 Declaring a list is pretty straight forward. Items separated by commas are enclosed within [
].
P. Veera Prakash 1|Page
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Python Tuple

 Tuple is an ordered sequence of items same as list.


 The only difference is that tuples are immutable.
 Tuples once created cannot be modified.
 Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.
 It is defined within parentheses where items are separated by commas.

P. Veera Prakash 2|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Python Strings

String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings. st

Python Set

Set is an unordered collection of items. Set is defined by values separated by comma inside braces
{ }. Items in a set are not ordered.

Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [ ] does
not work.
P. Veera Prakash 3|Page
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates.

Python Dictionary

 Dictionary is an unordered collection of key-value pairs.


 It is generally used when we have a huge amount of data.
 Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.
 In Python, dictionaries are defined within braces with each item being a pair in the form
key:value. Key and value can be of any type.

P. Veera Prakash 4|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Conversion between data types

We can convert between different data types by using different type conversion functions like int(),
float(), str() etc.

We can even convert one sequence to another.

P. Veera Prakash 5|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Python Operators

In this article, you'll learn everything about different types of operators in Python, their syntax and
how to use them with examples.

Operators are special symbols in Python that carry out arithmetic or logical computation. The
value that the operator operates on is called the operand.

For example:

>> 2 + 3
5

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation.

Python has a number of operators which are classified below.

Type of operators in Python:

 Arithmetic Operators
 Comparison (Relational) Operators
 Logical (Boolean) Operators
 Bitwise Operators
 Assignment Operators
 Special Operators

Arithmetic operators:

 Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication etc.

Operator Meaning Example


x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
x % y (remainder of
% Modulus - remainder of the division of left operand by the right
x/y)
Floor division - division that results into whole number adjusted to
// x // y
the left in the number line
x**y (x to the
** Exponent - left operand raised to the power of right
power y)

P. Veera Prakash 6|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Comparison operators:

Comparison operators are used to compare values. It either returns True or False according to the
condition.

Operator Meaning Example


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

Logical operators:

Logical operators are the and, or, not operators.

Logical operators in Python


Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Bitwise operators:

Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit,
hence the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Bitwise operators in Python


Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)

P. Veera Prakash 7|Page


B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Assignment operators:
 Assignment operators are used in Python to assign values to variables.
 a = 10 is a simple assignment operator that assigns the value 10 on the right to the variable a
on the left.
 There are various compound operators in Python like a += 10 that adds to the variable and
later assigns the same. It is equivalent to a = a + 10.

Assignment operators in Python


Operator Example Equivatent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

Special operators:

Python language offers some special type of operators like the identity operator or the membership
operator.

They are described below with examples.

Identity operators:

is and is not are the identity operators in Python. They are used to check if two values (or variables)
are located on the same part of the memory. Two variables that are equal do not imply that they are
identical.

Identity operators in Python


Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True

Membership operators:
P. Veera Prakash 8|Page
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
in and not in are the membership operators in Python. They are used to test whether a value or
variable is found in a sequence (string, list, tuple, set and dictionary).

In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x

Practice on Python operators:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

>>> #ARITHMETIC OPERATORS


>>> a = 5
>>> b = 8
>>> a
5
>>> b
8
>>> a + b
13
>>> a - b
-3
>>> a
5
>>> b
8
>>> a * b
40
>>> a / b
0.625
>>> a // b
0
>>> a % b
5
>>> a = 5
>>> RELATIONAL OPERATORS
SyntaxError: invalid syntax
>>> a == b
False
>>> a . b
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
a.b
AttributeError: 'int' object has no attribute 'b'
P. Veera Prakash 9|Page
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
>>> a > b
False
>>> a < b
True
>>> a != b
True
>>> a <> b
SyntaxError: invalid syntax
>>> a >= b
False
>>> a <= b
True
>>> #ASSIGNMENT OPERATORS
>>> a = 10
>>> a
10
>>> a += 1 # a = a + 1
>>> a
11
>>> a -= 1 # a = a - 1
>>> a
10
>>> a *= 2 # a = a* 2
>>> a
20
>>> a /= 2 # a = a/2
>>> a
10.0
>>> a //= 2 # a = a // 2
>>> a
5.0
>>> a %= 2 # a = a % 2
>>> a
1.0
>>> a **= 2
>>> a
1.0
>>> #BITWISE OPERATORS
>>> bin(a)
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
bin(a)
TypeError: 'float' object cannot be interpreted as an integer
>>> del a
>>> del b
>>> bin(a)
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
bin(a)
NameError: name 'a' is not defined
>>> a = 10
>>> bin(a)
P. Veera Prakash 10 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
'0b1010'
>>> bin(2)
'0b10'
>>> a = 60
>>> bin(a)
'0b111100'
>>> b = 13
>>> bin(b)
'0b1101'
>>> a & b
12
>>> 26 & 14
10
>>> 26 | 14
30
>>> 26 ^ 14
20
>>> ~15
-16
>>> 12 << 2
48
>>> 12 >> 2
3
>>> a
60
>>> del a
>>> del b
>>> a = True
>>> b = False
>>> a and b
False
>>> c = True
>>> a and c
True
>>> c and b
False
>>> a or b
True
>>> a or c
True
>>> c or b
True
>>> not (a & b)
True
>>> not (a | b)
False
>>> MEMBERSHIP OPERATORS
>>> list1 = [1,2,3,4,5,67,8]
>>> list1
[1, 2, 3, 4, 5, 67, 8]
>>> 67 in list1
True
P. Veera Prakash 11 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
>>> 5 in list1
True
>>> 9 in list1
False
>>> 5 not in list1
False
>>> 67 not in list1
False
>>> 9 not in list1
True
>>> IDENTITY OPERATORS
>>> a = 20
>>> b = 20
>>> c = 30
>>> a is b
True
>>> a is c
False
>>> a is not b
False
>>> a is not c
True
>>>

Python Control Flow:

if, if-elif-else, for, while, break, continue, pass

Python if...else Statement:

 Decision making is required when we want to execute a code only if a certain condition is
satisfied.
 The if…elif…else statement is used in Python for decision making.

Python if Statement Syntax:

if test expression:
statement(s)

 Here, the program evaluates the test expression and will execute statement(s) only if the test
expression is True.
 If the test expression is False, the statement(s) is not executed.
 In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.
 Python interprets non-zero values as True. None and 0 are interpreted as False.

P. Veera Prakash 12 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Python if Statement Flowchart:

Example of if:

PyPython if...else Statement:

Syntax of if...else

if test expression:
Body of if
else:
Body of else

 The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
 If the condition is False, body of else is executed. Indentation is used to separate the blocks.

P. Veera Prakash 13 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Python if..else Flowchart:

Example of if..else

Python if...elif...else:

Syntax of if...elif...else

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

 The elif is short for else if. It allows us to check for multiple expressions.
 If the condition for if is False, it checks the condition of the next elif block and so on.
 If all the conditions are False, body of else is executed.
 Only one block among the several if...elif...else blocks is executed according to the condition.

P. Veera Prakash 14 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
 The if block can have only one else block. But it can have multiple elif blocks.

Flowchart of if...elif...else

Example of if...elif...else

Python for Loop

 In this article, you'll learn to iterate over a sequence of elements using the different
variations of for loop.

P. Veera Prakash 15 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
 The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.

Syntax of for Loop


for val in a:
Body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is separated from
the rest of the code using indentation.

Flowchart of for Loop

Example: Python for Loop

P. Veera Prakash 16 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

The range() function

 We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
 We can also define the start, stop and step size as range(start,stop,step size). step size
defaults to 1 if not provided.
 This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
 To force this function to output all the items, we can use the function list().

The following example will clarify this.

We can use the range() function in for loops to iterate through a sequence of numbers. It can be
combined with the len() function to iterate though a sequence using indexing.

Here is an example.

P. Veera Prakash 17 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

for loop with else:

 A for loop can have an optional else block as well. The else part is executed if the items in
the sequence used in for loop exhausts.
 break statement can be used to stop a for loop. In such case, the else part is ignored.
 Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.

Here, for loop prints items of the list until the loop exhausts. When the for loop exhausts, it
executes the block of code in the else and prints.

Python while Loop

 Loops are used in programming to repeat a specific block of code. In this article, you will
learn to create a while loop in Python.
 The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
 We generally use this loop when we don't know beforehand, the number of times to iterate.

Syntax of while Loop in Python:

while test_expression:
Body of while

 In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression evaluates to True. After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates to False.
 In Python, the body of the while loop is determined through indentation.
 Body starts with indentation and the first unindented line marks the end.
 Python interprets any non-zero value as True. None and 0 are interpreted as False.

P. Veera Prakash 18 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Flowchart of while Loop:

P. Veera Prakash 19 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Example: Python while Loop

while loop with else:

 Same as that of for loop, we can have an optional else block with while loop as well.
 The else part is executed if the condition in the while loop evaluates to False.
 The while loop can be terminated with a break statement.
 In such case, the else part is ignored. Hence, a while loop's else part runs if no break occurs
and the condition is false.

Here is an example to illustrate this.

Here, we use a counter variable to print the string inside loop three times.
 On the forth iteration, the condition in while becomes False. Hence, the else part is executed.

Python break and continue

 In this article, you will learn to use break and continue statements to alter the flow of a
loop.
 In Python, break and continue statements can alter the flow of a normal loop.
 Loops iterate over a block of code until test expression is false, but sometimes we wish to
terminate the current iteration or even the whole loop without cheking test expression.

P. Veera Prakash 20 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

The break and continue statements are used in these cases.

Python break statement:

 The break statement terminates the loop containing it.


 Control of the program flows to the statement immediately after the body of the loop.
 If break statement is inside a nested loop (loop inside another loop), break will terminate
the innermost loop.

Syntax of break

break

Flowchart of break:

The working of break statement in for loop and while loop is shown below.

P. Veera Prakash 21 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Example: Python break

In this program, we iterate through the "string" sequence. We check if the letter is "i", upon which
we break from the loop. Hence, we see in our output that all the letters up till "i" gets printed. After
that, the loop terminates.

Python continue statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.

Syntax of Continue

continue

Flowchart of continue -

P. Veera Prakash 22 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

The working of continue statement in for and while loop is shown below.

P. Veera Prakash 23 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA

Example: Python continue

 This program is same as the above example except the break statement has been replaced
with continue.
 We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we
see in our output that all the letters except "i" gets printed.

Python pass statement

 It is used as a placeholder for future implementation of functions, loops, etc.


 In Python programming, pass is a null statement. The difference between a comment and
pass statement in Python is that, while the interpreter ignores a comment entirely, pass is not
ignored.
 However, nothing happens when pass is executed. It results into no operation (NOP).

Syntax of pass

pass

We generally use it as a placeholder.

P. Veera Prakash 24 | P a g e
B.TECH-CSE-IV YEAR II SEM-R13 REGULATION-JNTUA
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
the future. They cannot have an empty body. The interpreter would complain. So, we use the pass
statement to construct a body that does nothing.

Example: pass Statement

We can do the same thing in an empty function or class as well.

def function(args):
pass

class example:
pass

P. Veera Prakash 25 | P a g e

You might also like