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

Module1PPT (1)

Introduction to python programming,flow control,functions,loops

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 DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module1PPT (1)

Introduction to python programming,flow control,functions,loops

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 DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

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
D

r.Thyagaraju GS
Dr.

Thyagaraju GS

Dr.Thyagaraju GS
Dr.Thyagar

aju 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

• A variable is a name that refers to a value. In


Variable Python, a variable is a named storage location
that holds a value. pi = 3.1415926535897931,
• An assignment statement creates new
variables as illustrated in the example below: area_of _circle = pi*r*r.
x = 10
Examples To know the type of the variable one can use
Message =‘Python Programming ‘, type () function.
Ex: type(p)
p =1000, t= 2, r=3.142, To display the value of a variable, you can use a
print statement:
Si = p*t*r/100, Ex: print (Si) ; print(pi) Dr.Thyagaraju GS
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 1: x = 40 Example 2: a, b, c = y=3


1, 2, 3 result = x + y
Example 4: x = 10 Example 3: x = 5
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

Operators and operands


Op era tor
Operation Example Evaluates to
• Operators are special symbols that ** Exponent 5**3 125
represent computations like are called operands. // Integer
addition and multiplication. The • The operators +, -, *, /, and ** Division/Floore d quotient
values the operator is applied to % Modulus/Rema inder 33%7 5 33//5 6

perform addition, subtraction, multiplication, / Division 23/7 3.28571428571 42856


division, and exponentiation, as in the following * Multiplication 7*8 56 - Subtraction 8 – 5 3
examples:
+ 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
Example2 3*4.0
(5-2)*((8+4)/(5-2)) 3 * 12.0
((8+4)/(5-2)) 3*(12/(5-2))
Dr.Thyagaraju GS

3*(12/3)
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

• Python supports various types of literals,


2. Literals in Python including numeric literals, string literals,
Boolean literals, and more.
1. Numeric literals: Numeric literals represent numeric values
• In Python, literals are the raw, literal such as integers, floating-point numbers, and complex numbers.
Examples: x = 10, y = 3.14, z = 2 + 3j
values that are used to represent data in
the code. They are fixed values that are 2. String literals: String literals represent sequences of characters
directly assigned to variables or used as enclosed in either single quotes (') or double quotes (").
Examples: name = 'John', sage = "Hello, world!“
constants.
3. Boolean literals: Boolean literals represent the truth values Dr.Thyagaraju GS

True and False.


Examples: is_valid = True 3.Operators
4. None literal: The None literal represents the absence of a
value or a null value. It is often used to indicate the absence of a
meaningful result or as an initial value for variables. • A Symbol or a word that performs some
Example: result = None
kind of
4. Operator Literals : Operator literals include arithmetic operation on given values and returns the
operators, comparison operators, assignment operators, logical result.
operators, and more.
Examples: +,-,/,//,%,*,**, <,>,!=,==,and,or,not,etc. • There are 7 types of
operators available for
Python: Arithmetic Operator, Assignment
Operator,
Comparison Operator, Logical Operator,
Bitwise Operator, Identity Operator and
Dr.Thyagaraju GS
Membership Operator.
1. Arithmetic operators: +, -, *, /, %, **, //
2. Assignment operators: =, +=, -=, *=, /=,
%=, **=, //=
3. Comparison operators: ==, !=, >, <, >=,
<= 4. Logical operators: and, or, not
5. Bitwise operators: &, |, ^, ~, <<, >> 6.
Membership operators: in, not in 7.
Identity operators: is, is not
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

• In Python the two Boolean Values are


Boolean Values: True and False and the Python type is
bool.
• A Boolean value is either true or false. type(True)
# output : bool print(context) #output : True

type(False)
# output : bool

type(true)
# output: Name Error : name “ true” is not
defined

type(false) # output: Name Error : name “


false” is not defined

context = 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 5 == 6 # output: False

P = “hel”
P + “lo” == “hello” # output: True Dr.Thyagaraju GS
Comparison Operators 55 == 55 # output: True
55
== 79 # output: False
>= Greater than
Operato Meaning or equal to
r == Equal to
7!=10 # output : True
!= Not Equal to
7!=7 #output : False
< Less than True == True # output: True
> Greater than True != False # output: True
<= Les than or
equal to 12< 13 # output: True
55.55 > 66.75 # output : False
“tag”< = 2 Type error : ‘<’ is not supported between instances of ‘str’ and
‘int’. Dr.Thyagaraju GS
# output :

Difference between == and = Operator


= ==
It is an assignment It is a comparison operator
operator
It is used for assigning It is used for comparing two values.
the 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 and False # output : False False and True #
output : False False and False # output :False
Op1 Op2 Op1 and Op2
True False False
False True False
False False False
True True True

True or True # output : True


True or False # output : True
False or True # output : True
False or False # output :False
Op1 Op2 Op1 or Op2
True False True
False 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:

a) Conditions:
Conditions are Boolean expressions with the boolean values True or False. Flow control statements decides what to do
based on the condition whether it is true or false.
b) Blocks of Code /Clause:
The set of more than one statements grouped with same indentation so that they are syntactically equivalent to a single
statement is known as Block or Compound Statement. One can tell when a block begins, and ends based on indentation
of the statements. Following are 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

Conditional Control Statements:


Flow Control
• if statement: Executes a block of code if a specified condition is
statements true.
• elif statement: Allows you to check additional conditions if the
Loop Control Statements:

previous if or elif conditions are false. • break statement: Terminates the innermost loop and continues
• else statement: Executes a block of code if none of the previous with the next statement after the loop.
conditions are true. • continue statement: Skips the rest of the current iteration and
moves to the next iteration of the loop.
Looping Statements: • pass statement: Acts as a placeholder, allowing you to create
empty code blocks without causing syntax errors
• for loop: Iterates over a sequence (such as a list, tuple, string, or
range) and executes a block of code for each item in the sequence.
• while loop: Repeats a block of code as long as a specified Exception Handling Statements:

condition is true. • try statement: Defines a block of code where exceptions might
Flow control statements in Python are used to control occur.
the order of execution and make decisions based on
• except statement: Specifies the code to execute if a specific
certain conditions. The main flow control statements
in Python include exception occurs within the try block.
• finally statement: Defines a block of code that will be 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.Thyagar

aju 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

You might also like