Python Programming
Fundamentals
Module 2
Need of programming Languages
• Computers can execute tasks very rapidly. They
can handle a greater amount of input data than
you can. But they can not design a strategy to
solve problems for you.
• Need one programming language to
communicate with computer to solve the
problem.
What is Python?
• Python is a programming language, which is
object-oriented, high level, interpreted,
multipurpose and extremely user friendly
History in Brief
• Invented in the Netherlands by Guido Van Rossum
• Python was coined and conceived in the late 1980s
• Implementation was started in December 1989
• Named after Monty Python
• Guido Rossum (the founder) was a fan of Monty
Python’s
‘Flying Circus’ – a famous TV show in the Netherlands.
• It is easy to learn.
• Many of the programs written in python require comparatively
less number of lines of code to perform the same task compared
to other languages like C.
• Less programming errors and less development time.
• Python 3.11.4, documentation released on 6 June 2023
• Version details are known in detail by referring the below link
https://www.python.org/doc/versions/
Need for Python – in founder words
Applications
• Web and internet development
• Scientific and numeric computing
• Education
• Desktop GUIs
• Software and Game development, robot etc
• Network programming
• Business applications
Who is using Python
Python….
• Python is a high-level language; other high-level languages
you might have heard of are C, C++, Perl, and Java.
• There are also low-level languages, sometimes referred to
as “machine languages” or “assembly languages.”
• Computers can only run programs written in low-level
languages. So programs written in a high-level language have
to be processed before they can run.
• This extra processing takes some time, which is a small
disadvantage of high-level languages.
Python….
• Two kinds of program translator to convert from high-
level languages into low-level languages: interpreters
and compilers.
• An interpreter processes the program a little at a time,
alternately reading lines and performing computations.
Python….
• A compiler reads the program and translates it completely before
the program starts running. In this context, the high-level program is
called the source code, and the translated program is called the
object code or the executable. Once a program is compiled, you
can execute it repeatedly without further translation.
Compiler and Interpreter
Interactive and Script Mode
Python….
• Python is considered an interpreted language because
Python programs are executed by an interpreter. There
are two ways to use the interpreter:
• Interactive mode and script mode.
Python….Interactive mode
In interactive mode, you type Python
programs and the interpreter displays
the result:
>>> 1 + 1
2
The shell prompt, >>>, is the prompt
the interpreter uses to indicate that it is
ready. If you type 1 + 1, the interpreter
replies 2.
• When you start Python in interactive
mode, you will see a prompt
• Indicates the interpreter is
waiting for a Python statement
to be typed
• Prompt reappears after
previous statement is executed
• Error message displayed If you
incorrectly type a statement
• Good way to learn new parts of
Python
Python …. Shell
Python…. Script Mode
• Alternatively, you can store code in a file and use the
interpreter to execute the contents of the file, which is called a
script.
• By convention, Python scripts have names that end with .py.
• Working in interactive mode is convenient for testing small
pieces of code because you can type and execute them
immediately.
• But for anything more than a few lines, you should save your
code as a script so you can modify and execute it in the
future.
Python….Script Mode …
File name : first.py
print(4+3)
print(4-3)
print(4>3)
print("hello World")
Indentation
Indentation
• Indentation is a very important concept of Python
because without properly indenting the Python code,
you will end up seeing Indentation Error and the
code will not get compiled.
• Python indentation refers to adding white space
before a statement to a particular block of code.
Example
Example
Example
Example
Correct code with proper indentations
Benefits of Indentation in Python
• Indentation is important to increase the readability of the code by clearly
indicating the hierarchy (i.e. if statements belong to the same block or not).
• This avoids the need to use delimiters such as braces or brackets, which is
mandatory in most programming languages like C, C++, Java, etc.
• Python indentation is consistent throughout the program, making it easier to
debug.
• In most programming languages, indentation makes the structure of the code
proper. Python uses it for grouping, making the code automatically beautiful.
• Python indentation rules are very simple. Most of the Python IDEs automatically
indent the code for you, so it’s very easy to write the properly indented code.
Comments
https://
www.google.com/url?sa=i&url=https%3A%2F%2Fipcisco.com%2Flesson%2Fpython-comment-
Python Comments
• Comments in Python are the lines in the code
that are ignored by the interpreter during the
execution of the program.
• Comments enhance the readability of the code
and help the programmers to understand the
code very carefully.
Python Comments - Types
• Three types of comments in Python:
– Single line Comments
– Multiline Comments
– Docstring Comments
• Python Comments are ignored by the interpreter during the
execution of the program.
Example
# sample comment
name = “Welcome to VIT Chennai"
print(name)
Output: Welcome to VIT Chennai
Single-Line Comment
• Single-line comment starts with the hashtag symbol (#)
with no white spaces and lasts till the end of the line.
• If the comment exceeds one line then put a hashtag on
the next line and continue the Python Comments.
• Python’s single-line comments are proved useful for
supplying short explanations for variables, function
declarations, and expressions.
Example
Multi-Line Comments
• Python does not provide the option for multiline
comments.
• However, there are different ways through which
we can write multiline comments.
• Multiline comments using multiple hashtags (#)
• Multiline comments using string literals (‘’’)
Multi-Line Comments (#)
• We use multiple hashtags (#) to write
multiline comments in Python.
• Each and every line will be considered as a
single-line comment.
Multi-Line Comments (‘’’)
• Python ignores the string literals that are not
assigned to a variable so we can use these string
literals as Python Comments.
• On executing the below code we can see that
there will not be any output so we use triple
quotes(‘’’) as multiline comments.
Docstring Comments
• Python docstring is the string literals with triple
quotes that are appeared right after the function.
• Python docstrings provide a convenient way to
provide a help documentation with Python
modules, functions, classes, and methods.
• The docstring is then made available via the
__doc__ attribute.
Example
Use of Python Comments
• Make Code Easier to Understand
– If we write comments in our code, it will be easier for future
reference. Also, it will be easier for other developers to understand
the code.
• Using Comments for Debugging
• If we get an error while running the program, we can comment the
line of code that causes the error instead of removing it.
For example,
print(‘Welcome to VIT')
# print(‘First Year)
print(‘Students')
Here, print(‘First Year) was causing an error so we have changed it to a
comment. Now, the program runs without any errors.
This is how comments can be a valuable debugging tool.
Variables
https://realpython.com/python-variables/
Python variables
• Variable is a name that is used to refer to memory location.
Python variable is also known as an identifier and used to hold
value.
• In Python, we don't need to specify the type of variable because
Python is a infer language and smart enough to get variable type.
• Variable names can be a group of both the letters and digits, but
they have to begin with a letter or an underscore.
• It is recommended to use lowercase letters for the variable name.
Rules- Naming variable
The rules to name variable
• The first character of the variable must be an alphabet or
underscore ( _ ).
• All the characters except the first character may be an alphabet of
lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9).
• Identifier name must not contain any white-space, or special
character (!, @, #, %, ^, &, *).
• Identifier name must not be similar to any keyword defined in the
language.
• Identifier names are case sensitive; for example, my name, and
MyName is not the same.
• Examples of valid identifiers: a123, _n, n_3, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.
Invalid Identifier
Declaring Variable and Assigning Values
• Python does not bind us to declare a variable
before using it in the application. It allows us
to create a variable at the required time.
• We don't need to declare explicitly variable in
Python. When we assign any value to the
variable, that variable is declared
automatically.
• The equal (=) operator is used to assign value
to a variable.
Object references
• It is necessary to understand how the Python interpreter
works when we declare a variable.
• The process of treating variables is somewhat different from
many other programming languages.
• Python is the highly object-oriented programming language;
that's why every data item belongs to a specific type of class.
• Let's check the type of it by using the Python built-in type()
function.
Example
Multiple Assignment
1. Assigning single value to multiple variables
Multiple Assignment
2. Assigning multiple values to multiple variables
Python Variable Types
• Two types of variables in
Python
– Local variable and
– Global variable
Local Variable
Local Variable :
Local variables are the
variables that
declared inside the
function and have
scope within the
function.
Global variable
• Global variables can be
used throughout the
program, and its scope is in
the entire program.
• We can use global
variables inside or outside
the function.
Delete Variable
• We can delete the variable using the del
keyword.
• Syntax del <variable_name>
Reserved Keywords
https://beginnersbook.com/2019/03/python-keywords-and-identifiers/
Keywords
• Keywords in Python are predefined words that
have a special meaning to the interpreter.
• They are reserved words that are used to perform
a specific task in Python programming.
• There are 35 keywords in Python 3.11.
Rules for Keywords in Python
• Keywords are used to define the syntax of the
coding.
1. The keyword cannot be used as an identifier,
function, or variable name.
2. All the keywords in python should be in
lowercase except True and False.
Example – True, False, and, or not
Example of for, if, in, break, continue keywords
Example of def, if, and else keywords
Example of a lambda keyword
Data Types
https://www.google.com/url?sa=i&url=https%3A%2F%2Fmycstutorial.in%2Fpython-data-types/
Data Types
Data types
• Python Data Types are used to define the type of a
variable.
• It defines what type of data we are going to store in a
variable.
• The data stored in memory can be of many types.
• For example, a person's age is stored as a numeric value
and his or her address is stored as alphanumeric
characters.
Types
Python has various built-in data types
• Numeric - int, float, complex
• String - str
• Sequence - list, tuple, range
• Binary - bytes, bytearray, memoryview
• Mapping - dict
• Boolean - bool
• Set – set
• None - NoneType
Python Numeric Data Type
• Python numeric data types store numeric values. Number
objects are created when you assign a value to them.
• 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)
Examples
•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.
Example
String Data Type
• Python Strings are identified as a contiguous set of
characters represented in the quotation marks.
• 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
String Data Type
three
Sequence - List Data Type
• A Python list contains items separated by commas and
enclosed within square brackets ([])
• 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
where as C array can store elements related to a particular
data type.
List Data Type - Example
Sequence - Tuple Data Type
• A Python tuple consists of a number of values
separated by commas.
• Unlike lists, however, tuples are enclosed
within parentheses.
Tuple -Example
Tuple and List Difference
• List has mutable nature i.e., list can be changed or
modified after its creation according to needs.
• whereas tuple has immutable nature i.e., tuple can’t
be changed or modified after its creation.
list = [1,2,3]
tuple = (1,2,3)
print(list)
print(tuple)
Mutable vs Immutable
Sequence - range
• 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.
Range()
• syntax of the function:
range(start, stop, step)
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)
Example
Dictionary
• A dictionary is a key-value pair set arranged in any order.
• It stores a specific value for each key, like an associative array or
a hash table.
• Value is any Python object, while the key can hold any primitive
data type.
• Dictionaries are enclosed by curly braces ({ }) and values can be
assigned and accessed using square braces ([]).
Dictionary Example
• 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.
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.
Boolean Example
Boolean Values
Set
• The data type's unordered collection is Python Set.
• It is iterable, mutable(can change after creation), and has
remarkable components.
• The elements of a set have no set order; It might return the
element's altered sequence.
• Either a sequence of elements is passed through the curly
braces and separated by a comma to create the set or the
built-in function set() is used to create the set. It can contain
different kinds of values.
Set- Example
Operators and Precedence
https://realpython.com/python-operators/
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.
Types of Python Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Identity Operators
Arithmetic Operators
Arithmentic - Example
Comparison Operators
Example
Assignment Operators
Example
Bitwise Operator
Operat
or
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
Complement
Inverts all the bits
<< Binary Left Shift Shift left by pushing zeros in from the
right and let the leftmost bits fall off
>> Binary Right Shift Shift right by pushing copies of the
leftmost bit in from the left, and let the
rightmost bits fall off
Example
Identity Operators - Example
Pre ce den ce of Op era tors
• An expression in python consists
of variables, operators, values, etc.
• When the Python interpreter encounters any
expression containing several operations, all
operators get evaluated according to an ordered
hierarchy, called operator precedence.
Operators Precedence Table
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is
not, in, not in
Comparisons, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR
Operator precedence and associativity
Operator precedence and associativity
Expressions
Expressions in Python
• An expression is a combination of operators and
operands that is interpreted to produce some
other value.
• In any programming language, an expression is
evaluated as per the precedence of its operators.
• So that if there is more than one operator in an
expression, their precedence decides which
operation will be performed first.
Types of Expressions
1. Constant Expressions
2. Arithmetic Expressions
3. Integral Expressions
4. Floating Expressions
5. Relational Expressions
6. Logical Expressions
7. Bitwise Expressions
8. Combinational Expressions
Constant Expression
• The expressions have constant values only
Example
Answer : 15.5
Arithmetic Expressions
• An arithmetic expression is a combination of
numeric values, operators, and sometimes
parenthesis. The result of this type of expression is
also a numeric value.
• The operators used in these expressions are
arithmetic operators like addition, subtraction, etc.
Example
Output:
52
28
480
3.33333
Integral Expressions
• This expression produces only integer results
after all computations and type conversions.
Output:
12
Floating Expressions
• The expressions produce floating point numbers as
result after all computations and type conversions.
Output:
5.0
Relational Expressions
• In these types of expressions, arithmetic expressions
are written on both sides of relational operator (> , < ,
>= , <=). Those arithmetic expressions are evaluated
first, and then compared as per relational operator
and produce a boolean output in the end. These
expressions are also called Boolean expressions.
Example
Output:
True
Output:
False
Logical Expressions
• The expressions that result in either True or False. It
basically specifies one or more conditions.
• For example, (10 == 9) is a condition if 10 is equal to
9. As we know it is not correct, so it will return False.
• Logical operations are and, or, not
Example
Output:
False
True
False
Bitwise Expressions
• Computations are performed at bit level.
• Example
Output:
1
12
Combinational Expressions
• We can use different types of expressions in a single
expression - combinational expressions
• when we combine different types of expressions or use
multiple operators in a single expression, operator
precedence comes into play.
Output:
10
Built in Functions
https://realpython.com/python-build-in-functions/
Python Functions
A function is a collection of related statements that performs
a specific task.
• Built-in functions – 68 built-in functions
• User-defined functions -To define a user-defined
function, the def keyword is used
• Anonymous functions- these are also known as lambda
functions.
Build-in Functions
• The built-in Python functions are pre-defined by the
python interpreter. There are 68 built-in python
functions.
• These functions perform a specific task and can be
used in any program, depending on the requirement
of the user.
Example
Absolute value: 20
Example
Importing from packages
Import Packages
• Import in python is similar to #include header_file in
C/C++.
• Python modules can get access to code from another
module by importing the file/function using import.
• The import statement is the most common way of
invoking the import machinery, but it is not the only way.
Import ()
• import module_name
• import module_name.member_name
• from module_name import *
import module_name
When the import is used, it searches for the module
initially in the local scope by calling __import__() function.
The value returned by the function is then reflected in the
output of the initial code.
import module_name.member_name
• In the above code module, math is imported, and its
variables can be accessed by considering it to be a
class and pi as its object.
The value of pi is returned by __import__().
• pi as a whole can be imported into our initial code,
rather than importing the whole module.
from module_name import *
• All the functions and constants can be imported
using *.

Python programming fundamentals for class 12

  • 1.
  • 2.
    Need of programmingLanguages • Computers can execute tasks very rapidly. They can handle a greater amount of input data than you can. But they can not design a strategy to solve problems for you. • Need one programming language to communicate with computer to solve the problem.
  • 3.
    What is Python? •Python is a programming language, which is object-oriented, high level, interpreted, multipurpose and extremely user friendly
  • 4.
    History in Brief •Invented in the Netherlands by Guido Van Rossum • Python was coined and conceived in the late 1980s • Implementation was started in December 1989 • Named after Monty Python • Guido Rossum (the founder) was a fan of Monty Python’s ‘Flying Circus’ – a famous TV show in the Netherlands.
  • 5.
    • It iseasy to learn. • Many of the programs written in python require comparatively less number of lines of code to perform the same task compared to other languages like C. • Less programming errors and less development time. • Python 3.11.4, documentation released on 6 June 2023 • Version details are known in detail by referring the below link https://www.python.org/doc/versions/
  • 6.
    Need for Python– in founder words
  • 7.
    Applications • Web andinternet development • Scientific and numeric computing • Education • Desktop GUIs • Software and Game development, robot etc • Network programming • Business applications
  • 8.
  • 9.
    Python…. • Python isa high-level language; other high-level languages you might have heard of are C, C++, Perl, and Java. • There are also low-level languages, sometimes referred to as “machine languages” or “assembly languages.” • Computers can only run programs written in low-level languages. So programs written in a high-level language have to be processed before they can run. • This extra processing takes some time, which is a small disadvantage of high-level languages.
  • 10.
    Python…. • Two kindsof program translator to convert from high- level languages into low-level languages: interpreters and compilers. • An interpreter processes the program a little at a time, alternately reading lines and performing computations.
  • 11.
    Python…. • A compilerreads the program and translates it completely before the program starts running. In this context, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation.
  • 12.
  • 13.
  • 14.
    Python…. • Python isconsidered an interpreted language because Python programs are executed by an interpreter. There are two ways to use the interpreter: • Interactive mode and script mode.
  • 15.
    Python….Interactive mode In interactivemode, you type Python programs and the interpreter displays the result: >>> 1 + 1 2 The shell prompt, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type 1 + 1, the interpreter replies 2. • When you start Python in interactive mode, you will see a prompt • Indicates the interpreter is waiting for a Python statement to be typed • Prompt reappears after previous statement is executed • Error message displayed If you incorrectly type a statement • Good way to learn new parts of Python
  • 16.
  • 17.
    Python…. Script Mode •Alternatively, you can store code in a file and use the interpreter to execute the contents of the file, which is called a script. • By convention, Python scripts have names that end with .py. • Working in interactive mode is convenient for testing small pieces of code because you can type and execute them immediately. • But for anything more than a few lines, you should save your code as a script so you can modify and execute it in the future.
  • 18.
    Python….Script Mode … Filename : first.py print(4+3) print(4-3) print(4>3) print("hello World")
  • 19.
  • 20.
    Indentation • Indentation isa very important concept of Python because without properly indenting the Python code, you will end up seeing Indentation Error and the code will not get compiled. • Python indentation refers to adding white space before a statement to a particular block of code.
  • 21.
  • 22.
  • 23.
  • 24.
    Example Correct code withproper indentations
  • 25.
    Benefits of Indentationin Python • Indentation is important to increase the readability of the code by clearly indicating the hierarchy (i.e. if statements belong to the same block or not). • This avoids the need to use delimiters such as braces or brackets, which is mandatory in most programming languages like C, C++, Java, etc. • Python indentation is consistent throughout the program, making it easier to debug. • In most programming languages, indentation makes the structure of the code proper. Python uses it for grouping, making the code automatically beautiful. • Python indentation rules are very simple. Most of the Python IDEs automatically indent the code for you, so it’s very easy to write the properly indented code.
  • 26.
  • 27.
    Python Comments • Commentsin Python are the lines in the code that are ignored by the interpreter during the execution of the program. • Comments enhance the readability of the code and help the programmers to understand the code very carefully.
  • 28.
    Python Comments -Types • Three types of comments in Python: – Single line Comments – Multiline Comments – Docstring Comments • Python Comments are ignored by the interpreter during the execution of the program. Example # sample comment name = “Welcome to VIT Chennai" print(name) Output: Welcome to VIT Chennai
  • 29.
    Single-Line Comment • Single-linecomment starts with the hashtag symbol (#) with no white spaces and lasts till the end of the line. • If the comment exceeds one line then put a hashtag on the next line and continue the Python Comments. • Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions.
  • 30.
  • 31.
    Multi-Line Comments • Pythondoes not provide the option for multiline comments. • However, there are different ways through which we can write multiline comments. • Multiline comments using multiple hashtags (#) • Multiline comments using string literals (‘’’)
  • 32.
    Multi-Line Comments (#) •We use multiple hashtags (#) to write multiline comments in Python. • Each and every line will be considered as a single-line comment.
  • 33.
    Multi-Line Comments (‘’’) •Python ignores the string literals that are not assigned to a variable so we can use these string literals as Python Comments. • On executing the below code we can see that there will not be any output so we use triple quotes(‘’’) as multiline comments.
  • 34.
    Docstring Comments • Pythondocstring is the string literals with triple quotes that are appeared right after the function. • Python docstrings provide a convenient way to provide a help documentation with Python modules, functions, classes, and methods. • The docstring is then made available via the __doc__ attribute.
  • 35.
  • 36.
    Use of PythonComments • Make Code Easier to Understand – If we write comments in our code, it will be easier for future reference. Also, it will be easier for other developers to understand the code. • Using Comments for Debugging • If we get an error while running the program, we can comment the line of code that causes the error instead of removing it. For example, print(‘Welcome to VIT') # print(‘First Year) print(‘Students') Here, print(‘First Year) was causing an error so we have changed it to a comment. Now, the program runs without any errors. This is how comments can be a valuable debugging tool.
  • 37.
  • 38.
    Python variables • Variableis a name that is used to refer to memory location. Python variable is also known as an identifier and used to hold value. • In Python, we don't need to specify the type of variable because Python is a infer language and smart enough to get variable type. • Variable names can be a group of both the letters and digits, but they have to begin with a letter or an underscore. • It is recommended to use lowercase letters for the variable name.
  • 39.
    Rules- Naming variable Therules to name variable • The first character of the variable must be an alphabet or underscore ( _ ). • All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9). • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *). • Identifier name must not be similar to any keyword defined in the language. • Identifier names are case sensitive; for example, my name, and MyName is not the same. • Examples of valid identifiers: a123, _n, n_3, etc. • Examples of invalid identifiers: 1a, n%4, n 9, etc.
  • 40.
  • 41.
    Declaring Variable andAssigning Values • Python does not bind us to declare a variable before using it in the application. It allows us to create a variable at the required time. • We don't need to declare explicitly variable in Python. When we assign any value to the variable, that variable is declared automatically. • The equal (=) operator is used to assign value to a variable.
  • 42.
    Object references • Itis necessary to understand how the Python interpreter works when we declare a variable. • The process of treating variables is somewhat different from many other programming languages. • Python is the highly object-oriented programming language; that's why every data item belongs to a specific type of class. • Let's check the type of it by using the Python built-in type() function.
  • 43.
  • 44.
    Multiple Assignment 1. Assigningsingle value to multiple variables
  • 45.
    Multiple Assignment 2. Assigningmultiple values to multiple variables
  • 46.
    Python Variable Types •Two types of variables in Python – Local variable and – Global variable
  • 47.
    Local Variable Local Variable: Local variables are the variables that declared inside the function and have scope within the function.
  • 48.
    Global variable • Globalvariables can be used throughout the program, and its scope is in the entire program. • We can use global variables inside or outside the function.
  • 49.
    Delete Variable • Wecan delete the variable using the del keyword. • Syntax del <variable_name>
  • 50.
  • 51.
    Keywords • Keywords inPython are predefined words that have a special meaning to the interpreter. • They are reserved words that are used to perform a specific task in Python programming. • There are 35 keywords in Python 3.11.
  • 52.
    Rules for Keywordsin Python • Keywords are used to define the syntax of the coding. 1. The keyword cannot be used as an identifier, function, or variable name. 2. All the keywords in python should be in lowercase except True and False.
  • 55.
    Example – True,False, and, or not
  • 56.
    Example of for,if, in, break, continue keywords
  • 57.
    Example of def,if, and else keywords
  • 58.
    Example of alambda keyword
  • 59.
  • 60.
  • 61.
    Data types • PythonData Types are used to define the type of a variable. • It defines what type of data we are going to store in a variable. • The data stored in memory can be of many types. • For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters.
  • 62.
    Types Python has variousbuilt-in data types • Numeric - int, float, complex • String - str • Sequence - list, tuple, range • Binary - bytes, bytearray, memoryview • Mapping - dict • Boolean - bool • Set – set • None - NoneType
  • 63.
    Python Numeric DataType • Python numeric data types store numeric values. Number objects are created when you assign a value to them. • 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)
  • 64.
    Examples •Python allows youto 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.
  • 65.
  • 66.
    String Data Type •Python Strings are identified as a contiguous set of characters represented in the quotation marks. • 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
  • 67.
  • 68.
    Sequence - ListData Type • A Python list contains items separated by commas and enclosed within square brackets ([]) • 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 where as C array can store elements related to a particular data type.
  • 69.
    List Data Type- Example
  • 70.
    Sequence - TupleData Type • A Python tuple consists of a number of values separated by commas. • Unlike lists, however, tuples are enclosed within parentheses.
  • 71.
  • 72.
    Tuple and ListDifference • List has mutable nature i.e., list can be changed or modified after its creation according to needs. • whereas tuple has immutable nature i.e., tuple can’t be changed or modified after its creation. list = [1,2,3] tuple = (1,2,3) print(list) print(tuple)
  • 73.
  • 74.
    Sequence - range •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.
  • 75.
    Range() • syntax ofthe function: range(start, stop, step) 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)
  • 76.
  • 77.
    Dictionary • A dictionaryis a key-value pair set arranged in any order. • It stores a specific value for each key, like an associative array or a hash table. • Value is any Python object, while the key can hold any primitive data type. • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
  • 78.
    Dictionary Example • Pythondictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.
  • 79.
    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.
  • 80.
  • 81.
  • 82.
    Set • The datatype's unordered collection is Python Set. • It is iterable, mutable(can change after creation), and has remarkable components. • The elements of a set have no set order; It might return the element's altered sequence. • Either a sequence of elements is passed through the curly braces and separated by a comma to create the set or the built-in function set() is used to create the set. It can contain different kinds of values.
  • 83.
  • 84.
  • 85.
    Operators • Python operatorsare 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.
  • 86.
    Types of PythonOperators • Arithmetic Operators • Comparison (Relational) Operators • Assignment Operators • Logical Operators • Bitwise Operators • Identity Operators
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
    Bitwise Operator Operat or 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 Complement Inverts all the bits << Binary Left Shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Binary Right Shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
  • 94.
  • 95.
  • 96.
    Pre ce dence of Op era tors • An expression in python consists of variables, operators, values, etc. • When the Python interpreter encounters any expression containing several operations, all operators get evaluated according to an ordered hierarchy, called operator precedence.
  • 97.
    Operators Precedence Table OperatorsMeaning () Parentheses ** Exponent +x, -x, ~x Unary plus, Unary minus, Bitwise NOT *, /, //, % Multiplication, Division, Floor division, Modulus +, - Addition, Subtraction <<, >> Bitwise shift operators & Bitwise AND ^ Bitwise XOR | Bitwise OR ==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators not Logical NOT and Logical AND or Logical OR
  • 98.
  • 99.
  • 100.
  • 101.
    Expressions in Python •An expression is a combination of operators and operands that is interpreted to produce some other value. • In any programming language, an expression is evaluated as per the precedence of its operators. • So that if there is more than one operator in an expression, their precedence decides which operation will be performed first.
  • 102.
    Types of Expressions 1.Constant Expressions 2. Arithmetic Expressions 3. Integral Expressions 4. Floating Expressions 5. Relational Expressions 6. Logical Expressions 7. Bitwise Expressions 8. Combinational Expressions
  • 103.
    Constant Expression • Theexpressions have constant values only Example Answer : 15.5
  • 104.
    Arithmetic Expressions • Anarithmetic expression is a combination of numeric values, operators, and sometimes parenthesis. The result of this type of expression is also a numeric value. • The operators used in these expressions are arithmetic operators like addition, subtraction, etc.
  • 105.
  • 106.
    Integral Expressions • Thisexpression produces only integer results after all computations and type conversions. Output: 12
  • 107.
    Floating Expressions • Theexpressions produce floating point numbers as result after all computations and type conversions. Output: 5.0
  • 108.
    Relational Expressions • Inthese types of expressions, arithmetic expressions are written on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per relational operator and produce a boolean output in the end. These expressions are also called Boolean expressions.
  • 109.
  • 110.
    Logical Expressions • Theexpressions that result in either True or False. It basically specifies one or more conditions. • For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return False. • Logical operations are and, or, not
  • 111.
  • 112.
    Bitwise Expressions • Computationsare performed at bit level. • Example Output: 1 12
  • 113.
    Combinational Expressions • Wecan use different types of expressions in a single expression - combinational expressions • when we combine different types of expressions or use multiple operators in a single expression, operator precedence comes into play. Output: 10
  • 114.
  • 115.
    Python Functions A functionis a collection of related statements that performs a specific task. • Built-in functions – 68 built-in functions • User-defined functions -To define a user-defined function, the def keyword is used • Anonymous functions- these are also known as lambda functions.
  • 116.
    Build-in Functions • Thebuilt-in Python functions are pre-defined by the python interpreter. There are 68 built-in python functions. • These functions perform a specific task and can be used in any program, depending on the requirement of the user.
  • 118.
  • 119.
  • 120.
  • 121.
    Import Packages • Importin python is similar to #include header_file in C/C++. • Python modules can get access to code from another module by importing the file/function using import. • The import statement is the most common way of invoking the import machinery, but it is not the only way.
  • 122.
    Import () • importmodule_name • import module_name.member_name • from module_name import *
  • 123.
    import module_name When theimport is used, it searches for the module initially in the local scope by calling __import__() function. The value returned by the function is then reflected in the output of the initial code.
  • 124.
    import module_name.member_name • Inthe above code module, math is imported, and its variables can be accessed by considering it to be a class and pi as its object. The value of pi is returned by __import__(). • pi as a whole can be imported into our initial code, rather than importing the whole module.
  • 125.
    from module_name import* • All the functions and constants can be imported using *.