SlideShare a Scribd company logo
INTRODUCTION
TO
PYTHON
PROGRAMMING
-By
Ziyauddin Shaik
Btech (CSE)
(PART - 2)
Contents
• Control flow statements
• Recursion
• Infinite recursion
• keyboard input
• output formatting
• incremental development
• composition
• leap of faith
• checking types
• turtle
CONTROLFLOW STATEMENTS ( if, if-else,if-elif-else) :
Decision making is the most important aspect of almost all the programming languages.
 As the name implies, decision making allows us to run a particular block of code for a particular
decision.
Here, the decisions are made on the validity of the particular conditions. Condition checking is
the backbone of decision making.
Decision making statements in programming languages decides the direction of flow of program
execution.
 decision making statements are: 1.if or simple if statement
2. if-else statement
3. elif statement
4. Nested if statement
1. if or simple if statement:
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block.
 The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.
syntax :
if expression:
statement
Example 1
num = int(input("enter
the number:"))
if num%2 == 0:
print("Number is
even")
Output:
enter the number:10
Number is even
2. if-else statement :
The if-else statement provides an else block combined with the if
statement which is executed in the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the
else-block is executed.
Syntax:
if expression:
True block statements
else:
False block
statements
Example :
age = int (input("Enter your age: "))
if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")
Output:
Enter your age: 90
You are eligible to vote !!
3. elif statement
 The elif statement works like an if-else-if ladder statement in C. It must
be succeeded by an if statement.
Syntax:
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1:
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");
Output:
Enter the number:15
number is not equal to 10, 50 or 100
4. Nested if statements :
Nested if statements means an if statement inside another if statement.
Syntax:
if (condition1):
# condition1 is true
if (condition2):
# condition2 is true
# if Block is end here
# if Block is end here
Program:
i = 10
if (i == 10):
if (i < 15):
print ("i is smaller than 15")
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
Recursion:
A Function call itself again and
again is called recursion.
Ex:
def add():
……
add()
add()
Example
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
num = 3
print("The factorial
of",num,"is",factorial(num))
Output:
The factorial of 3 is 6
Infinite Recursion
Every recursive function must
have a base condition that stops
the recursion or else the function
calls itself infinitely.
The Python interpreter limits the
depths of recursion to help avoid
infinite recursions, resulting in
stack overflows.
By default, the maximum depth of
recursion is 1000. If the limit is
crossed, it results
in RecursionError.
EX:
def recursor():
recursor()
recursor()
Output
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth
exceeded
Advantages of Recursion
1.Recursive functions make the code look clean and elegant.
2.A complex task can be broken down into simpler sub-problems using
recursion.
3.Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of Recursion
1.Sometimes the logic behind recursion is hard to follow through.
2.Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
3.Recursive functions are hard to debug.
Keyboard input
Input :
Python input() function is used to get input from the user.
 It prompts for the user input and reads a line.
 After reading data, it converts it into a string and returns that.
 It throws an error EOFError if EOF(End Of File) is read.
Syntax:
Input([prompt])
prompt: It is a string message which prompts for the user input.
It returns user input after converting into a string
Example :
a = input("Enter a value: ")
print("You entered:",a)
Output:
Enter a value: 45
You entered: 45
here you should enter a
value through keyboard
Example :
a = input("Enter an integer: ")
val = int(a)
b = (val*val)
print("Multiplication of the value:",b)
Output:
Enter an integer: 12
Multiplication of the value: 144
Output function :
Print():
Python print () function prints the given output on the screen.
Syntax: print (object(s), sep=separator, end=end, file=file, flush=flush)
Example :
print(“Hi Selena ”)
Output:
Hi Selena
Example :
a=5
print(“The value of a is:”,a)
Output:
The value of a is:5
Example :
a,b=10,20
print(“The sum of a ,b is:”,a+b)
Output:
The sum of a , b is:30
We can also Use ‘+’ and ‘,’ operators in print():
+ adding two strings
, provide space between two strings
Example :
print(“Hi”+”Selena”)
Output
Hi Selena
Example :
print(“Hi”,”Selena”)
Output
Hi Selena
Output formatting
Sometimes we would like to format our output to make it look attractive.
 This can be done by using the str.format() method.
This method is visible to any string object.
Ex: x = 5; y = 10
print(“The value of x is {} and y is {}”. format(x,y))
OUTPUT: The value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order
in which it is printed by using numbers (tuple index).
Example 1 : 0 1
print(' Selena is {0} and {1}'.format('cute','pretty'))
Output:
Selena is cute and pretty
Example 2 : 0 1
print(' Selena is {1} and {0}'.format('cute','pretty'))
Output:
Selena is pretty and cute
Fruitful Functions:
These are the functions that return a value after their completion.
 A fruitful function must always return a value to where it is called from.
A fruitful function can return any type of value may it be string, integer, boolean, etc.
 It is not necessary for a fruitful function to return the value of one variable, the value
to be returned can be an array or a vector.
 A fruitful function can also return multiple values.
Ex:
function add_f(a, b);
c = a + b;
return c;
d = add_f(3, 4);
print(d)
Output :
7
Incremental development
As you write larger functions, you might find yourself spending more time
debugging.
To deal with increasingly complex programs, you might want to try a process
called incremental development.
The goal of incremental development is to avoid long debugging sessions by
adding and testing only a small amount of code at a time.
Ex : suppose you want to find the distance between two points, given by the
coordinates (x1, y1) and (x2, y2). By the Pythagorean theorem, the distance is:
distance = (x2 − x1)2 + (y2 − y1) 2
The first step is to consider what a distance function should look like in Python.
In other words, what are the inputs (parameters) and what is the output (return
value)?
In this case, the two points are the inputs, which we can represent using four
parameters. The return value is the distance, which Is a floating-point value.
Immediately you can write an outline of the function:
def distance(x1, y1, x2, y2):
return 0.0
Obviously, this version doesn’t compute distances; it always returns zero. But it is
syntactically correct, and it runs which means that we can test it before we make it
more complicated.
To test the new function, we call it with sample values:
 >>> distance(1, 2, 4, 6)
OUTPUT:0.0
We chose these values so that the horizontal distance equals 3 and the vertical
distance equals 4; that way, the result is 5 (the hypotenuse of a 3-4-5 triangle).
When testing a function, it is useful to know the right answer.
At this point we have confirmed that the function is syntactically correct, and
we can start adding lines of code. After each incremental change, we test the
function again.
If an error occurs at any point, we know where it must be in the last line we
added.
A logical first step in the computation is to find the differences x2- x1 and y2-
y1. We will refer to those values using temporary variables named dx and dy.
1.def distance(x1, y1, x2, y2):
2. dx = x2 - x1
3. dy = y2 - y1
4. return 0.0
If we call the function with the arguments shown above, when the flow of
execution gets to the return statement, dx should be 3 and dy should be
Next we compute the sum of squares of dx and dy:
1.def distance(x1, y1, x2, y2):
2. dx = x2 - x1
3. dy = y2 - y1
4. dsquared = dx*dx + dy*dy
5. return 0.0
Again, we could run the program at this stage and check the value of dsquared (which
should be 25).
Finally, using the fractional exponent 0.5 to find the square root, we compute and
return the result:
1.def distance(x1, y1, x2, y2):
2. dx = x2 - x1
3. dy = y2 - y1
4. dsquared = dx*dx + dy*dy
5. result = dsquared**0.5
6. return result
If that works correctly, you are done.
Composition
you can call one function from within another. This ability is
called composition.
Example: we’ll write a function that takes two points, the center of the circle
and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp.
 The first step is to find the radius of the circle, which is the distance between
the two points.
 Fortunately, we’ve just written a function, distance, that does just that, so now
all we have to do is use it:
1. radius = distance(xc, yc, xp, yp)
The second step is to find the area of a circle with that radius and return it.
Again we will use one of our earlier functions:
1 .result = area(radius)
2. return result
Wrapping that up in a function, we get:
1.def area2(xc, yc, xp, yp):
2. radius = distance(xc, yc, xp, yp)
3. result = area(radius)
4. return result
We called this function area2 to distinguish it from the area function defined
earlier.
The temporary variables radius and result are useful for development, debugging,
and single-stepping through the code to inspect what is happening, but once the
program is working, we can make it more concise by composing the function calls:
1. def area2(xc, yc, xp, yp):
2. return area(distance(xc, yc, xp, yp))
Leap Of Faith
Following the flow of execution is one way to read programs, but it can
quickly become overwhelming.
 An alternative is what I call the “leap of faith”.
When you come to a function call, instead of following the flow of execution,
you assume that the function works correctly and returns the right result.
 In fact, you are already practicing this leap of faith when you use built-in
functions.
.When you call math.cos or math.exp, you don’t examine the bodies of those
functions.
You just assume that they work because the people who wrote the built-in
functions were good programmers.
The same is true when you call one of your own functions.
For example above we wrote a function called is_divisible that determines
whether one number is divisible by another.
Once we have convinced ourselves that this function is correct—by
examining the code and testing—we can use the function without looking at
the body again.
The same is true of recursive programs.
Checking types
What happens if we call factorial and give it 1.5 as an argument?
>>> factorial(1.5)
RuntimeError: Maximum recursion depth exceeded
It looks like an infinite recursion. But how can that be? There is a base
case—when n == 0.
But if n is not an integer, we can miss the base case and recurse forever.
In the first recursive call, the value of n is 0.5.
 In the next, it is -0.5. From there, it gets smaller (more negative), but it
will never be 0.
We have two choices. We can try
to generalize the factorial function
to work with floating-point
numbers, or we can make factorial
check the type of its argument.
The first option is called the
gamma function and it’s a little
beyond the scope of this book. So
we’ll go for the second.
We can use the built-in function
isinstance to verify the type of the
argument. While we’re at it, we can
also make sure the argument is
positive:
Program :
def factorial(n):
if not isinstance(n, int):
print('Factorial is only defined for integers.')
return None
elif n < 0:
print('Factorial is not defined for negative integers.')
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)
The first base case handles nonintegers.
the second handles negative integers.
In both cases, the program prints an error message and returns None to
indicate that something went wrong:
 >>> print(factorial('fred'))
OUTPUT: Factorial is only defined for integers. None
>>> print(factorial(-2))
OUTPUT: Factorial is not defined for negative integers. None
Turtle :
Turtle is a special feathers of Python. Using Turtle, we can easily draw in a
drawing board.
First we import the turtle module.
Then create a window.
Next we create turtle object and using turtle method we can draw in the
drawing board.
NAME PARAMETER DESCRIPTION
1.Turtle() None It creates and returns a
new turtle Object
2.forward() amount It moves the turtle forward by the
specified amount
3.backward() amount It moves the turtle backward by the
specified amount
4.right() angle It turns the turtle clockwise
5.left() angle It turns the turtle counter clockwise
6.penup() None It picks up the turtle’s Pen
7.pendown() None Puts down the turtle’s Pen
8.up() None Picks up the turtle’s Pen
9.down() None Puts down the turtle's Pen
10.color() Color name Changes the color of the turtle’s pen
NAME PARAMETER DESCRIPTION
11.fillcolor() Color name Changes the color of the turtle will
use to fill a polygon
12.heading() None It returns the current heading
13.position() None It returns the current position
14.goto() x, y It moves the turtle to position x,y
15.begin_fill() None Remember the starting point for a
filled polygon
16.end_fill() None It closes the polygon and fills with the
current fill color
17.dot() None Leaves the dot at the current position
18stamp() None Leaves an impression of a turtle shape
at the current location
19.shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or
‘circle’
The turtle module
The turtle Module provided by python software, it provide all turtle
methods to perform operations on turtle.
To check whether you have the turtle module, open the Python
interpreter and type
>>> import turtle
>>> bob = turtle.Turtle()
When you run this code, it should create a new window with small
arrow that represents the turtle.
To make use of the turtle methods and functionalities, we need to
import turtle.
for executing a turtle program follows 4 steps:
1.Import the turtle module
2.Create a turtle to control.
3.Draw around using the turtle methods.
4.Run turtle.done().
1.Import the turtle module:
before we can use turtle, we need to import it. We import it as :
1.from turtle import *
( or)
2. import turtle
After importing the turtle library and making all the turtle functionalities available to
us
2. Create a turtle to control:
we need to create a turtle.
The turtle module (with a lowercase ’t’) provides a function called Turtle (with an
uppercase ’T’) that creates a Turtle object, which we assign to a variable named skk.
skk = turtle.Turtle()
# THANK YOU

More Related Content

Similar to Introduction to python programming ( part-2 ) (20)

Reliable and Concurrent Software - Erlang
Reliable and Concurrent Software - ErlangReliable and Concurrent Software - Erlang
Reliable and Concurrent Software - Erlang
ssuser2637a1
 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Working with functions.pptx. Hb.
Working with functions.pptx.          Hb.Working with functions.pptx.          Hb.
Working with functions.pptx. Hb.
sabarivelan111007
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
Abdul Haseeb
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
AKANSHAMITTAL2K21AFI
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Rakotoarison Louis Frederick
 
TN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptxTN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptx
knmschool
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
RohitSindhu10
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
AkashdeepBhattacharj1
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
Panimalar Engineering College
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
Sudharsan S
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
Praveen M Jigajinni
 
Lecture 2 java.pdf
Lecture 2 java.pdfLecture 2 java.pdf
Lecture 2 java.pdf
SantoshSurwade2
 
Reliable and Concurrent Software - Erlang
Reliable and Concurrent Software - ErlangReliable and Concurrent Software - Erlang
Reliable and Concurrent Software - Erlang
ssuser2637a1
 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Working with functions.pptx. Hb.
Working with functions.pptx.          Hb.Working with functions.pptx.          Hb.
Working with functions.pptx. Hb.
sabarivelan111007
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
Abdul Haseeb
 
TN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptxTN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptx
knmschool
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 

More from Ziyauddin Shaik (6)

Operating Systems
Operating Systems Operating Systems
Operating Systems
Ziyauddin Shaik
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems
Ziyauddin Shaik
 
Introduction to python programming ( part-1)
Introduction to python programming  ( part-1)Introduction to python programming  ( part-1)
Introduction to python programming ( part-1)
Ziyauddin Shaik
 
Product Design
Product Design Product Design
Product Design
Ziyauddin Shaik
 
Capsule Endoscopy
Capsule Endoscopy Capsule Endoscopy
Capsule Endoscopy
Ziyauddin Shaik
 
Amazon Go : The future of shopping
Amazon Go : The future of shopping Amazon Go : The future of shopping
Amazon Go : The future of shopping
Ziyauddin Shaik
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems
Ziyauddin Shaik
 
Introduction to python programming ( part-1)
Introduction to python programming  ( part-1)Introduction to python programming  ( part-1)
Introduction to python programming ( part-1)
Ziyauddin Shaik
 
Amazon Go : The future of shopping
Amazon Go : The future of shopping Amazon Go : The future of shopping
Amazon Go : The future of shopping
Ziyauddin Shaik
 
Ad

Recently uploaded (20)

Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Ad

Introduction to python programming ( part-2 )

  • 2. Contents • Control flow statements • Recursion • Infinite recursion • keyboard input • output formatting • incremental development • composition • leap of faith • checking types • turtle
  • 3. CONTROLFLOW STATEMENTS ( if, if-else,if-elif-else) : Decision making is the most important aspect of almost all the programming languages.  As the name implies, decision making allows us to run a particular block of code for a particular decision. Here, the decisions are made on the validity of the particular conditions. Condition checking is the backbone of decision making. Decision making statements in programming languages decides the direction of flow of program execution.  decision making statements are: 1.if or simple if statement 2. if-else statement 3. elif statement 4. Nested if statement
  • 4. 1. if or simple if statement: The if statement is used to test a particular condition and if the condition is true, it executes a block of code known as if-block.  The condition of if statement can be any valid logical expression which can be either evaluated to true or false. syntax : if expression: statement Example 1 num = int(input("enter the number:")) if num%2 == 0: print("Number is even") Output: enter the number:10 Number is even
  • 5. 2. if-else statement : The if-else statement provides an else block combined with the if statement which is executed in the false case of the condition. If the condition is true, then the if-block is executed. Otherwise, the else-block is executed. Syntax: if expression: True block statements else: False block statements Example : age = int (input("Enter your age: ")) if age>=18: print("You are eligible to vote !!") else: print("Sorry! you have to wait !!") Output: Enter your age: 90 You are eligible to vote !!
  • 6. 3. elif statement  The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement. Syntax: if expression 1: # block of statements elif expression 2: # block of statements elif expression 3: # block of statements else: # block of statements Example 1: 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"); Output: Enter the number:15 number is not equal to 10, 50 or 100
  • 7. 4. Nested if statements : Nested if statements means an if statement inside another if statement. Syntax: if (condition1): # condition1 is true if (condition2): # condition2 is true # if Block is end here # if Block is end here Program: i = 10 if (i == 10): if (i < 15): print ("i is smaller than 15") if (i < 12): print ("i is smaller than 12 too") else: print ("i is greater than 15") Output: i is smaller than 15 i is smaller than 12 too
  • 8. Recursion: A Function call itself again and again is called recursion. Ex: def add(): …… add() add() Example def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) num = 3 print("The factorial of",num,"is",factorial(num)) Output: The factorial of 3 is 6
  • 9. Infinite Recursion Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely. The Python interpreter limits the depths of recursion to help avoid infinite recursions, resulting in stack overflows. By default, the maximum depth of recursion is 1000. If the limit is crossed, it results in RecursionError. EX: def recursor(): recursor() recursor() Output Traceback (most recent call last): File "<string>", line 3, in <module> File "<string>", line 2, in a File "<string>", line 2, in a File "<string>", line 2, in a [Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded
  • 10. Advantages of Recursion 1.Recursive functions make the code look clean and elegant. 2.A complex task can be broken down into simpler sub-problems using recursion. 3.Sequence generation is easier with recursion than using some nested iteration. Disadvantages of Recursion 1.Sometimes the logic behind recursion is hard to follow through. 2.Recursive calls are expensive (inefficient) as they take up a lot of memory and time. 3.Recursive functions are hard to debug.
  • 11. Keyboard input Input : Python input() function is used to get input from the user.  It prompts for the user input and reads a line.  After reading data, it converts it into a string and returns that.  It throws an error EOFError if EOF(End Of File) is read. Syntax: Input([prompt]) prompt: It is a string message which prompts for the user input. It returns user input after converting into a string
  • 12. Example : a = input("Enter a value: ") print("You entered:",a) Output: Enter a value: 45 You entered: 45 here you should enter a value through keyboard Example : a = input("Enter an integer: ") val = int(a) b = (val*val) print("Multiplication of the value:",b) Output: Enter an integer: 12 Multiplication of the value: 144
  • 13. Output function : Print(): Python print () function prints the given output on the screen. Syntax: print (object(s), sep=separator, end=end, file=file, flush=flush) Example : print(“Hi Selena ”) Output: Hi Selena Example : a=5 print(“The value of a is:”,a) Output: The value of a is:5 Example : a,b=10,20 print(“The sum of a ,b is:”,a+b) Output: The sum of a , b is:30
  • 14. We can also Use ‘+’ and ‘,’ operators in print(): + adding two strings , provide space between two strings Example : print(“Hi”+”Selena”) Output Hi Selena Example : print(“Hi”,”Selena”) Output Hi Selena
  • 15. Output formatting Sometimes we would like to format our output to make it look attractive.  This can be done by using the str.format() method. This method is visible to any string object. Ex: x = 5; y = 10 print(“The value of x is {} and y is {}”. format(x,y)) OUTPUT: The value of x is 5 and y is 10 Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by using numbers (tuple index).
  • 16. Example 1 : 0 1 print(' Selena is {0} and {1}'.format('cute','pretty')) Output: Selena is cute and pretty Example 2 : 0 1 print(' Selena is {1} and {0}'.format('cute','pretty')) Output: Selena is pretty and cute
  • 17. Fruitful Functions: These are the functions that return a value after their completion.  A fruitful function must always return a value to where it is called from. A fruitful function can return any type of value may it be string, integer, boolean, etc.  It is not necessary for a fruitful function to return the value of one variable, the value to be returned can be an array or a vector.  A fruitful function can also return multiple values. Ex: function add_f(a, b); c = a + b; return c; d = add_f(3, 4); print(d) Output : 7
  • 18. Incremental development As you write larger functions, you might find yourself spending more time debugging. To deal with increasingly complex programs, you might want to try a process called incremental development. The goal of incremental development is to avoid long debugging sessions by adding and testing only a small amount of code at a time. Ex : suppose you want to find the distance between two points, given by the coordinates (x1, y1) and (x2, y2). By the Pythagorean theorem, the distance is: distance = (x2 − x1)2 + (y2 − y1) 2 The first step is to consider what a distance function should look like in Python. In other words, what are the inputs (parameters) and what is the output (return value)?
  • 19. In this case, the two points are the inputs, which we can represent using four parameters. The return value is the distance, which Is a floating-point value. Immediately you can write an outline of the function: def distance(x1, y1, x2, y2): return 0.0 Obviously, this version doesn’t compute distances; it always returns zero. But it is syntactically correct, and it runs which means that we can test it before we make it more complicated. To test the new function, we call it with sample values:  >>> distance(1, 2, 4, 6) OUTPUT:0.0 We chose these values so that the horizontal distance equals 3 and the vertical distance equals 4; that way, the result is 5 (the hypotenuse of a 3-4-5 triangle). When testing a function, it is useful to know the right answer.
  • 20. At this point we have confirmed that the function is syntactically correct, and we can start adding lines of code. After each incremental change, we test the function again. If an error occurs at any point, we know where it must be in the last line we added. A logical first step in the computation is to find the differences x2- x1 and y2- y1. We will refer to those values using temporary variables named dx and dy. 1.def distance(x1, y1, x2, y2): 2. dx = x2 - x1 3. dy = y2 - y1 4. return 0.0 If we call the function with the arguments shown above, when the flow of execution gets to the return statement, dx should be 3 and dy should be Next we compute the sum of squares of dx and dy:
  • 21. 1.def distance(x1, y1, x2, y2): 2. dx = x2 - x1 3. dy = y2 - y1 4. dsquared = dx*dx + dy*dy 5. return 0.0 Again, we could run the program at this stage and check the value of dsquared (which should be 25). Finally, using the fractional exponent 0.5 to find the square root, we compute and return the result: 1.def distance(x1, y1, x2, y2): 2. dx = x2 - x1 3. dy = y2 - y1 4. dsquared = dx*dx + dy*dy 5. result = dsquared**0.5 6. return result If that works correctly, you are done.
  • 22. Composition you can call one function from within another. This ability is called composition. Example: we’ll write a function that takes two points, the center of the circle and a point on the perimeter, and computes the area of the circle. Assume that the center point is stored in the variables xc and yc, and the perimeter point is in xp and yp.  The first step is to find the radius of the circle, which is the distance between the two points.  Fortunately, we’ve just written a function, distance, that does just that, so now all we have to do is use it: 1. radius = distance(xc, yc, xp, yp)
  • 23. The second step is to find the area of a circle with that radius and return it. Again we will use one of our earlier functions: 1 .result = area(radius) 2. return result Wrapping that up in a function, we get: 1.def area2(xc, yc, xp, yp): 2. radius = distance(xc, yc, xp, yp) 3. result = area(radius) 4. return result We called this function area2 to distinguish it from the area function defined earlier.
  • 24. The temporary variables radius and result are useful for development, debugging, and single-stepping through the code to inspect what is happening, but once the program is working, we can make it more concise by composing the function calls: 1. def area2(xc, yc, xp, yp): 2. return area(distance(xc, yc, xp, yp))
  • 25. Leap Of Faith Following the flow of execution is one way to read programs, but it can quickly become overwhelming.  An alternative is what I call the “leap of faith”. When you come to a function call, instead of following the flow of execution, you assume that the function works correctly and returns the right result.  In fact, you are already practicing this leap of faith when you use built-in functions. .When you call math.cos or math.exp, you don’t examine the bodies of those functions. You just assume that they work because the people who wrote the built-in functions were good programmers.
  • 26. The same is true when you call one of your own functions. For example above we wrote a function called is_divisible that determines whether one number is divisible by another. Once we have convinced ourselves that this function is correct—by examining the code and testing—we can use the function without looking at the body again. The same is true of recursive programs.
  • 27. Checking types What happens if we call factorial and give it 1.5 as an argument? >>> factorial(1.5) RuntimeError: Maximum recursion depth exceeded It looks like an infinite recursion. But how can that be? There is a base case—when n == 0. But if n is not an integer, we can miss the base case and recurse forever. In the first recursive call, the value of n is 0.5.  In the next, it is -0.5. From there, it gets smaller (more negative), but it will never be 0.
  • 28. We have two choices. We can try to generalize the factorial function to work with floating-point numbers, or we can make factorial check the type of its argument. The first option is called the gamma function and it’s a little beyond the scope of this book. So we’ll go for the second. We can use the built-in function isinstance to verify the type of the argument. While we’re at it, we can also make sure the argument is positive: Program : def factorial(n): if not isinstance(n, int): print('Factorial is only defined for integers.') return None elif n < 0: print('Factorial is not defined for negative integers.') return None elif n == 0: return 1 else: return n * factorial(n-1)
  • 29. The first base case handles nonintegers. the second handles negative integers. In both cases, the program prints an error message and returns None to indicate that something went wrong:  >>> print(factorial('fred')) OUTPUT: Factorial is only defined for integers. None >>> print(factorial(-2)) OUTPUT: Factorial is not defined for negative integers. None
  • 30. Turtle : Turtle is a special feathers of Python. Using Turtle, we can easily draw in a drawing board. First we import the turtle module. Then create a window. Next we create turtle object and using turtle method we can draw in the drawing board.
  • 31. NAME PARAMETER DESCRIPTION 1.Turtle() None It creates and returns a new turtle Object 2.forward() amount It moves the turtle forward by the specified amount 3.backward() amount It moves the turtle backward by the specified amount 4.right() angle It turns the turtle clockwise 5.left() angle It turns the turtle counter clockwise 6.penup() None It picks up the turtle’s Pen 7.pendown() None Puts down the turtle’s Pen 8.up() None Picks up the turtle’s Pen 9.down() None Puts down the turtle's Pen 10.color() Color name Changes the color of the turtle’s pen
  • 32. NAME PARAMETER DESCRIPTION 11.fillcolor() Color name Changes the color of the turtle will use to fill a polygon 12.heading() None It returns the current heading 13.position() None It returns the current position 14.goto() x, y It moves the turtle to position x,y 15.begin_fill() None Remember the starting point for a filled polygon 16.end_fill() None It closes the polygon and fills with the current fill color 17.dot() None Leaves the dot at the current position 18stamp() None Leaves an impression of a turtle shape at the current location 19.shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’
  • 33. The turtle module The turtle Module provided by python software, it provide all turtle methods to perform operations on turtle. To check whether you have the turtle module, open the Python interpreter and type >>> import turtle >>> bob = turtle.Turtle() When you run this code, it should create a new window with small arrow that represents the turtle. To make use of the turtle methods and functionalities, we need to import turtle. for executing a turtle program follows 4 steps:
  • 34. 1.Import the turtle module 2.Create a turtle to control. 3.Draw around using the turtle methods. 4.Run turtle.done().
  • 35. 1.Import the turtle module: before we can use turtle, we need to import it. We import it as : 1.from turtle import * ( or) 2. import turtle After importing the turtle library and making all the turtle functionalities available to us 2. Create a turtle to control: we need to create a turtle. The turtle module (with a lowercase ’t’) provides a function called Turtle (with an uppercase ’T’) that creates a Turtle object, which we assign to a variable named skk. skk = turtle.Turtle()