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

Python 2

Uploaded by

godochetimothy10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python 2

Uploaded by

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

Python 1

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Numeric Data Type

Python numeric data types store numeric values


Number objects are created when you assign a value to them.
 var1 = 1

 var2 = 10

 var3 = 10.023

Python supports four different numerical types −


 int (signed integers)

 long (long integers, they can also be represented in octal and hexadecimal)

 float (floating point real values)

 complex (complex numbers)

© ISBAT UNIVERSITY – 2023. 01/06/2024


 Python allows you to use a lowercase l with long, but it is
recommended that you use only an uppercase L to avoid confusion
with the number 1. Python displays long integers with an uppercase
L.
 A complex number consists of an ordered pair of real floating-point
numbers denoted by x + yj, where x and y are the real numbers and j
is the imaginary unit.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python String Data Type

 Python Strings are identified as a contiguous set of characters


represented in the quotation marks.
 Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from
-1 at the end.
 The plus (+) sign is the string concatenation operator and the asterisk
(*) is the repetition operator in

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python List Data Type

 Python Lists are the most versatile compound data types.


 A Python list contains items separated by commas and enclosed
within square brackets ([]).
 To some extent, Python lists are similar to arrays in C.
 One difference between them is that all the items belonging to a
Python list can be of different data type whereas C array can store
elements related to a particular data type.
 The values stored in a Python list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the beginning of the
list and working
© ISBAT UNIVERSITY – 2023. 01/06/2024
 their way to end -1. The plus (+) sign is the list concatenation
operator, and the asterisk (*) is the repetition operator.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Tuple Data Type

 Python tuple is another sequence data type that is similar to a list. A


Python tuple consists of a number of values separated by commas.
Unlike lists, however, tuples are enclosed within parentheses.
 The main differences between lists and tuples are: Lists are enclosed
in brackets ( [ ] ) and their elements and size can be changed, while
tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Ranges

 Python range() is an in-built function in Python which returns a


sequence of numbers starting from 0 and increments to 1 until it
reaches a specified number.
 We use range() function with for and while loop to generate a
sequence of numbers. Following is the syntax of the function:

 range(start, stop, step)

© ISBAT UNIVERSITY – 2023. 01/06/2024


Here is the description of the parameters used:

 start: Integer number to specify starting position, (Its optional,


Default: 0)
 stop: Integer number to specify starting position (It's mandatory)
 step: Integer number to specify increment, (Its optional, Default: 1)

© ISBAT UNIVERSITY – 2023. 01/06/2024


 −
for p in range(5):
print(p)
Now let's modify above program to print the number starting from 1
instead of 0:
for i in range(1, 5):
print(i)

© ISBAT UNIVERSITY – 2023. 01/06/2024


 Again, let's modify the program to print the number starting from 1
but with an increment of 2 instead of 1:
for i in range(1, 5, 2):
print(i)

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Dictionary

 Python dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs. A dictionary key can be almost any Python type, but are usually
numbers or strings.
 Values, on the other hand, can be any arbitrary Python object.
 Dictionaries are enclosed by curly braces ({ }) and values can be
assigned and accessed using square braces ([])

© ISBAT UNIVERSITY – 2023. 01/06/2024


For example −

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values())
© ISBAT UNIVERSITY – 2023. 01/06/2024
 Python dictionaries have no concept of order among elements. It is
incorrect to say that the elements are "out of order"; they are simply
unordered

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Boolean Data Types

 Python boolean type is one of built-in data types which represents


one of the two values either True or False. Python bool() function
allows you to evaluate the value of any expression and returns either
True or False based on the expression.
Examples
Following is a program which prints the value of boolean variables a
and b −
a = True
# display the value of a
print(a)
© ISBAT UNIVERSITY – 2023. 01/06/2024
Python Data Type Conversion

 To convert data between different Python data types, you simply use
the type name as a function.
 Conversion to int

Following is an example to convert number, float and string into integer


data type:
a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3

© ISBAT UNIVERSITY – 2023. 01/06/2024


Data Type Conversion Functions

There are several built-in functions to perform conversion from one


data type to another. These functions return a new object representing
the converted value.
int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
float(x)
Converts x to a floating-point number.
© ISBAT UNIVERSITY – 2023. 01/06/2024
complex(real [,imag])
Creates a complex number
str(x)
Converts object x to a string representation.
repr(x)
Converts object x to an expression string
eval(str)
Evaluates a string and returns an object.
tuple(s)
Converts s to a tuple.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python operators

 Python operators are the constructs which can manipulate the value of
operands. These are symbols used for the purpose of logical,
arithmetic and various other operations.
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are
called operands and + is called operator. In this tutorial, we will
study different types of Python operators.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Types of Python Operators

Python language supports the following types of operators.

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
© ISBAT UNIVERSITY – 2023. 01/06/2024
Python Arithmetic Operators

 Python arithmetic operators are used to perform mathematical


operations on numerical values.
 These operations are Addition, Subtraction, Multiplication, Division,
Modulus, Exponents and Floor Division.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Operator Name Example
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
// Floor Division 9//2 = 4

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Comparison Operators

 Python comparison operators compare the values on


either sides of them and decide the relation among them.
 They are also called relational operators. These

operators are equal, not equal, greater than, less than,


greater than or equal to and less than or equal to.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Operator Name Example
== Equal 4 == 5 is not
true.
!= Not Equal 4 != 5 is true.
> Greater Than 4 > 5 is not
true.
< Less Than 4 < 5 is true.
>= Greater than or Equal to 4 >= 5 is not
true.
<= Less than or Equal to 4 <= 5 is true.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Assignment Operators

 Python assignment operators are used to assign values to


variables. These operators include simple assignment operator,
addition assign, subtraction assign, multiplication assign,
division and assign operators etc.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Operator Name Example

= Assignment Operator a = 10
+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)


© ISBAT UNIVERSITY – 2023. 01/06/2024
**= Exponent a **= 2 (Same as a =
Assignment a ** 2)
//= Floor Division a //= 3 (Same as a =
Assignment a // 3)

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Bitwise Operators

 Bitwise operator works on bits and performs bit by bit


operation. Assume if a = 60; and b = 13; Now in the binary
format their values will be 0011 1100 and 0000 1101
respectively.
 Following table lists out the bitwise operators supported by

Python language with an example each in those, we use the


above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
© ISBAT UNIVERSITY – 2023. 01/06/2024
--------------------------
a&b = 12 (0000 1100)
a|b = 61 (0011 1101)
a^b = 49 (0011 0001)
~a = -61 (1100 0011)
a << 2 = 240 (1111 0000)
a>>2 = 15 (0000 1111)
© ISBAT UNIVERSITY – 2023. 01/06/2024
Operator Name Example

& Binary AND Sets each bit to 1 if both bits are 1


| Binary OR Sets each bit to 1 if one of two bits is 1
^ Binary XOR Sets each bit to 1 if only one of two bits is 1
~ Binary Ones Inverts all the bits
Complement
<< Binary Left Shift left by pushing zeros in from the right
Shift and let the leftmost bits fall off
>> Binary Right Shift right by pushing copies of the leftmost
Shift bit in from the left, and let the rightmost bits
fall off
© ISBAT UNIVERSITY – 2023. 01/06/2024
Python Logical Operators

 There are following logical operators supported by Python language.


Assume variable a holds 10 and variable b holds 20 then

© ISBAT UNIVERSITY – 2023. 01/06/2024


Operator Description Example

and Logical AND If both the operands are true then (a and b) is true.
condition becomes true.

or Logical OR If any of the two operands are (a or b) is true.


non-zero then condition becomes
true.
not Logical NOT Used to reverse the logical state Not(a and b) is false.
of its operand.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Membership Operators

 Python’s membership operators test for membership in a sequence,


such as strings, lists, or tuples. There are two membership operators
as explained below

© ISBAT UNIVERSITY – 2023. 01/06/2024


Operator Description Example
in Evaluates to true if it finds a
x in y, here in results in a 1 if x is
variable in the specified sequence
a member of sequence y.
and false otherwise.
not in Evaluates to true if it does not x not in y, here not in results in a
finds a variable in the specified 1 if x is not a member of
sequence and false otherwise. sequence y.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Identity Operators

 Identity operators compare the memory locations of two objects.


There are two Identity operators explained below −

© ISBAT UNIVERSITY – 2023. 01/06/2024


Operator Description Example

is Evaluates to true if the variables


on either side of the operator x is y, here is results in 1 if id(x)
point to the same object and equals id(y).
false otherwise.

is not Evaluates to false if the


variables on either side of the x is not y, here is not results in 1
operator point to the same if id(x) is not equal to id(y).
object and true otherwise.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python Operators Precedence

 The following table lists all operators from highest precedence to


lowest

© ISBAT UNIVERSITY – 2023. 01/06/2024


Sr.No. Operator & Description
1 ** Exponentiation (raise to the power)

2 ~ + - Complement, unary plus and minus (method names for


the last two are +@ and -@)

3 * / % // Multiply, divide, modulo and floor division

4 +- Addition and subtraction

© ISBAT UNIVERSITY – 2023. 01/06/2024


5 >> << Right and left bitwise shift

6 & Bitwise 'AND'


7 ^ | Bitwise exclusive `OR' and regular `OR'
8 <= < > >= Comparison operators

9 <> == != Equality operators

10 = %= /= //= -= += *= **= Assignment operators

11 is is not Identity operators


© ISBAT UNIVERSITY – 2023. 01/06/2024
12 in not in
Membership operators
13 not or and
Logical operators

© ISBAT UNIVERSITY – 2023. 01/06/2024


Decision making

 Decision making is anticipation of conditions occurring while


execution of the program and specifying actions taken according to
the conditions.
 Decision structures evaluate multiple expressions which produce
TRUE or FALSE as outcome. You need to determine which action to
take and which statements to execute if outcome is TRUE or FALSE
otherwise.
 Following is the general form of a typical decision making structure
found in most of the programming languages −

© ISBAT UNIVERSITY – 2023. 01/06/2024


© ISBAT UNIVERSITY – 2023. 01/06/2024
Sr.No. Statement & Description
1 if statements
An if statement consists of a boolean expression followed by one or
more statements.
2 if...else statements
An if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.

3 nested if statements
You can use one if or else if statement inside another if or else
if statement(s).
© ISBAT UNIVERSITY – 2023. 01/06/2024
Single Statement Suites

 If the suite of an if clause consists only of a single line, it may go on


the same line as the header statement.
 Here is an example of a one-line if clause −

var = 100
if ( var == 100 ) : print ("Value of expression is 100“)
print( "Good bye!“)

© ISBAT UNIVERSITY – 2023. 01/06/2024


 A loop statement allows us to execute a statement or group of
statements multiple times. The following diagram illustrates a loop
statement

© ISBAT UNIVERSITY – 2023. 01/06/2024


© ISBAT UNIVERSITY – 2023. 01/06/2024
Sr.No. Loop Type & Description
1 while loop
Repeats a statement or group of statements while a given condition is
TRUE. It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while
loop.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Loop Control Statements

 Loop control statements change execution from its normal sequence.


When execution leaves a scope, all automatic objects that were
created in that scope are destroyed.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Sr.No. Control Statement & Description
1 break statement
Terminates the loop statement and transfers execution to the
statement immediately following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is
required syntactically but you do not want any command or code to
execute.
© ISBAT UNIVERSITY – 2023. 01/06/2024
 Number data types store numeric values.
 They are immutable data types, means that changing the value of a
number data type results in a newly allocated object.
 Number objects are created when you assign a value to them.

© ISBAT UNIVERSITY – 2023. 01/06/2024


 Number data types store numeric values. They are immutable data
types, means that changing the value of a number data type results in
a newly allocated object.

 Number objects are created when you assign a value to them.


 You can also delete the reference to a number object by using
the del statement.
 The syntax of the del statement is −
 del var1[,var2[,var3[....,varN]]]]

© ISBAT UNIVERSITY – 2023. 01/06/2024


Python supports four different numerical types −

 int (signed integers) − They are often called just integers or ints, are
positive or negative whole numbers with no decimal point.

 long (long integers ) − they are integers of unlimited size, written


like integers and followed by an uppercase or lowercase L.

© ISBAT UNIVERSITY – 2023. 01/06/2024


 float (floating point real values) − they represent real numbers and are
written with a decimal point dividing the integer and fractional parts.
 Floats may also be in scientific notation, with E or e indicating the
power of 10 (2.5e2 = 2.5 x 102 = 250).

 complex (complex numbers) − are of the form a + bJ, where a and b


are floats and J (or j) represents the square root of -1 (which is an
imaginary number).
 The real part of the number is a, and the imaginary part is b. Complex
numbers are not used much in Python programming.
© ISBAT UNIVERSITY – 2023. 01/06/2024
Mathematical Functions

 Python includes following functions that perform mathematical


calculations

© ISBAT UNIVERSITY – 2023. 01/06/2024


Sr.No. Function & Returns ( description )

1 abs(x) The absolute value of x: the (positive) distance


between x and zero.
2 ceil(x) The ceiling of x: the smallest integer not less than x

3 cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y


4 exp(x) The exponential of x: ex
5 fabs(x) The absolute value of x.
6 floor(x) The floor of x: the largest integer not greater than x

© ISBAT UNIVERSITY – 2023. 01/06/2024


7 log(x)
The natural logarithm of x, for x> 0
8 log10(x)
The base-10 logarithm of x for x> 0.
9 max(x1, x2,...)
The largest of its arguments: the value closest to positive
infinity
10 min(x1, x2,...)
The smallest of its arguments: the value closest to negative
infinity

© ISBAT UNIVERSITY – 2023. 01/06/2024


11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts
have the same sign as x. The integer part is returned as a float.

12 pow(x, y) The value of x**y.

13 round(x [,n])
x rounded to n digits from the decimal point. Python rounds away from
zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.

14 sqrt(x) The square root of x for x > 0


© ISBAT UNIVERSITY – 2023. 01/06/2024
Random Number Functions

 Random numbers are used for games, simulations, testing, security,


and privacy applications. Python includes following functions that are
commonly used.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Sr.No Function & Description
.
1 choice(seq) A random item from a list, tuple, or string.

2 randrange ([start,] stop [,step])


A randomly selected element from range(start, stop, step)
3 random() A random float r, such that 0 is less than or equal to r and r is less than 1

4 seed([x])
Sets the integer starting value used in generating random numbers. Call this function
before calling any other random module function. Returns None.

© ISBAT UNIVERSITY – 2023. 01/06/2024


5 shuffle(lst)
Randomizes the items of a list in place. Returns
None.
6 uniform(x, y)
A random float r, such that x is less than or equal to r
and r is less than y

© ISBAT UNIVERSITY – 2023. 01/06/2024


Trigonometric Functions

 Python includes following functions that perform trigonometric


calculations.

© ISBAT UNIVERSITY – 2023. 01/06/2024


Sr.No Function & Description
.
1 acos(x) Return the arc cosine of x, in radians.

2 asin(x) Return the arc sine of x, in radians.


3 atan(x) Return the arc tangent of x, in radians.
4 atan2(y, x) Return atan(y / x), in radians.
5 cos(x) Return the cosine of x radians.

6 hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y).

© ISBAT UNIVERSITY – 2023. 01/06/2024


7 sin(x) Return the sine of x radians.

8 tan(x) Return the tangent of x radians.

9 degrees(x)
Converts angle x from radians to degrees.

10 radians(x)
Converts angle x from degrees to radians.
© ISBAT UNIVERSITY – 2023. 01/06/2024
Mathematical Constants

 The module also defines two mathematical constants −

Sr.N Constants & Description


o.
1 pi
The mathematical constant pi.
2 e
The mathematical constant e.

© ISBAT UNIVERSITY – 2023. 01/06/2024

You might also like