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

Module1PPT (1)

Uploaded by

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

Module1PPT (1)

Uploaded by

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

Introduction to Python Programming

(BPLCK205B)

Dr. Thyagaraju G S

Dr.Thyagaraju GS
Modules
• Module1: Python Basics, Flow control, Functions
• Module2 : Lists, Tuples and Dictionaries
• Module3: Strings, Reading and Writing Files
• Module 4: Organizing Files and Debugging
• Module 5: Classes and Objects, Classes and Methods,
Classes and Functions

Dr.Thyagaraju GS
Module 1:
• Python Basics: Entering Expressions into the Interactive Shell, The Integer,
Floating-Point, and String Data Types, String Concatenation and Replication,
Storing Values in Variables, Your First Program, Dissecting Your Program,
• Flow control: Boolean Values, Comparison Operators, Boolean Operators,
Mixing Boolean and Comparison Operators, Elements of Flow Control, Program
Execution, Flow Control Statements, Importing Modules, Ending a Program Early
with sys.exit(),
• Functions: def Statements with Parameters, Return Values and return
Statements,The None Value, Keyword Arguments and print(), Local and Global
Scope, The global Statement, Exception Handling, A Short Program: Guess the
Number

Dr.Thyagaraju GS
1.1 Python Basics

• Entering Expressions into the Interactive Shell,


• The Integer, Floating-Point, and String Data
Types,
• String Concatenation and Replication,
• Storing Values in Variables,
• Your First Program, Dissecting Your Program,

Dr.Thyagaraju GS
Entering Expressions into the Interactive
Shell
• In Python, expressions are combinations of values,
variables, operators, and function calls that can be evaluated
to produce a result. They represent computations and return
a value when executed. Here are some examples of
expressions in Python:
• Examples: 17, x, x+17 , 1+2*2 , X**2, x**2 + y**2

Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
Value
• A value is a letter or a number.
• In Python, a value is a fundamental piece of data that
can be assigned to variables, used in expressions, and
manipulated by operations.
• Values can be of different types, such as numbers,
strings, booleans, lists, tuples, dictionaries, and more.
Each type of value has its own characteristics and
behaviors.
Dr.Thyagaraju GS
Examples

• x = 10 # integer
• y = 3.14 # floating-point number
• z = 2 + 3j # complex number
• name = "John" # string
• message = 'Hello, World!' # string
• is_true = True # Boolean Value
Dr.Thyagaraju GS
type() function
• In Python, the type() function is used to determine
the type of a given object or value.
• It returns the data type of the object as a result.

Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
String Concatenation

• String concatenation is the process of combining two or more


strings together to create a single string. In Python, you can
concatenate strings using the + operator.
• Here's an example:

Dr.Thyagaraju GS
String Replication

• String replication allows you to repeat a string multiple times. In Python,


you can replicate a string by using the * operator.
• Here's an example:

Dr.Thyagaraju GS
Dr.Thyagaraju GS
Examples
Message = ‘Python Programming ‘,
Variable
p =1000, t= 2, r=3.142,

• A variable is a name that refers to a Si = p*t*r/100,


value. In Python, a variable is a
named storage location that holds a pi = 3.1415926535897931,
value.
• An assignment statement creates area_of _circle = pi*r*r.
new variables as illustrated in the
example below: To know the type of the variable one can use
x = 10 type () function.
Ex: type(p)
To display the value of a variable, you can use
a print statement:
Dr.Thyagaraju GS
Ex: print (Si) ; print(pi)
Rules for writing Variable names

1.Variable names can be a combination of letters in lowercase


(a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_).
2.Variable names cannot start with a number/digit.
3.Keywords cannot be used as Variable names.
4.Special symbols like !, @, #, $, % etc. cannot be used in
Variable names.
5.Variable names can be of any length.
6.Variable name must be of single word.
Dr.Thyagaraju GS
Valid Variable Names and Invalid Variable
Names
Valid Variable Names Invalid Variable Names
python12 current- account(hyphens are not allowed)
Simple savings account (spaces are not allowed)
interest_year 4freinds (can’t begin with a number)
_rate_of_interest 1975 (can’t begin with a number)
_spam 10April_$ (cannot begin with a number and special
characters like $ are not allowed)
HAM Principle#@( special characters like # and @ are not
allowed)
account1234 ‘bear’ ( special characters like ‘ is not allowed)
Dr.Thyagaraju GS
Storing Values in a Variables

• Values can be stored in a variable using an Assignment statement.


• An assignment statement consists of a variable name, an equal (=) sign
and the value to be stored.

Example 3:
Example 1: Example 2:
x = 40
x=5
a, b, c = 1, 2, 3
y=3
result = x + y
Example 4:

x = 10
x = x + 5 # x is updated to 15 Dr.Thyagaraju GS
Dissecting the Simple Program

Dr.Thyagaraju GS
Dr.Thyagaraju GS
Comments
• Comments are readable explanation or descriptions that help
programmers better understand the intent and functionality
of the source code.
• Comments are completely ignored by interpreter.

Dr.Thyagaraju GS
Advantages of Using Comments:

1.Makes code more readable and understandable.


2.Helps to remember why certain blocks of code were
written.
3.Can also be used to ignore some code while testing other
blocks of code.

Dr.Thyagaraju GS
Single Line Comments in Python:

Dr.Thyagaraju GS
Multiline Comments
1. Using # at the beginning of each line of comment on multiple lines
Example:
# It is a
# multiline
# comment

2. Using String Literals ''' at the beginning and end of multiple lines

Example:
'''
I am a
Multiline comment!
''' Dr.Thyagaraju GS
Dr.Thyagaraju GS
The len() Function
• In Python, the len() function is used to determine the length of an
object, such as a string, list, tuple, or any other iterable.

Dr.Thyagaraju GS
Op Operation Example Evaluates to
Operators and era
operands tor

** Exponent 5**3 125


• Operators are special symbols that
represent computations like % Modulus/Rema 33%7 5
addition and multiplication. The inder
values the operator is applied to are // Integer 33//5 6
called operands. Division/Floore
• The operators +, -, *, /, and ** d quotient
perform addition, subtraction, / Division 23/7 3.28571428571
multiplication, division, and 42856
exponentiation, as in the following * Multiplication 7*8 56
examples: - Subtraction 8–5 3
+ Addition 7+ 3 10
Dr.Thyagaraju GS
Order of operations

• When more than one operator appears in an expression, the order of


evaluation depends on the rules of precedence.
• PEMDAS order of operation is followed in Python:
• Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want.
• Exponentiation has the next highest precedence,
• Multiplication and Division have the same precedence, which is higher than
• Addition and Subtraction, which also have the same precedence.
• Operators with the same precedence are evaluated from left to right.

Dr.Thyagaraju GS
Example1

Dr.Thyagaraju GS
(5-2)*((8+4)/(5-2))
3 * ((8+4)/(5-2))
Example2 3*(12/(5-2))
3*(12/3)
3*4.0
12.0
Dr.Thyagaraju GS
Example3 : Invalid Expressions

Dr.Thyagaraju GS
Python Character Set :

• The set of valid characters recognized by Python like letter, digit or any other
symbol. The latest version of Python recognizes Unicode character set. Python
supports the following character set:
• Letters : A-Z ,a-z
• Digits :0-9
• Special Symbols : space +-/*\**()[]{}//=!= == <>,”””,;: %!#?$& ^=@_
• White Spaces : Blank Space, tabs(->), Carriage return , new line , form feed
• Other Characters : All other 256 ACII and Unicode characters

Dr.Thyagaraju GS
Python Tokens:

A token (lexical unit) is the smallest element of Python script that is


meaningful to the interpreter. Python has following categories of
tokens:
1. Identifiers
2. Literals
3. Operators
4. Delimiters
5. Keywords

Dr.Thyagaraju GS
1.Identifiers
• Identifiers are names that you give to
a variable , class or Function.
• There are certain rules for naming
identifiers similar to the variable
declaration rules , such as :
• No Special character except_ ,
• Keywords are not used as identifiers ,
• the first character of an identifier should
be _ underscore or a character ,
• but a number is not valid for identifiers
and
• identifiers are case sensitive In the above example, we have used identifiers like
my_variable, counter, calculate_area, MyClass, and math.
Dr.Thyagaraju GS
1. Numeric literals: Numeric literals represent numeric values such
as integers, floating-point numbers, and complex numbers.
2. Literals in Python Examples: x = 10, y = 3.14, z = 2 + 3j

2. String literals: String literals represent sequences of characters


enclosed in either single quotes (') or double quotes (").
• In Python, literals are the raw, Examples: name = 'John', sage = "Hello, world!“

literal values that are used to 3. Boolean literals: Boolean literals represent the truth values True
represent data in the code. and False.
Examples: is_valid = True
They are fixed values that are
directly assigned to variables 4. None literal: The None literal represents the absence of a value or
or used as constants. a null value. It is often used to indicate the absence of a meaningful
result or as an initial value for variables.
• Python supports various types Example: result = None
of literals, including numeric 4. Operator Literals : Operator literals include arithmetic operators,
literals, string literals, Boolean comparison operators, assignment operators, logical operators, and
literals, and more. more.
Examples: +,-,/,//,%,*,**, <,>,!=,==,and,or,not,etc.

Dr.Thyagaraju GS
3.Operators

• A Symbol or a word that


performs some kind of 1. Arithmetic operators: +, -, *, /, %, **, //
operation on given values 2. Assignment operators: =, +=, -=, *=, /=,
and returns the result.
%=, **=, //=
• There are 7 types of
operators available for 3. Comparison operators: ==, !=, >, <, >=, <=
Python: Arithmetic Operator, 4. Logical operators: and, or, not
Assignment Operator, 5. Bitwise operators: &, |, ^, ~, <<, >>
Comparison Operator, Logical
Operator, Bitwise Operator, 6. Membership operators: in, not in
Identity Operator and 7. Identity operators: is, is not
Membership Operator.
Dr.Thyagaraju GS
4. Delimiters

• Delimiters are the symbols which can be used as separators of values


or to enclose some values.
• Examples : Comma (,),Colon (:),Parentheses (( and )),Square brackets
([ and ]),Curly braces ({ and }),Quotation marks (' and ") and Backslash
(\)

Dr.Thyagaraju GS
5. Keywords
• The reserved words of Python which have a special fixed meaning for the
interpreter are called keywords.
• No keyword can be used as an identifier or variable names. There are 36 keywords
in python as listed below:

Dr.Thyagaraju GS
1.2 Flow Control

Syllabus:
• Boolean Values, Comparison Operators, Boolean
Operators, Mixing Boolean and Comparison Operators,
• Elements of Flow Control, Program Execution, Flow
Control Statements,
• Importing Modules, Ending a Program Early with
sys.exit().

Dr.Thyagaraju GS
type(True)
Boolean Values: # output : bool

• A Boolean value is type(False)


either true or false. # output : bool
• In Python the two
Boolean Values are type(true)
True and False and # output: Name Error : name “ true” is not defined
the Python type is
bool.
type(false) # output: Name Error : name “ false” is
not defined

context = True
print(context) #output : True
Dr.Thyagaraju GS
• A Boolean expression is an
Boolean Expressions expression that evaluated to
produce a result which is a
Boolean value.

5 == (1+4) # output : True P = “hel”


P + “lo” == “hello” # output: True
5 == 6 # output: False

Dr.Thyagaraju GS
55 == 55 # output: True
Comparison Operators 55 == 79 # output: False
7!=10 # output : True
Operator Meaning 7!=7 #output : False
== Equal to True == True # output: True
!= Not Equal to True != False # output: True
< Less than
12< 13 # output: True
> Greater than
55.55 > 66.75 # output : False
<= Les than or
equal to
“tag”< = 2
>= Greater than or
equal to # output :
Type error : ‘<’ is not supported between instances of ‘str’ and ‘int’.
Dr.Thyagaraju GS
Difference between == and = Operator
= ==
It is an assignment It is a comparison operator
operator
It is used for assigning the It is used for comparing two values.
value to a variable It returns 1 if both the value is equal
otherwise returns 0
Constant term cannot be Constant term can be placed in the left-
place on left hand side hand side.
Example: Example: 1 ==1 is valid and return 1
1= x; is invalid
Dr.Thyagaraju GS
Boolean Operators:

True and True # output : True True or True # output : True


True and False # output : False True or False # output : True
False and True # output : False False or True # output : True
False and False # output :False False or False # output :False

Op1 Op2 Op1 and Op2 Op1 Op2 Op1 or Op2


True False False True False True
False True False
False True True
False False False
True True True False False False
True True True
Dr.Thyagaraju GS
Not operator:
• It is a unary operator and evaluates the expression to
opposite value true or false as illustrated below :

not True # output : False


not False # output : True
not not not not True # output : True

op not op
True False
False True
Dr.Thyagaraju GS
Mixing Boolean and Comparison Operators

x = 10
y = 20
x<y and x>y # output : False
(x<y) and (x!=y) or (x*2) and (x<20 or y<20) # output : True
2+2 == 4 and not 2+2 == 5 and 2*2 == 2+2 #output : True
5*7 +8 == 7 or not 5+7 ==10 and 5*4 ==20 #output : True

Dr.Thyagaraju GS
Elements of Flow Control
Flow control statements often starts with condition followed by a block of
code called clause. The two elements of Flow Control are discussed below:

b) Blocks of Code /Clause:


a) Conditions:
The set of more than one statements grouped with same
Conditions are Boolean expressions
indentation so that they are syntactically equivalent to a
with the boolean values True or
single statement is known as Block or Compound
False. Flow control statements
Statement. One can tell when a block begins, and ends
decides what to do based on the
based on indentation of the statements. Following are
condition whether it is true or false.
three rules for blocks:
1. Blocks begin when the indentation increases
2. Blocks can have nested blocks
3. Blocks end when the indentation decreases to zero

Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
Flow control statements in Python are used to control
Flow Control the order of execution and make decisions based on
certain conditions. The main flow control statements
statements in Python include
Conditional Control Statements: Loop Control Statements:
• if statement: Executes a block of code • break statement: Terminates the innermost loop and
if a specified condition is true. continues with the next statement after the loop.
• elif statement: Allows you to check • continue statement: Skips the rest of the current iteration
additional conditions if the previous if and moves to the next iteration of the loop.
or elif conditions are false. • pass statement: Acts as a placeholder, allowing you to create
• else statement: Executes a block of empty code blocks without causing syntax errors
code if none of the previous
conditions are true.
Exception Handling Statements:
Looping Statements: • try statement: Defines a block of code where exceptions
• for loop: Iterates over a sequence (such as a might occur.
list, tuple, string, or range) and executes a • except statement: Specifies the code to execute if a specific
block of code for each item in the sequence. exception occurs within the try block.
• while loop: Repeats a block of code as long • finally statement: Defines a block of code that will be
as a specified condition is true. executed regardless of whether an exception occurred or not.
Dr.Thyagaraju GS
if
statement

Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
2. If else
statement:

Dr.Thyagaraju GS
Dr.Thyagaraju GS
3. Nested if
else:

Dr.Thyagaraju GS
Dr.Thyagaraju GS
4. if – elif
ladder:

Dr.Thyagaraju GS
Example

Dr.Thyagaraju GS
Types of Loops Supported in Python
• The Python Language supports the following two looping
operations:
1.The while statement
2.The for statement

Dr.Thyagaraju GS
while
Statement

Dr.Thyagaraju GS
Dr.Thyagaraju GS
for Loop

Dr.Thyagaraju GS
Dr.Thyagaraju GS
range ( ) function:
The range() function returns a sequence of numbers,
starting from 0 to a specified number ,incrementing each
time by 1.
Syntax :

range(start,step,stop)

Dr.Thyagaraju GS
Dr.Thyagaraju GS
Infinite Loop
A loop becomes infinite loop
if a condition never becomes
FALSE. You must use caution
when using while loops
because of the possibility
that this condition never
resolves to a FALSE value.
This results in a loop that
never ends. Such a loop is
called an infinite loop.

Dr.Thyagaraju GS
break
and
continue

Dr.Thyagaraju GS
The 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.
• The pass statement is
a null operation; nothing happens
when it executes. The pass is also
useful in places where your code will
eventually go, but has not been
written yet (e.g., in stubs for example):

Dr.Thyagaraju GS
Importing Modules

• Each module is a Python program that contains a related group of functions that
can be embedded in your programs. For example, the math module has
mathematics related functions, the random module has random number–related
functions, and so on.
In code, an import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas

Dr.Thyagaraju GS
Importing math

Dr.Thyagaraju GS
Importing
random

Dr.Thyagaraju GS
Importing random

Dr.Thyagaraju GS
Ending a Program
Early with sys.exit ()

Dr.Thyagaraju GS
1.3 Functions
• Syllabus : def Statements with Parameters, Return Values and return
Statements, The None Value, Keyword Arguments and print(), Local
and Global Scope, The global Statement, Exception Handling, A Short
Program: Guess the Number

Dr.Thyagaraju GS
What is Function?
• A function is a group (or block ) of statements that perform a
specific task .
• Functions run only when it is called.
• One can pass data into the function in the form of
parameters.
• Function can also return data as a result.

Dr.Thyagaraju GS
Types of Functions

1.User Defined
2.Built in

Dr.Thyagaraju GS
User defined
Functions
• In Python, user-defined
functions are functions that
are created by the
programmer to perform
specific tasks. These
functions are defined using
the def keyword followed by
the function name,
parentheses for optional
parameters, and a colon to
start the function block.

Dr.Thyagaraju GS
Example

Dr.Thyagaraju GS
• Parameters are temporary variable
names within functions.
• The argument can be thought of as the Parameters and arguments
value that is assigned to that temporary
variable.
• 'n' here is the parameter for the
function 'cube'. This means that
anywhere we see 'n' within the
function will act as a placeholder until
number is passed an argument.
• Here 10 is the argument.
• Parameters are used in function
definition and arguments are used in
function call.

Dr.Thyagaraju GS
Function
without
parameters

Dr.Thyagaraju GS
Function with
parameters
but without
returning
values

Dr.Thyagaraju GS
Function with
parameters
and return
values

Dr.Thyagaraju GS
Function with
parameters
and return
values

Dr.Thyagaraju GS
Function which
return multiple
values

Dr.Thyagaraju GS
The None-
Value
• In Python there is a value
called None, which
represents the absence of a
value. None is the only value
of the None Type data type.
• (Other programming
languages might call this
value null, nil, or undefined.)
• Just like the Boolean True and
False values, None must be
typed with a capital N.

Dr.Thyagaraju GS
Keyword
Arguments and
print()

Keyword arguments
are identified by the
keyword put before
them in the function
call. Keyword
arguments are often
used for optional
parameters.

Examples : end and


sep. Dr.Thyagaraju GS
Keyword
Arguments and
print()

Keyword arguments
are identified by the
keyword put before
them in the function
call. Keyword
arguments are often
used for optional
parameters.

Examples : end and


sep. Dr.Thyagaraju GS
Local and
Global Scope

Dr.Thyagaraju GS
Local variable
cannot be
used in the
global scope

Dr.Thyagaraju GS
Local Scopes Cannot Use
Variables in Other Local
Scopes

Dr.Thyagaraju GS
Global Variable
Can be read
from a local
scope :

Dr.Thyagaraju GS
Local and Global
Variables with
the same Name
:

Dr.Thyagaraju GS
Global
Statement:

Dr.Thyagaraju GS
Exceptional
Handling

Dr.Thyagaraju GS
Try and
Except :

Dr.Thyagaraju GS
Try and
Except :

Dr.Thyagaraju GS
A Sample Program: Guess The number

Dr.Thyagaraju GS
Dr.Thyagaraju GS
Dr.Thyagaraju GS
Simple Project

Dr.Thyagaraju GS

You might also like