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

MODULE1

Uploaded by

Zeel Goyani
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)
26 views

MODULE1

Uploaded by

Zeel Goyani
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/ 71

A.D.

PATEL INSTITUTE OF TECHNOLOGY


(A Constituent College of CVM University)

Subject: Programming with Python


(102044504)

Prepared By
Prof. Sherin Mariam Jijo
Prof. Nikesha Patel
IT Department
1.Introduction to Python
• Data types, Keywords, Identifiers
• Variables, Comments, Operators
• Simple Input and Output
• Branching, Control structures
• Iterations, break, continue
• Functions, Recursion
WHY PYTHON IS IMPORTANT?
1) Python is an easy to learn, powerful programming language.
2) It has efficient high-level data structures and a simple but
effective approach to object-oriented programming.
3) Python’s elegant syntax and dynamic typing, together with its
interpreted nature, make it an ideal language for scripting and
rapid application development in many areas on most
platforms.
4) The Python interpreter and the extensive standard library are
freely available in source .
Continue…
5) It’s Powerful due to
i. Dynamic typing
ii. Built-in types and tools
iii. Library utilities
iv. Third party utilities (e.g. Numeric, NumPy, sciPy)
v. Automatic memory management
6) Used heavily in Datascience, Machine Learning and Scientific
Learning (Scikit learn, pandas, numpy etc)
7) Plenty of job opportunities (Google, Facebook, You tube etc)
HISTORY OF PYTHON
• Invented in the Netherlands, early 90s by Guido van Rossum
• Named after Monty Python
• Open sourced from the beginning
• Considered a scripting language, but is much more
• Scalable, object oriented and functional from the beginning
• Used by Google from the beginning
• Increasingly popular
Python’s Benevolent Dictator For Life
• “Python is an experiment in how much freedom programmers
need. Too much freedom and nobody can read another's code;
too little and expressive-ness is endangered.”
• - Guido van Rossum
Understanding code
• Indentation matters to meaning the code
• Block structure indicated by indentation
• The first assignment to a variable creates it
• Dynamic typing: no declarations, names don’t have types, objects do
• Assignment uses = and comparison uses ==
• For numbers + - * / % are as expected.
• Use of + for string concatenation.
• Use of % for string formatting (like printf in C)
• Logical operators are words (and,or,not) not symbols
• The basic printing command is print
Whitespace
Whitespace is meaningful in Python, especially indentation and
placement of newlines
∙Use a newline to end a line of code
Use \ when must go to next line prematurely
∙No braces {} to mark blocks of code, use consistent indentation
instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
∙Colons start of a new block in many constructs, e.g. function
definitions, then clauses
Comments
• Start comments with #, rest of line is ignored
• Can include a “documentation string” as the first line of a new
function or class you define
• Development environments, debugger, and other tools use it:
it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive integer and
returns facorial of n.”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)
Naming Rules
• Names are case sensitive and cannot start with a number.
They can contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
• Keywords
and, assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if,
import, in, is, lambda, not, or, pass, print, raise,
return, try, while
Data types
Integers
• Integers are whole numbers. They have no fractional parts.
• Integers can be positive or negative.
• There are two types of integers in Python:
• i) Integers(Signed) : It is the normal integer representation of
• whole numbers using the digits 0 to 9. Python provides
• single int data type to store any integer whether big or small.
• It is signed representation i.e. it can be positive or negative.
• ii) Boolean : These represent the truth values True and False. It
• is a subtype of integers and Boolean values True and False
• corresponds to values 1 and 0 respectively
Demonstration of Integer Data Type
#Demonstration of Integer-Addition of two integer number
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
sum=a+b
print("The sum of two integers=",sum)
Output:
• Enter the value of a: 45
• Enter the value of b: 67
• The sum of two integers= 112
Floating point
• A number having fractional part is a floating point number.
• It has a decimal point. It is written in two forms :
• i) Fractional Form : Normal decimal notation e.g. 675.456
• ii) Exponent Notation: It has mantissa and exponent.
• e.g. 6.75456E2
• Advantage of Floating point numbers:
• They can represent values between the integers.
• They can represent a much greater range of values.
• Disadvantage of Floating point numbers:
• Floating-point operations are usually slower than integer operations.
#Demonstration of Float Number- Calculate Simple
Interest

princ=float(input("Enter the Principal Amount:"))


rate=float(input("Enter the Rate of interest:"))
time=float(input("Enter the Time period:"))
si=(princ*rate*time)/100
print("The Simple Interest=",si)
• Output:
Enter the Principal Amount:5000
Enter the Rate of interest:8.5
Enter the Time period:5.5
Simple Interest= 2337.5
Complex numbers
• Python represents complex numbers in the form a+bj.
• #Demonstration of Complex Number- Sum of two Complex Numbers
a=7+8j
b=3.1+6j
c=a+b
print("Sum of two Complex Numbers")
print(a,"+",b,"=",c)
• Output:
(7+8j) + (3.1+6j) = (10.1+14j)
Strings
• A String is a group of valid characters enclosed in Single or
• Double quotation marks.
• A string can group any type of known characters i.e. letters ,numbers and
special characters.
• A Python string is a sequence of characters and each character
can be accessed by its index either by forward indexing or by
backward indexing.
• e.g. subj=“Computer”
Demonstration of String Data Type
• #Demonstration of String- To input string & print it
my_name=input("What is your Name? :")
print("Greetings!!!")
print("Hello!",my_name)
print("How do you do?")
• Output :
What is your Name? :Ananya Inkane
Greetings!!!
Hello! Ananya Inkane
How do you do?
List
• The List is Python’s compound data type. A List in Python
• represents a list of comma separated values of any data type
• between square brackets. Lists are Mutable.
#Demonstration of List- Program to input 2 list & join it
List1=eval(input("Enter Elements for List 1:"))
List2=eval(input("Enter Elements for List 2:"))
List=List1+List2
print("List 1 :",List1)
print("List 2 :",List2)
print("Joined List :",List)
• Output:
Enter Elements for List 1:12,'vv',34
Enter Elements for List 2:'adff',4,5.6
List 1 : (12, 'vv', 34)
List 2 : ('adff', 4, 5.6)
Joined List : (12, 'vv', 34, 'adff', 4, 5.6)
Dictionary
• Dictionaries are unordered collection of elements in curly braces in the form of
a key:value pairs that associate keys to values.
• Dictionaries are Mutable.
• As dictionary elements does not have index value ,the elements are accessed
• through the keys defined in key:value pairs.
#Demonstration of Dictionary- Program to save Phone nos. in dictionary &
print it
Phonedict={'Madhav':9876567843,'Dilpreet':7650983457,'Murugan':9067208769,
‘Abhinav':9870987067}
print(Phonedict)
• Output:
{'Madhav': 9876567843, 'Dilpreet': 7650983457, 'Murugan': 9067208769,'Abhinav’:
9870987067}
Operators
• Python language supports the following types of operators.
1. Arithmetic Operators
2. Comparison(i.e., Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Python Arithmetic Operators:
Python Comparison Operators:
Python Assignment Operators:
Python Bitwise Operators:
Python Logical Operators:
Python Membership Operators:
• In addition to the operators discussed previously, Python has
membership operators, which test for membership
• in a sequence, such as string s, lists, or tuples. There are two
membership operators explained below:
Python Identity Operators:
Python Operators Precedence
Conditional Statements
• In daily routine
• If it is very hot, I will skip exercise.
• If there is a quiz tomorrow, I will first study and then sleep.
Otherwise I will sleep now.
• If I have to buy coffee, I will go left. Else I will go straight.
if-else statement
• Compare two integers and print the min.

if x < y:
1. Check if x is less
print (x) than y.
else: 2. If so, print x
print (y) 3. Otherwise, print y.
print (‘is the minimum’)
if statement (no else!)
• General form of the if statement
if boolean-expr :
S1
S2
• Execution of if statement
• First the expression is evaluated.
• If it evaluates to a true value, then S1 is executed and then control
moves to the S2.
• If expression evaluates to false, then control moves to the S2 directly.
if-else statement
if boolean-expr :
S1
else:
S2
S3
• Execution of if-else statement
• First the expression is evaluated.
• If it evaluates to a true value, then S1 is executed and then control
moves to S3.
• If expression evaluates to false, then S2 is executed and then control
moves to S3.
• S1/S2 can be blocks of statements!
Nested if, if-else

if a <= b:
if a <= c:

else:

else:
if b <= c) :

else:

Elif
• A special kind of nesting is the chain of if-else-if-else-…
statements
• Can be written elegantly using if-elif-..-else
if cond1: if cond1:
s1 s1
else: elif cond2:
if cond2: s2
s2 elif cond3:
else: s3
if cond3: elif …
s3 else
else: last-block-of-stmt

ITERATION OR LOOPING
• What is loop or iteration?
• Loops can execute a block of code number of times until a
certain condition is met.
OR
• The iteration statement allows instructions to be executed until a
certain condition is to be fulfilled.
• The iteration statements are also called as loops or Looping
statements.
• Python provides two kinds of loops & they are,

while loop

For loop
While loop
• A while loop allows general repetition based upon the repeated
testing of a Boolean co
• The syntax for a while loop in Python is as follows:
while condition:
: Colon Must
body
• Where, loop body contain the single statement or set of
statements (compound statement) or an empty statement.
• The loop iterates while the expression evaluates to true, when
expression becomes false the loop terminates.
# Python Program to Print Natural Numbers from 1 to N

number = int(input("Please Enter Output:


any Number: ")) Please Enter any Number: 6
i=1 The List of Natural Numbers from
print("The List of Natural Numbers 1 to 6
from 1 to", number) 1
while ( i <= number): 2
print (i) 3
i=i+1 4
5
6
# Program to display the Fibonacci sequence up to n-th
term

nterms = int(input("How many terms? ")) # generate fibonacci sequence


# first two terms else:
n1, n2 = 0, 1 print("Fibonacci sequence:")
count = 0 while count < nterms:
# check if the number of terms is valid print(n1)
if nterms <= 0: nth = n1 + n2
print("Please enter a positive integer") # update values
# if there is only one term, return n1 n1 = n2
elif nterms == 1: n2 = nth
print("Fibonacci sequence count += 1
upto",nterms,":")
print(n1)
Output
How many terms? 5
Fibonacci sequence:
0
1
1
2
3
for LOOP

• Python’s for-loop syntax is a more convenient alternative to a


while loop when iterating through a series of elements.
• The for-loop syntax can be used on any type of iterable
structure, such as a list, tuple str, set, dict, or file
• Syntax or general format of for loop is,
for element in iterable:
body
# Natural Numbers generation

# Take number from user


num = int(input("Enter any number : "))
print("\n Natural numbers from 1 to", num)
for i in range(1, num + 1):
print(i, end=" ")
Output:
Enter any number : 5
Natural numbers from 1 to 5
12345
Programs
• # Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
for LOOP - range KEYWORD

• The range() function returns a sequence of numbers, starting


from 0 by default, and increments by 1 (by default), and ends at
a specified number.
range(start, stop, step)
for n in range(3,6):
print(n)
or
x = range(3, 6)
for n in x:
print(n)
else statement in loop

• else can be used in for and Output:


while loops the else body will T
be executed as and when the
loop’s conditional expression P
evaluates to false. Loop-else statement
for i in ['T','P']: successfully executed
print(i)
else: # Loop else statement
print("Loop-else statement
successfully executed")
BRANCHING OR JUMPING STATEMENTS
Python has an unconditional branching statements and they are,
1. break STATEMENT
• Break can be used to unconditionally jump out of the loop. It
terminates the execution of the loop.
• Break can be used in while loop and for loop. Break is mostly
required, when because of some external condition, we need to
exit from a loop.
# Use of break statement inside the loop

for val in "string": Output:


if val == "i": s
break t
print(val) r
print("The end") The end
2. continue STATEMENT
• The continue statement in Python returns the control to the
beginning of the while loop.
• The continue statement rejects all the remaining statements in
the current iteration of the loop and moves the control back to
the top of the loop.
• The continue statement can be used in both while and for loops.
# Program to show the use of continue statement
inside loops
for val in "string": Output:
if val == "i": s
continue t
print(val) r
n
print("The end") g
The end
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):
#program to demonstrate pass usage
li =['a', 'b', 'c', 'd'] Output:
for i in li: b
if(i =='a'): c
pass d
else:
print(i)
Difference Between break and continue
BASIS FOR COMPARISON BREAK CONTINUE
Task It terminates the execution of It terminates only the current
remaining iteration of the loop. iteration of the loop.

Control after break/continue 'break' resumes the control of 'continue' resumes the control of
the program to the end of loop the program to the next iteration
enclosing that 'break'. of that loop enclosing 'continue'.

Causes It causes early termination of It causes early execution of the


loop. next iteration.
Continuation 'break' stops the continuation of 'continue' do not stops the
loop. continuation of loop, it only
stops the current iteration.

Other uses 'break' can be used with 'continue' can not be executed
'switch', 'label'. with 'switch' and 'labels'.
FUNCTIONS
#Python program to add two numbers using
function

def add_num(a,b):#function for Output:


addition The sum is 80
sum=a+b;
return sum; #return value
num1=25 #variable declaration help(add_num)
num2=55 Help on function add_num in
print("The sum module __main__:
is",add_num(num1,num2))#call add_num(a, b)
the function
Keyword Arguments
•Call
def printName(first, last, initials) :
•Output Note use of [0]
•printName('Acads', 'Institute', False) to get the first
if initials:
•Acads Institute character of a
•printName('Acads', 'Institute', True)
print (first[0] + '. ' + last[0] + '.')
•A. I.
string. More on
•printName(last='Institute', initials=False, first='Acads') this later.
else:
•Acads Institute
•printName('Acads', initials=True, last='Institute')
print (first, last)
•A. I.
• Parameter passing where formal is bound to actual using
formal's name
• Can mix keyword and non-keyword arguments
• All non-keyword arguments precede keyword arguments in
the call
• Non-keyword arguments are matched by position (order is important)
• Order of keyword arguments is not important
Default Values
def printName(first, last, initials=False) :
if initials:
print (first[0] + '. ' + last[0] + '.')
else:
Call Output
print (first, last) printName('Acads', 'Institute') Acads
Institute
printName(first='Acads', last='Institute', A. I.
initials=True)
printName(last='Institute', first='Acads') Acads
Institute
printName('Acads', last='Institute') Acads
Institute
• Allows user to call a function with fewer arguments
• Useful when some argument has a fixed value for most of the
calls
• All arguments with default values must be at the end of
argument list
• non-default argument can not follow default argument
Globals
• Globals allow functions to communicate with each other
indirectly
• Without parameter passing/return value
• Convenient when two seemingly “far-apart” functions want to
share data
• No direct caller/callee relation
• If a function has to update a global, it must re-declare the global
variable with global keyword.
PI = 3.14 >>> print(area (100))
def perimeter(r): 31400.0
return 2 * PI * r >>> print(perimeter(10))
def area(r): 62.800000000000004
return PI * r * r >>> update_pi()
def update_pi(): >>> print(area(100))
global PI 31415.999999999996
PI = 3.14159 >>> print(perimeter(10))
62.832

defines PI to be of float type with value


3.14. PI can be used across functions. Any
change to PI in update_pi will be visible to
all due to the use of global.
Recursion
• The term Recursion can be defined as the process of defining
something in terms of itself. In simple words, it is a process in
which a function calls itself directly or indirectly.
#Program to print factorial of a number recursively.
# # Recursive function
def recursive_factorial(n): elif num == 0:
if n == 1: print("Factorial of number 0 is 1")
return n else:
else: print("Factorial of number", num,
return n * recursive_factorial(n-1) "=", recursive_factorial(num))
# user input
num = 6 Output:
# check if the input is valid or not Factorial of number 6 = 720
if num < 0:
print("Invalid input ! Please enter
a positive number.")
# Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1: Fibonacci sequence:
return n 0
else: 1
return(recur_fibo(n-1) + recur_fibo(n-2)) 1
nterms = 10 2
# check if the number of terms is valid 3
if nterms <= 0: 5
print("Plese enter a positive integer") 8
else: 13
print("Fibonacci sequence:") 21
for i in range(nterms): 34
print(recur_fibo(i))
Programs for practice
•Write a PYTHON program to evaluate the student performance
If % is >=90 then Excellent performance
If % is >=80 then Very Good performance
If % is >=70 then Good performance
If % is >=60 then average performance
else Poor performance.
•Write a PYTHON program to find largest of three numbers.
• Write a PYTHON program to check weather number is even or
odd.
• Write a PYTHON program to check a year for leap year.
• Write a PYTHON program to check the entered number is prime
or not
• Write a PYTHON program to find the sum of digits of given
number.
• Write a PYTHON program to check the entered number is
palindrome or not
• Write a PYTHON program to reverse the given number.
• Write a PYTHON program to print the multiplication table
• Write a PYTHON program to print the largest of n numbers
• Write a PYTHON program that prints 1 2 4 8 16 32 … n2
• Write a PYTHON program to sum the given sequence
1 + 1/ 1! + 1/ 2! + 1/3! + …. + 1/n!
• Write a PYTHON program to compute the cosine series
• cos(x) = 1 – x2 / 2! + x4 / 4! – x6 / 6! + … xn / n!
• Write a PYTHON program to produce following design
ABC
ABC
ABC
• Write a PYTHON program to produce following design
A
AB
ABC
ABCD
ABCDE
If user enters n value as 5
• Write a PYTHON program to produce following design
1
12
123
1234
12345
If user enters n value as 5

You might also like