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/
Applications
• Web andinternet development
• Scientific and numeric computing
• Education
• Desktop GUIs
• Software and Game development, robot etc
• Network programming
• Business applications
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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>
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.
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.
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
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.
Sequence - TupleData Type
• A Python tuple consists of a number of values
separated by commas.
• Unlike lists, however, tuples are enclosed
within parentheses.
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)
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)
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.
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.
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.
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
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
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.
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.
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.
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
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
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.
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.
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.