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

Mod1_ppt dda

The document provides an overview of Python basics, including data types, operators, flow control statements, and functions. It covers topics such as entering expressions, variable storage, comments, and the use of if, else, and while statements. Additionally, it includes programming examples and exercises to reinforce the concepts discussed.

Uploaded by

h13584962
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)
4 views

Mod1_ppt dda

The document provides an overview of Python basics, including data types, operators, flow control statements, and functions. It covers topics such as entering expressions, variable storage, comments, and the use of if, else, and while statements. Additionally, it includes programming examples and exercises to reinforce the concepts discussed.

Uploaded by

h13584962
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/ 161

MODULE- 1

PYTHON BASICS
FLOW CONTROL
FUNCTIONS
PYTHON BASICS
ENTERING EXPRESSIONS INTO THE
INTERACTIVE SHELL
ENTERING EXPRESSIONS INTO THE
INTERACTIVE SHELL
 A >>> prompt appears in the
interactive shell

 In the given example


 2 + 2 is called an
expression
 2 and 2 are values
 + is an operator

 The expression evaluates to a


single value

 A single value with no


operator is also an
expression
OPERATORS IN PYTHON
 The order of operations is
called precedence

 The ** operator is
evaluated first the
 *, /, //, and % operators
are evaluated next(from
left to right)
 and the + and - operators
are evaluated last (from
left to right).

 Parentheses to override the


usual precedence if you need
to.
OPERATORS IN PYTHON
THE INTEGER, FLOATING-POINT, AND
STRING DATA TYPES
THE INTEGER, FLOATING-POINT, AND
STRING DATA TYPES
 A data type is a category for values and every value belongs
to exactly one data type.

 The integer (or int) data type indicates values that are
whole numbers

 Numbers with a decimal point are called floating-point


numbers (or float)

 Python programs can also have text values enclosed in


single quotes called strings (or str)

 A string with no characters is called an empty string or


blank string
THE INTEGER, FLOATING-POINT, AND
STRING DATA TYPES
STRING CONCATENATION AND
REPLICATION
STRING CONCATENATION AND
REPLICATION
 The + operator is used for
string concatenation

 Both operands must be


strings for concatenation

 The * operator is used for


string replication

 One of the operands is a


string and the other is an
integer for string replication
STORING VALUES IN VARIABLES
STORING VALUES IN VARIABLES
 Variables are not declared with a datatype in Python

 Python is a dynamically-typed programming language

 The name of a variable should obey the following rules:


 It can be only one word with no spaces
 It can use only letters, numbers and underscore character
 It cannot begin with a number

 Variable names are case sensitive

 Values in variables are stored with an assignment


statement
STORING VALUES IN VARIABLES
COMMENTS IN PYTHON
COMMENTS IN PYTHON

 Comments are needed to make a code readable and for


documentation

 Comments in Python are written using '#' symbol

 For multi-line comments, '#' is placed at the beginning of the


comment in every line

 Multi-line comments are also written within a pair of three


single quotes
COMMENTS IN PYTHON
len(), input() and print() FUNCTIONS
len(), input() and print() FUNCTIONS

 The print() function displays the string value inside its


parentheses on the screen

 The input() function waits for the user input

 The len() function accepts a string value (or a variable


containing a string), and the function evaluates to the
integer value of the number of characters in that string
len(), input() and print() FUNCTIONS
len(), input() and print() FUNCTIONS

 The input() accepts input from user and stores it as a string

 For math operations, the input should be converted to


appropriate data type before evaluation
THE str(), int(), and float() FUNCTIONS
THE str(), int(), and float() FUNCTIONS

 The str() function can be passed an integer value and will


evaluate to a string value version of the integer

 The int() function can be passed an string or a float value


and will evaluate to an integer value

 The float() function can be passed an integer value and will


evaluate to a float value
THE str(), int(), and float() FUNCTIONS
>>> str(0)
'0’
>>> str(-3.14)
'-3.14’
>>> int('42’)
42
>>> int('-99’)
-99
>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14’)
3.14
>>> float(10)
10.0
CAN U GUESS 
>>> spam = input() >>> 42 == '42'
101 False
>>> spam >>> 42 == 42.0
'101’ True
spam = int(spam) >>> 42.0 == 0042.000
>>> spam True
101
>>>spam * 10 / 5
202.0
>>> int('99.99')
CONTD.,

The int() function is also useful if you need to round


a floating-point number down.
>>> int(7.7)
7
>>> int(7.7) + 1
8
CONTD….
FIRST PROGRAM
Once you’ve entered the below source code, save it so
that you won’t have to retype it each time you start. Click
the Save button, enter sa.py in the File Name field, and
then click Save.
UTPUT
PROGRAMMING EXAMPLES
1. Find the maximum of two numbers
2. Find the maximum of three numbers
3. Find Simple interest
Simple interest formula is given by:
Simple Interest = (P x T x R)/100
Where, P is the principle amount T is the time and R
is the rate
4. Print ASCII Value of Character
5. Print Area of Rectangle
6. Print Area of Circle
7. Print Area of Square
8. Print Area of Traingle
QUIZ
QUIZ
QUIZ
QUIZ
QUIZ
 Which operator has higher precedence in the
following list
FLOW CONTROL
FLOW CONTROL

 Flow control statements can decide which Python


instructions to execute under which conditions

 The flow control statements control the order of


program execution
CONTD ….
BOOLEAN VALUES
BOOLEAN VALUES
 The Boolean data type has only two values:

 True
 False

 The Boolean values True and False are not


enclosed in quotes

 They always start with a capital T or F

 Boolean values are used in expressions and can


be stored in variables

 True and False cannot be used as variable


names
COMPARISON OPERATORS
COMPARISON OPERATORS
 Comparison operators, also
called relational operators

 They compare two values and


evaluate down to a single
Boolean value
 The == and != operators can
actually work with values of any
data type
 The <, >, <=, and >= operators,
on the other hand, work
properly only with integer and
floating-point values
THE DIFFERENCE BETWEEN THE ==
AND = OPERATORS
 The == operator (equal to) asks whether two
values are the same as each other.
 The = operator (assignment) puts the value on
the right into the variable on the left.
BOOLEAN OPERATORS
BOOLEAN OPERATORS
 The Boolean operators
 and
 or
 not

 The and and or operators always take two


Boolean values (or expressions), so they’re
considered binary operators

 The not operator operates on only one Boolean


value (or expression) and is called a unary
operator
AND STATEMENT

a b c
0 0 0
0 1 0
1 0 0
1 1 1
OR STATEMENT

a b c
0 0 0
0 1 1
1 0 1
1 1 1
BOOLEAN OPERATORS

Fig: The Truth tables for and, or and not operators

Fig: Examples for and, or and not boolean operators


MIXING BOOLEAN AND COMPARISON
OPERATORS
MIXING BOOLEAN AND COMPARISON
OPERATORS
 Comparison operators can be
used with Boolean operators
 The expression on the left side of
Boolean operator will be
evaluated first
 Boolean operators are
evaluated in the following
order
 not
 and
 or
ELEMENTS OF FLOW CONTROL
ELEMENTS OF FLOW CONTROL
 Flow control statements often start with a part
called the condition

 Conditions are always followed by a block of code


called the clause

 Conditions always evaluate down to True or


False based on which the flow of execution is
decided

 Lines of Python code can be grouped together in


blocks
ELEMENTS OF FLOW CONTROL

 Rules for blocks are as follows

 Blocks begin when the indentation increases

 Blocks can contain other blocks

 Blocks end when the indentation decreases to


zero or to a containing block’s indentation
FLOW CONTROL STATEMENTS
FLOW CONTROL STATEMENTS
 if statements
 else statements

 elif statements

 while loop

 for loop

 break

 continue
IF STATEMENTS
 The most common type of flow control statement
 An if statement’s clause will execute if the
statement’s condition is True
 An if statement consists of the following:

 if keyword
 A condition (an expression) that evaluates to
True or False
 A colon
 Starting on the next line, an indented block of
code called the if clause
EXAMPLE OF IF STATEMENT
SIMPLE IF
ELSE

 An else statement doesn’t have a condition, and


in code,
 An else statement always consists of the
following:
 The else keyword
 A colon
 Starting on the next line, an indented block of code
(called the else clause)
CONTD ….
IF...ELSE S TATEMENT
The if..else statement evaluates test expression and will execute body of if only
when test condition is True.
If the condition is False, body of else is executed. Indentation is used to separate
the blocks.
IF...ELSE
Program to check whether a person is
eligible to vote or not

age = int (input("Enter your age? "))


if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")
PROGRAM TO CHECK WHETHER THE
NUMBER IS EVEN OR ODD

num = int(input("enter the


number?\n"))
if num%2 == 0:
print("Number is Even")
else:
print("Number is Odd")
PROGRAMMING EXAMPLES

1) A company decided to give bonus of 5% to employee if his/her


year of service is more than 5 years. Ask user for their salary
and year of service and print the net bonus amount.
2) Take values of length and breadth of a rectangle from user
and check if it is square or not.
3) Take two int values from user and print greatest among them.
4) A shop will give discount of 10% if the cost of purchased
quantity is more than 1000. Ask user for quantity Suppose,
one unit will cost 100.
Judge and print total cost for user.
5) Write a program to print absolute vlaue of a number entered
by user. E.g. INPUT: 1 OUTPUT: 1
INPUT: -1 OUTPUT: 1
A COMPANY DECIDED TO GIVE BONUS OF 5% TO
EMPLOYEE IF HIS/HER YEAR OF SERVICE IS MORE THAN
5 YEARS. ASK USER FOR THEIR SALARY AND YEAR OF
SERVICE AND PRINT THE NET BONUS AMOUNT.

print('Enter Salary')
salary = int (input())
print ("Enter year of service")
yos = int(input())
if yos > 5:
print ('Bonus is', .05 * salary)
else:
print ("No Bonus")
TAKE VALUES OF LENGTH AND BREADTH OF A
RECTANGLE FROM USER AND CHECK IF IT IS SQUARE
OR NOT.

print ("Enter the length")


length = int(input())
print("Enter the Breadth")
breadth = int(input())
if length == breadth:
print('yes, its square')
else:
print('No, its only Rectangle')
TAKE TWO INT VALUES FROM USER AND PRINT
GREATEST AMONG THEM.

print("Enter the first number")


first = int(input())
print("Enter the second number")
second = int(input())
if first > second:
print("Greatest is", first)
elif second > first:
print("Greatest is", second)
else:
print("Both are equal")
A SHOP WILL GIVE DISCOUNT OF 10% IF THE COST
OF PURCHASED QUANTITY IS MORE THAN 1000. ASK
USER FOR QUANTITY SUPPOSE, ONE UNIT WILL COST
100.
JUDGE AND PRINT TOTAL COST FOR USER.
print ('Enter The Quantity')
quantity = int(input())
if quantity*100 > 1000:
print ("cost is",((quantity*100)-(.1 * quantity*100)))
else:
print ("cost is",quantity*100)
WRITE A PROGRAM TO PRINT ABSOLUTE VALUE OF
A NUMBER ENTERED BY USER.
E.G. INPUT: 1 OUTPUT: 1
INPUT: -1 OUTPUT: 1

print ("Enter a number")


number = int(input())
if number < 0:
print (number * -1)
else:
print (number)
if...elif...else

The elif is short for else if. It allows


us to check for multiple
expressions.
If the condition for if is False, it
checks the condition of the next
elif block and so on.
If all the conditions are False, body
of else is executed.
Only one block among the several
if...elif...else blocks is executed
according to the condition.
The if block can have only
one else block. But it can
have multiple elif blocks.
CONTD ….
QUICK CMPARE
elif example1

number = int(input("Enter the number?"))


if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50")
elif number==100:
print("number is equal to 100")
else:
print("number is not equal to 10, 50 or
100")
ELIF EXAMPLE2
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
THE WHILE LOOP
WHILE LOOPS

 The while keyword Syntax


 A condition

 A colon while condition:


 Indented block of code #indented code
block

Output
WHAT DOES THE FOLLOWING CODE DO?

Output 1
Output 2
PROGRAM TO PRINT 1 TO 10 USING
WHILE LOOP

i=1
#The while loop will iterate until condition
becomes false.
while i<=10:
print(i)
i=i+1
PROGRAMS
 Write a Python program to input an integer
number and print its last digit
 Write a Python program to input a number
and count the number of digits in it using
while loop.
 Write a Python program to find multiplication
table of a number.
 Write a python program to input an integer
number and print reverse of that number.
 Write a Python program to input a positive
integer and find its factorial.
 Write a python program to input an integer
number and print reverse of that number Also
check the number is palindrome or not.
BREAK
STATEMENTS
#statement(s)
while condition :
#statement(s)
if break_condition :
break
#statement(s)
BREAK STATEMENTS

It is used to exit


from a loop

The break Output

keyword is used
BREAK STATEMENT WITH WHILE LOOP

i=0
while 1:
print(i)
i=i+1;
if i == 20:
break
print('came out of while loop')
break statement with while loop
Example Programs
Program to check prime number or not
num = int(input("Enter a number: "))

if num <= 1:
print(f"{num} is not a prime number.")
else:
i=2
while i <= num ** 0.5:
if num % i == 0:
print(f"{num} is not a prime number.")
break
i=i+1
else:
print(f"{num} is a prime number.")
CONTINUE
STATEMENTS

• It skips the current iteration

• The continue keyword is used


EXAMPLE FOR CONTINUE
STATEMENT

Output:
i=0
1
while(i < 10): 2
i = i+1 3
4
if(i == 5): 6
continue 7
print(i) 8
9
10
CONTINUE STATEMENTS
Output 1

Output 2
Values like 0, 0.0, ' '(empty string)
are considered False

All other values are considered


True

Such values in other datatypes


(int, float, string) are equivalent
to True or False
TRUTHY AND
FALSEY Such values can be used in
VALUES conditions
WHAT IS THE OUTPUT OF THE FOLLOWING
CODE?

Output
You could have entered
name != ' ' instead of not
name, and
numOfGuests != 0 instead
of numOfGuests
THE FOR LOOPS AND
THE RANGE()
FUNCTION
FOR LOOPS

 It is used to execute a block of code a


certain number of times
 This is done using for loop statement
and a range() function
 A for loop contains
 for keyword
 A variable
 The in keyword
 range() function with up to 3
integers
 A colon
 for code block with indentation
RANGE()

 Used to generate a sequence of numbers


 range(10) will generate numbers from 0 to 9 (10
numbers)
 Can define the start, stop and step size as range

 Default step size is 1

 All numbers generated are not stored in memory

 >>> range(10)

range(0, 10)
USING RANGE() IN FOR
 range() is also used in for loops to iterate over a
sequence of numbers
 Example

n = int(input('Enter a number'))
for i in range(1,n+1):
print(i)
Enter a number 3
1
2
3
>>>
EXAMPLE OF FOR LOOP AND RANGE()

Output
WHAT IS THE OUTPUT OF THE FOLLOWING
CODE?

Output
EXAMPLE OF FOR LOOP AND RANGE( )

total = 0
for num in range(10):
total = total + num Outpu
print(total) t:
45
THE STARTING, STOPPING, AND STEPPING
ARGUMENTS TO RANGE()
Syntax
range(start, stop, step)

Output
PROGRAM TO PRINT TABLE OF GIVEN
NUMBER.

Output:
Enter the
n = int(input('Enter the
number: 19
number: \n')) 19 * 1 = 19
for i in range(1,11): 19 * 2 = 38
c = n*i 19 * 3 = 57
19 * 4 = 76
print(n,'*',i,'=',c) 19 * 5 = 95
19 * 6 = 114
19 * 7 = 133
19 * 8 = 152
19 * 9 = 171
19 * 10 = 190
PROGRAM TO PRINT EVEN NUMBER
USING STEP SIZE IN RANGE().

Output:
Enter the
number: 21
n = int(input('Enter the number: 2
\n')) 4
6
for i in range(2,n,2):
8
print(i) 10
12
14
16
18
20
NEGATIVE ARGUMENTS IN RANGE()

Output
PROGRAMS
IMPORTING
MODULES
IMPORTING MODULES
 Python also comes with a set of modules called the
standard library

 Each module is a Python program that contains a


related group of functions

 These modules can be embedded in other programs

 Examples
 math module has mathematics-related functions
 random module has random number-related
functions
IMPORT STATEMENT

 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
EXAMPLES OF IMPORT MODULE
Run 1:

Run 2:

Run 1: Run 2:
CONTD….
FROM IMPORT STATEMENTS

 The from keyword is used to import only a


specified section from a module.

 composed of
 the from keyword
 the import keyword
 an asterisk

 E.g.
from random import *
SYS

The sys module provides functions and variables


used to manipulate different parts of the Python
runtime environment.

sys.argv
CONTD ….
 sys.version

 sys.path

 sys.maxsize
ENDING A PROGRAM EARLY WITH THE
SYS.EXIT() FUNCTION
SYS.EXIT()
 Used to terminate a program
 The exit method belongs to sys module

 Therefore, sys module must be imported before


using this function

Output
FUNCTIONS

 A function is like a mini program within a program

 A major purpose of functions is to group code that gets


executed multiple times

 A program may have


 Built – in functions
 User defined functions
BUILT – IN FUNCTIONS SO FAR..

 print()

 input()

 len()
USER-DEFINED FUNCTIONS

• A function definition contains Syntax

• def keyword
• Function name
• A colon
• An indented block of code

• Function names are case


sensitive
EXAMPLE OF USER DEFINED FUNCTION

• 2 parts of a function

• Function definition

• Function call

Output
ARGUMENTS AND PARAMETERS
ARGUMENTS AND PARAMETERS

 Arguments are values passed in a function call

 Parameters are variables that contain arguments.

 The value stored in a parameter is forgotten when the


function returns.
ARGUMENTS AND PARAMETERS

Output
RETRUN VALUES AND RETURN
STATEMENTS
RETURN VALUES AND RETURN
STATEMENTS

 A function definition can contain a return statement

 A return statement specifies what value the function returns

 A return statement consists of the following:


 The return keyword
 The value or expression that the function should return

 The expression with a return statement evaluates to a return value


RETURN VALUES AND RETURN
STATEMENTS

Output Output
THE NONE VALUE
THE NONE VALUE

 None represents the absence of a value

 It belongs to NoneType data type

 It begins with an uppercase N

 Python adds return None to the end of any function definition


with no return statement

 If a return statement without a value is used, then None is


returned
EXAMPLE OF NONETYPE

Output

Output
KEYWORD ARGUMENTS AND THE PRINT() FUNCTION
KEYWORD ARGUMENTS AND THE PRINT()
FUNCTION
 Keyword arguments are often used for optional
parameters.

 For example, the print() function has optional


parameters end and sep

 Specify what should be printed at the end of its


arguments and between its arguments (separating
them), respectively
KEYWORD ARGUMENTS AND THE PRINT()
FUNCTION
KEYWORD ARGUMENTS AND THE PRINT()
FUNCTION
 The print()function automatically adds a newline character to
the end of the string it is passed.

 The end keyword argument can be set to change the newline


character to a different string.

 When you pass multiple string values to print(), the function


will automatically separate them with a single space.

 But the default separating string can be replaced by passing the


sep keyword argument a different string.
LOCAL AND GLOBAL SCOPE
LOCAL AND GLOBAL SCOPE
 Parameters and variables that are assigned in a called function
are said to exist in that function’s local scope.

 Variables that are assigned outside all functions are said to exist
in the global scope.

 A variable that exists in a local scope is called a local variable

 A variable that exists in the global scope is called a global


variable.

 It cannot be both local and global.


LOCAL AND GLOBAL SCOPE

 Code in the global scope, outside of all functions, cannot use any
local variables.

 Code in a local scope can access global variables.

 Code in a function’s local scope cannot use variables in any other


local scope.

 You can use the same name for different variables if they are in
different scopes.
LOCAL VARIABLES CANNOT BE USED IN THE
GLOBAL SCOPE
LOCAL SCOPES CANNOT USE VARIABLES IN OTHER
LOCAL SCOPES
GLOBAL VARIABLES CAN BE READ FROM A LOCAL
SCOPE
LOCAL AND GLOBAL VARIABLES WITH THE
SAME NAME
THE GLOBAL STATEMENT
THE GLOBAL STATEMENT

 To modify a global variable


from within a function

 global statement is used


RULES FOR IDENTIFYING LOCAL AND GLOBAL
VARIABLES

 If a variable is being used in the global scope (that is, outside of


all functions), then it is always a global variable.

 If there is a global statement for that variable in a function, it is a


global variable.

 Otherwise, if the variable is used in an assignment statement in


the function, it is a local variable.

 But if the variable is not used in an assignment statement, it is a


global variable.
RULES FOR IDENTIFYING LOCAL AND GLOBAL
VARIABLES
EXCEPTION HANDLING
PYTHON EXCEPTION

Common Exceptions
ZeroDivisionError: Occurs when a number is divided by zero.

NameError: It occurs when a name is not found. It may be local or


global.

IndentationError: If incorrect indentation is given.

IOError: It occurs when Input Output operation fails.

EOFError: It occurs when the end of the file is reached, and yet
operations are being performed
EXCEPTION HANDLING

An error, or exception, in your program means the entire program will


crash.

Errors can be handled with try and except statements

The code that could potentially have an error is put in a try clause.

The program execution moves to the start of a following except clause if an


error happens.

After running that code in except, the execution continues as normal.


THE PROBLEM WITHOUT HANDLING
EXCEPTIONS

a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)

#other code: Output:


print("Hi I am other part of the
program") Enter a:12
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
EXCEPTION HANDLING IN PYTHON

The try-expect statement


Example 1

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")

Output:

Enter a:30
Enter b:0
Can't divide with zero
THE EXCEPT STATEMENT WITH NO
EXCEPTION

Example

try: Enter a:10


a = int(input("Enter a:"))
b = int(input("Enter b:"))
Enter b:4
c = a//b; a/b = 2
print("a/b = “,c)
except: Hi I am else block
print("can't divide by zero")
else:
print("Hi I am else block")

Enter a:5
Enter b:0
can't divide by zero
EXCEPTION HANDLING

 An error, or exception, in your


program means the entire
program will crash.

 Errors can be handled with try


and except statements
EXCEPTION HANDLING

 The code that could


potentially have an error is
put in a try clause.

 The program execution moves


to the start of a following
except clause if an error
happens.

 After running that code in


except, the execution
continues as normal.
A SHORT PROGRAM: GUESS THE NUMBER
Output: Run1 Output: Run2
POINTS TO PONDER 
Function LOCAL SCOPE
CONTD ….
GLOBAL SCOPE

Naming variables
CONTD ….
Global Keyword
Program to print Collatz
Sequence
More example programs on functions
Example

Output:
2
4
Example of a recursive function

Output:
The factorial of 3 is
6
Using Global and Local variables in the
same code

Output:
global global
local
Global variable and Local variable with
same name

Output:
local x: 10
global x: 5

You might also like