0% found this document useful (0 votes)
16 views17 pages

3.note by kk

The document covers programming concepts in Python, focusing on control flow using conditions, if statements, loops, and functions. It explains the syntax and usage of if statements, if-else statements, for loops, while loops, and introduces functions, including defining and calling them. Additionally, it discusses variable scope, recursion, and string manipulation, providing examples for each concept.

Uploaded by

kiradij268
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)
16 views17 pages

3.note by kk

The document covers programming concepts in Python, focusing on control flow using conditions, if statements, loops, and functions. It explains the syntax and usage of if statements, if-else statements, for loops, while loops, and introduces functions, including defining and calling them. Additionally, it discusses variable scope, recursion, and string manipulation, providing examples for each concept.

Uploaded by

kiradij268
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/ 17

Subject: Programming for problem solving

Unit III: Control Flow, Function

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

• Equals: a == b
• Not Equals: a!= b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

The 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.

The syntax of the if-statement is given below.

if expression:
statement

Example

If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

Example
num = int(input("enter the number:"))
if num%2 == 0:
Print ("The Given number is an even number")

Example: Program to print the largest of the three numbers.


a = int (input("Enter a: "));
b = int (input("Enter b: "));
c = int (input("Enter c: "));
if a>b and a>c:
print ("From the above three numbers given a is largest");
if b>a and b>c:
print ("From the above three numbers given b is largest");
if c>a and c>b:
print ("From the above three numbers given c is largest");

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.
The syntax of the if-else statement is given below.

if condition:
#block of statements
else:
#another block of statements (else-block)

WAP to check the person is eligible for voting or not eligible


age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")

WAP to check the number is even or odd number


num = int(input("enter the number?"))

if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")

WAP to print the largest of the three numbers


a = int(input("Enter a? "))
b = int(input("Enter b? "))
c = int(input("Enter c? "))
if a>b and a>c:
print("a is largest")
if b>a and b>c:
print("b is largest")
if c>a and c>b:
print("c is largest")

or
WAP to print the largest of the three numbers
a = int(input("Enter a? "))
b = int(input("Enter b? "))
c = int(input("Enter c? "))
if a>b and a>c:
print("a is largest")
elif b>a and b>c:
print("b is largest")
else:
print("c is largest")

WAP for basic calculator


Here we create a basic function with name calc()
def calc(n):
s=0
p=1
a=int(input("first number"))
b=int(input("second number"))
if n==1:
s=a+b
print("sum",s)
elif n==2:
p=a*b
print("prod",p)
elif n==3:
s=a-b
print("diff",s)
else:
p=a/b
print("divide",p)
i=int(input("enter for calculation 1. add 2. product 3.subtract 4.divide"))
calc(i)
WAP to check entered character in vowel or not
ch = input("Enter a character: ")

if(ch == 'A' or ch == 'a' or ch == 'E' or ch == 'e' or ch == 'I' or


ch == 'i' or ch == 'O' or ch == 'o' or ch == 'U' or ch == 'u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")

Introduction to for Loop in Python

Python frequently uses the Loop to iterate over iterable objects like lists, tuples, and strings.
Crossing is the most common way of emphasizing across a series, for loops are used when a
section of code needs to be repeated a certain number of times. The for-circle is typically
utilized on an iterable item, for example, a rundown or the in-fabricated range capability. In
Python, the for Statement runs the code block each time it traverses a series of elements. On
the other hand, the "while" Loop is used when a condition needs to be verified after each
repetition or when a piece of code needs to be repeated indefinitely. The for Statement is
opposed to this Loop.

Syntax of for Loop


for value in sequence:
{loop body}

WAP to print the table of given number


list = [1,2,3,4,5,6,7,8,9,10]
n=5

for i in list:
c = n*i
print(c)

WAP to print Fibonacci Series using for loop


num = int(input("enter the number of elements you want in series:"))
n1 = 0
n2= 1
for i in range(1, n-1):
sum = n1+n2
c.append(d)
n1 = n2
n2= sum
print(sum)
Output:

enter the number of elements you want in series: 4


0
1
1
2

Write a Program to reverse a string

def reverse_string(str):
str1 = "" # Declaring empty string to store the reversed string
for i in str:
str1 = i + str1
return str1 # It will return the reverse string to the caller function

str = "PYTHON" # Given String


print("The original string is: ",str)
print("The reverse string is",reverse_string(str)) # Function call

Python While Loops

In coding, loops are designed to execute a specified code block repeatedly.

The Python while loop iteration of a code block is executed as long as the given Condition,
i.e., conditional expression, is true.

The syntax of the Python while loop. The syntax is given below -

Statement
while Condition:
Statement

The given condition, i.e., conditional_expression, is evaluated initially in the Python while
loop. Then, if the conditional expression gives a boolean value True, the while loop statements
are executed. The conditional expression is verified again when the complete code block is
executed. This procedure repeatedly occurs until the conditional expression returns the boolean
value False.

o The statements of the Python while loop are dictated by indentation.


o The code block begins when a statement is indented & ends with the very first
unindented statement.
o Any non-zero number in Python is interpreted as boolean True. False is interpreted as
None and 0.

Python for printing numbers from 1 to 10.

i=1
while i<=10:
print(i, end=' ')
i+=1
Output:

WAP to print Fibonacci Series using while loop


In this Python program, we have used the while loop to find the Fibonacci Series numbers
within that range.
num = int(input("Enter the Fibonacci Number Range: "))

n1 = 0
n2 = 1
Sum = 0
i=0

while(i < num):


print(n1, end = ' ')
Sum = Sum + n1
Next = n1 + n2
n1 = n2
n2 = Next
i=i+1

print("\nSum of Fibonacci Series Numbers: %d" %Sum)


Output of the above code:
Enter the Fibonacci Number Range: 12
0 1 1 2 3 5 8 13 21 34 55 89
Sum of Fibonacci Series Numbers: 232
Continue Statement
Continue statement is used to skip the remaining statements in the loop and to shift the
control back to the beginning of the loop. Continue statement can be used inside “for” as well
as “while” loop.
Syntax for Continue:
Continue

Example:
for i in range(1,11):
if(i%2) != 0:
continue
print(i)

Break Statement
Break statement is used to terminate the execution of a loop. Break statement can be used
inside “for” as well as “while” loops. Take a look at the following statement to see break
statement in action.
Syntax for break:
Break

for i in range(1,11):
if(i > 5):
break
print(i)

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 statement is a null operation; nothing 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.

Example:
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)

print ("Good bye!")

Functions in Python
If a program contains a large piece of code that must be run repeatedly, it is preferable to
implement that code as a function and then call it using a loop. Functions promote code reuse,
modularity, and integrity.
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.
A function is a block of organized, reusable code that is used to perform a single, related
action.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
• Function blocks begin with the keyword def followed by the function name and
parentheses (( )).
• Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string
of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return none.

Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello GHRCE")

Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello GHRCE")
my_function()

Example:
# Function definition is here
def abc( str ):
"This prints a passed string into this function"
print (str)
return;

# Now you can call abc function


abc("I'm first call to user defined function!")
abc("Again second call to the same function")

Arguments:
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
• The following example has a function with one argument (fname). When the function
is called, we pass along a first name, which is used inside the function to print the full
name:
Example:
def my_function(fname):
print(fname + " Kapoor")
my_function("Raj")
my_function("Shashi")
my_function("Shammi")

Parameters or Arguments
• The terms parameter and argument can be used for the same thing: information that
are passed into a function.
• From a function's perspective:
• A parameter is the variable listed inside the parentheses in the function definition.
• An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning
that if your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.
Example:
This function expects 2 arguments, and gets 2 arguments:
def my_function (fname, lname):
print(fname + " " + lname)
my_function("Sachin", "Tendulkar")

Default Parameter Value


• The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as an Argument


• You can send any data types of argument to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function.
Example:
if you send a List as an argument, it will still be a List when it reaches the function:
def my_function (fruits):
for x in fruits:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

WAP to Print the Factorial of given number using function.


Scope of Variables
• All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where you can access a
particular identifier.
There are two basic scopes of variables in Python –
– Global variables
– Local variables
Global vs. Local variables
• Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
• This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Example:
Global Varaiable
Local Variable:

Recursion
• Recursion is the process of defining something in terms of itself.

• Advantages of Recursion:
– Recursive functions make the code look clean and elegant.
– A complex task can be broken down into simpler sub-problems using recursion.
– Sequence generation is easier with recursion than using some nested iteration.

• Disadvantages of Recursion:
– Sometimes the logic behind recursion is hard to follow through.
– Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
– Recursive functions are hard to debug.
Example: Factorial of number using recursion

def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# Change this value for a different result
num = 7

# uncomment to take input from the user


num = int(input("Enter a number: "))
OR
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))

Python String
In Python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.

Syntax:
str = "Hi Python !"

Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.

#Using single quotes


str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)

#Using triple quotes


str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)

Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Strings indexing and splitting

The indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given

Example:

str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])

Output:

H
E
L
L
O
IndexError: string index out of range
The slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in Python to access the substring from the given string.

example.

Example:

# Given String
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Output:

JAVATPOINT
AVAT
VA
JAV
TPO

The negative slicing in the string; it starts from the rightmost character, which is indicated as -
1. The second rightmost index indicates -2, and so on

example

str = 'JAVATPOINT'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])

Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range

You might also like