PYTHON
LECTURE-1
WHY PYTHON?
• Easy to read, learn and write than many other programming languages like C, C++, C# and Java,
enabling novices and professional developers to get up to speed quickly
• open source and large active community base which contributes to its development and
provides support
• Supports both object-oriented and functional programming - versatile programming
• Enhances developer productivity with extensive standard libraries and third-party opensource libraries. No need to reinvent the wheel!
• Dynamically typed language – No need to declare data types explicitly like procedural
languages – flexible and reliable
PYTHON: DYNAMICALLY TYPED LANGUAGE
• Python is a dynamically typed language where variable names are bound to different values, possibly of
varying types, during program execution i.e. type of object that a variable refers to is determined at runtime
• The assignment operator simply creates an association between a name and a value.
• Although each value has an associated type such as an integer or string, variable names are untyped and can
be made to refer to any type of data during execution.
APPLICATIONS
• GUI-based desktop applications
• Graphics, games, and scientific computing
• Web frameworks and applications
• Operating systems
• Data science and machine learning
• Scripting to automate tasks and processes
PYTHON STANDARD LIBRARY MODULES EXAMPLES
• collections—Additional data structures beyond
lists, tuples, dictionaries and sets.
• csv—Processing comma-separated value files.
• datetime, time—Date and time manipulations.
• decimal—Fixed-point and floating-point
arithmetic, including monetary calculations.
• doctest—Simple unit testing via validation tests
and expected results embedded in docstrings.
• json—JavaScript Object Notation (JSON)
processing for use with web services and No
SQL Databases
• os—Interacting with the operating system.
• queue—First-in, first-out data structure.
• random—Pseudorandom numbers.
• re—Regular expressions for pattern matching.
• string—String processing.
• sys—Command-line argument processing;
standard input, standard output and standard
error streams.
• timeit—Performance analysis.
• math—Common math constants and
operations.
DEFINITIONS
• Identifier: an identifier is a name used to identify variables, functions, classes, or other
objects. However, not all names are valid identifiers. Python enforces specific rules for
naming identifiers, and violating these rules results in invalid identifiers. Identifiers can
only contain letters, digits, and underscores and not starts with digits.
• Keywords: Predefined keywords in Python are reserved words that have specific
meanings and purposes in the language. They form the foundation of Python's syntax and
structure, enabling developers to write clear and functional code. These keywords cannot
be used as identifiers (e.g., variable names, function names) and are case-sensitive.
KEYWORDS
Keywords
• Identifier: Category
an identifier is a name used to identify variables,
functions, classes, or other
True,enforces
False, None specific rules for
objects.Value
However,
not all names are valid identifiers. Python
Keywords
naming
identifiers,
and violating these rules results in invalid
identifiers.
Identifiers can
and, or,
not, is, in
Operator
Keywords
only
contain
letters,
digits, and underscores
and
not
startspass,
with
digits.finally, raise, assert
if, else, elif, for, while,
break,
continue,
try, except,
Control
Flow
Keywords
def, return,
lambda,
yield,have
class specific
Function
and Class
• Keywords:
Predefined
keywords in Python are reserved
words
that
with, as of Python's syntax and
Context
meanings
andManagement
purposes in the language. They form the foundation
from
structure,
enabling
developers to write clear and functionalimport,
code.
These keywords cannot
Import
and Module
be used
as and
identifiers
(e.g., variable names, function names)
andnonlocal
are case-sensitive.
global,
Scope
Namespace
Async Programming
async, await
DIFFERENCE BETWEEN KEYWORDS AND
IDENTIFIERS
Keywords
Identifiers
Reserved words in Python that
have a specific meaning.
Names given to variables, functions, classes, etc.
Cannot be used as variable names.
Can be used as variable names (if not a keyword).
Examples: if, else, for, while
Examples: x, number, sum, result
Part of the Python syntax.
User-defined, meaningful names in the code.
They cannot be redefined or
changed.
Can be defined and redefined by the programmer.
STATEMENTS
• An statement is an instruction that the Python interpreter can execute. Eg. The different types of Python statements
are listed below:
• Simple Statement eg- print("Hello, Python!")
• Multi-Line Statements
• Python Conditional and Loop Statements
•
If-else
•
for loop
• while loop
• Python try-except
• Python with statement
• Python Expression statements
• pass statement
• del statement
•
return statement
• import statement
• continue and
• break statement
EXPRESSIONS
• An expression in Python is a combination of values, variables, and operators that Python
evaluates to produce a result or value. Eg.
1. # Constant Expressions
x = 15 + 1.3
print(x)
2. # Combining strings
greeting = "Hello" + " " + "World!"
print(greeting) # Output: Hello World!
INDENTATION
• Whitespace is used for indentation in Python. Unlike many other programming languages
which only serve to make the code easier to read, Python indentation is mandatory.
• One of the distinctive roles of Python is its use of indentation to highlight the blocks of code. All
statements with the same distance to the right belong to the same block of code. If a block has
to be more deeply nested, it is simply indented further to the right.
EXAMPLE
# Python indentation
site = ‘google'
if site == 'google':
print('Logging on to web..')
else:
print(‘check the URL.')
print(' Ready to use !')
Output: 'Logging on to web..
Ready to use
VARIABLES AND ASSIGNMENT STATEMENTS
Variable : Variable in Programming is a named storage location that holds a value or data. These
values can change during the execution of a program, hence the term "variable."
Variable Names
A variable name, such as x, may consist of letters, digits and underscores (_) but must not begin with
a digit. Python is case sensitive, so number and Number are different identifiers because one begins
with a lowercase letter and the other begins with an uppercase letter.
TYPES
Each value in Python has a type that indicates the kind of data the value represents. You can view a
value’s type with Python’s built-in type function,
OPERATORS
Operators are used to perform operations on variables and values. The types are as listed below
1.
Arithmetic operators
2.
Assignment operators
3.
Comparison operators
4.
Logical operators
5.
Identity operators
6.
Membership operators
7.
Bitwise operators
ARITHMETIC OPERATORS
• Addition
+
f+7
f+7
• Subtraction
–
p–c
p-c
• Multiplication
*
b·m
b*m
• Exponentiation **
xy
x ** y
• True division
/
x/y
x/y
• Floor division
//
x/y
x // y
r mod s
r%s
• Remainder (modulo) %
To calculate the square root, you can use the exponent 1/2
TRUE DIVISION (/) VS. FLOOR DIVISION (//)
True division (/) divides a numerator by a denominator and yields a floating-point
number with a decimal point, as in:
Floor division (//) divides a numerator by a denominator, yielding the closest integer
that’s not greater than than the result.
ASSIGNMENT OPERATORS & COMPARISON OPERATORS
Assignment Operator
Example
Same As
=
x=5
x=5
+=
x += 3
x=x+3
-=
x -= 3
x=x-3
*=
x *= 3
x=x*3
/=
x /= 3
x=x/3
%=
x %= 3
x=x%3
//=
x //= 3
x = x // 3
**=
x **= 3
x = x ** 3
&=
x &= 3
x=x&3
|=
x |= 3
x=x|3
^=
x ^= 3
x=x^3
>>=
x >>= 3
x = x >> 3
<<=
x <<= 3
x = x << 3
:=
print(x := 3)
x=3
print(x)
Comparison Name
Operator
Example
==
Equal
x == y
!=
Not equal
x != y
>
Greater than
x>y
<
Less than
x<y
>=
Greater than or
equal to
x >= y
<=
Less than or equal
to
x <= y
LOGICAL OPERATORS & IDENTITY OPERATORS
Logical
Operator
Description
Example
and
Returns True if
both statements
are true
x < 5 and x <
10
or
Returns True if
one of the
statements is
true
x < 5 or x < 4
not
Reverse the
not(x < 5 and
result, returns
x < 10)
False if the result
is true
Identity
Operator
Description
Example
is
Returns True if
x is y
both variables are
the same object
is not
Returns True if
x is not y
both variables are
not the same
object
MEMBERSHIP OPERATORS
Membership
Operator
Description
Example
in
Returns True if x in y
a sequence
with the
specified value
is present in
the object
not in
Returns True if x not in y
a sequence
with the
specified value
is not present
in the object
BITWISE OPERATORS
.
Bitwise Operator
Name
Description
Example
&
AND
Sets each bit to 1 if both bits are 1
x&y
|
OR
Sets each bit to 1 if one of two bits is 1
x|y
^
XOR
Sets each bit to 1 if only one of two bits is 1
x^y
~
NOT
Inverts all the bits
~x
<<
Zero fill left shift
Shift left by pushing zeros in from the right and let x << 2
the leftmost bits fall off
>>
Signed right shift
Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off
x >> 2
FUNCTION ‘PRINT’
Printing a Comma-Separated List of Items
Printing Many Lines of Text with One Statement
Ignoring a Line Break in long String
Printing the value of an expression
ESCAPE SEQUENCES
\n
Insert a newline character in a string. When the string is displayed, for each newline,
move the screen cursor to the beginning of the next line.
\t
Insert a horizontal tab. When the string is displayed, for each tab, move the screen
cursor to the next tab stop.
\\
Insert a backslash character in a string.
\"
Insert a double quote character in a string.
\'
Insert a single quote character in a string.
TRIPLE QUOTED STRINGS
• Denoted by three double quotes(""") or three single quotes('‘’)
• Used for multiline strings, docstrings to describe a script's purpose and strings that
contain single or double quotes
GETTING INPUT FROM USER
• Use input function
• Function input always returns a string
TAKING INTEGER AS INPUT