You are on page 1of 28

Python Basics

Section A

Dr. Emmanuel S. Pilli


Associate Professor, CSE
Python Keywords

None await except in pass

False break else import raise

True continue for is return

and class finally lambda try

as def from nonlocal while

async del global not with

assert elif if or yield


Python Keywords
 Import Keywords: import, from, as
 Structure Keywords: def, class, with, pass, lambda
 Value Keywords: True, False, None
 Operator Keywords: and, or, not, in, is
 Control Flow Keywords: if, elif, else
 Iteration Keywords: for, while, break, continue
 Returning Keywords: return, yield
 Exception-Handling Keywords: try,except,raise,finally,assert
 Asynchronous Programming Keywords: async, await
 Variable Handling Keywords: del, global, nonlocal
Python Identifiers
 Identifier is a name used to identify a variable, function,
class, module or other object
 Rules for Identifiers
 Starts with alphabet or an underscore (_)
 Followed by zero or more letters, _ , and digits
 Keywords cannot be used as Identifiers
 All keywords are lowercase except 3 of them
 Python has 35 Keywords
Data Types
 Three Categories of Data Types
 Basic types: int, float, complex, bool,
string, bytes
 Container types: list, tuple, set, dict
 User- defined types: class
Basic Types
 int binary, decimal, octal and hexadecimal
 float fractional or exponential
 complex real and imaginary part
 bool Boolean values True or False
 string immutable collection of Unicode Characters
enclosed within ‘ ‘, “ “, “”” “””
 bytes binary data
Basic Types

 int binary, decimal, octal and hexadecimal


 binary starts with 0b / 0B 0b10111
 octal starts with 0o / 0O 0o432
 hex starts with 0x / 0X 0x4A3
 float fractional or exponential
 fractional -314.1528
 exponential 3.141528E2, 3.141528e2
 complex 3 + 2j, 1 + 4j
Basic Types
 string immutable collection of Unicode Characters
enclosed within ‘ ‘, “ “, “”” “””
 ‘MNIT’, “MNIT”, “””MNIT”””

 bytes binary data


 b'Bytes objects are immutable sequences of single bytes'
Integer and Float
 int can be of any value
 Python has arbitrary precision integers
 Integers can be created as big as needed
 Arithmetic operation can be performed without worrying
about overflow / underflow

 float is represented internally in binary as 64-bit double


precision values as per IEEE 754 standard
 The maximum value a float can have is approximately
1.8 x 10308
Variable Assignment
 Type of a variable need not be defined
 The type of variable is inferred from the context in which
it is used. Hence Python is called dynamically typed.
 Type of a data type or a variable can be checked by using
type( )
 Single and Multiple Assignments separated by , or ;
 Floor division a//b
Arithmetic Operators
 +
 -
 *
 /
 %
 //
 **
 Shorthand += -= *= /= %= //= **=
Precedence and Associativity
 When multiple operators are used in an arithmetic
expression, it is evaluated on the basis of
precedence (priority) of the operators
 Operators in decreasing order of their priority
PEMDAS
 ()
 **
 *, /, //, %
 +, -
Precedence and Associativity
 If there is a tie between operators of same precedence, it
is settled using associativity of operators
 Each operator has left to right associativity or right to
left associativity

 Most of the operators are evaluated left to right except


exponentiation (**), bitwise NOT (~) and
assignment or short hand
= += -= *= /= %= //= **=
Precedence and Associativity
Precedence and Associativity
Precedence and Associativity
Precedence and Associativity

( ) Parentheses left-to-right
** Exponent right-to-left
* / % Multiplication / Division / Modulus left-to-right
+ – Addition / Subtraction left-to-right
= += -= *=
Assignment and Shorthand right-to-left
/= %= //= **=
Mixed Operations and Type Conversions
 Mixed mode operations
 Operation between int and float will yield float
 Operation between int and complex will yield complex
 Operation between float & complex will yield complex
 One numeric type can be converted another using built-
in functions int( ), float( ), complex( ), and
bool( )
 int( )removes the decimal portion from the quotient
Type Conversions
 int (float, numeric string)
 int (numeric string, base)
 float (int, numeric string)
 float (int)
 complex (int, float).
 complex (int/float, int/float)
 bool (int / float)
 str (int / float)
 chr (int)
Built-in Functions
 abs (x)
 pow (x, y)
 min (x1, x2, x3, ….)
 max (x1, x2, x3, ….)
 divmod (x, y) returns a pair (x // y, x % y)
 round (x, [,n])
 bin (x), oct (x), hex (x)
Built-in Modules
 Python has many Built-in Modules. Each module
contains many functions
 For sophisticated mathematical operations, modules
like math, cmath, random, and decimal can be used
 math – many useful mathematical functions
 cmath – functions for operations on complex numbers
 random – functions for random number generation
 decimal – functions for precise arithmetic operations
Mathematical Functions
 sqrt (x)
 factorial (x)
 fabs (x)
 log (x)
 log10(x)
 exp (x)
 trunc (x), round (x)
 ceil (x), floor (x), modf (x)
Trigonometric functions
 degrees (x)
 radians (x)
 sin (x), cos (x), tan (x)
 sinh (x), cosh (x), tanh (x)
 asin (x), acos (x), atan (x)
 hypot (x, y)
 random (x), randint (x)
 seed( ), seed (x)
Container Types
 Container typically refer to multiple values stored together
 list is an indexed collection of similar or dissimilar entries
 tuple is an immutable collection
 set is a collection of unique values
 dict is a collection of key value pairs, with unique key
enclosed in ‘ ‘
 Values in a list or tuple can be accessed using their
position
Python Types Jargon
 Collection – a generic term for container types
 Iterable – collection that can be iterated over using a loop
 Ordered collection – elements are stored in the same
order in which they are inserted and can be accessed using
an index; generic term is Sequence
 Unordered collection – elements are not stored in the
same order in which they are inserted and cannot be
accessed using an index
 Immutable – unchangeable collection
 Mutable – changeable collection
Python Types Jargon
 String – ordered collection, immutable, iterable
 List – ordered collection, mutable, iterable
 Tuple - ordered collection, immutable, iterable
 Set – unordered collection, mutable, iterable
 Dictionary – unordered collection, mutable, iterable
Class and Objects
 Every type is a class – int, float, complex, bool,
str, list, tuple, set, dict are all ready-made
classes.
 User defined classes can also be created
 Object is created from a Class, Object is an instance of a Class
 A Class describes two things –
 the form an object created from it will take
 methods (functions) that can be used to access and manipulate
the object
 Multiple objects can be created form one class
Comments and Indentation
 Comments begin with #
 Multi line comments must be enclosed between a pair of
‘’’ or ‘’’’’’
 Indentation matters and should not be used casually.
Unexpected indent error will be reported.
 If statements are long, they can be written in multi-lines
with each line except the last ending with /
 Multi-line statements within [ ], { }, or ( ) don’t need /

You might also like