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

BCA2pythonSEP-pytcontrol

The document covers basic Python control flow statements, including conditional (if, if-else, if-elif-else), iterative (for, while), and transfer statements (break, continue). It also explains the concept of functions in Python, detailing how to define and call them, as well as the types of function arguments. Examples are provided for each concept to illustrate their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

BCA2pythonSEP-pytcontrol

The document covers basic Python control flow statements, including conditional (if, if-else, if-elif-else), iterative (for, while), and transfer statements (break, continue). It also explains the concept of functions in Python, detailing how to define and call them, as well as the types of function arguments. Examples are provided for each concept to illustrate their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Python Basic Concepts-BCA-2nd sem

93 Python Control Flow Statements


The flow control statements are divided into three categories

1. Conditional statements
2. Iterative statements.
3. Transfer statements

Python control flow statements

Conditional statements

In Python, condition statements act depending on whether a given condition is true or


false. You can execute different blocks of codes depending on the outcome of a
condition. Condition statements always evaluate to either True or False.

There are three types of conditional statements.

1. if statement
2. if-else
3. if-elif-else
4. nested if-else

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 1


Python Basic Concepts-BCA-2nd sem

if statement in Python

In control statements, The if statement is the simplest form. It takes a condition and
evaluates to either True or False.

If the condition is True, then the True block of code will be executed, and if the
condition is False, then the block of code is skipped, and The controller moves to the
next line

Syntax of the if statement

if condition:
statement 1
statement 2
statement n

Python if statements
Let’s see the example of the if statement. In this example, we will calculate the square
of a number if it greater than 5

Example

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 2


Python Basic Concepts-BCA-2nd sem

number =6
if number >5:
# Calculate square
print(number * number)
print('Next lines of code')

Run
Output

36

Next lines of code

If – else statement

The if-else statement checks the condition and executes the if block of code when the
condition is True, and if the condition is False, it will execute the else block of code.

Syntax of the if-else statement

if condition:
statement 1
else:
statement 2

If the condition is True, then statement 1 will be executed If the condition is False,
statement 2 will be executed. See the following flowchart for more detail.

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 3


Python Basic Concepts-BCA-2nd sem

Python if-else statements


Example

password =input('Enter password ')

if password =="PYnative@#29":
print("Correct password")
else:
print("Incorrect Password")

Run
Output 1:

Enter password PYnative@#29

Correct password

Output 2:

Enter password PYnative

Incorrect Password

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 4


Python Basic Concepts-BCA-2nd sem

Chain multiple if statement in Python

In Python, the if-elif-else condition statement has an elif blocks to chain multiple
conditions one after another. This is useful when you need to check multiple conditions.

With the help of if-elif-else we can make a tricky decision. The elif statement checks
multiple conditions one by one and if the condition fulfills, then executes that code.

Syntax of the if-elif-else statement:

if condition-1:
statement 1
elif condition-2:
stetement2
elif condition-3:
stetement3
...
else:
statement

Example

defuser_check(choice):
if choice ==1:
print("Admin")
elif choice ==2:
print("Editor")
elif choice ==3:
print("Guest")
else:
print("Wrong entry")

user_check(1)
user_check(2)
user_check(3)
user_check(4)

Run

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 5


Python Basic Concepts-BCA-2nd sem

Output:

Admin

Editor

Guest

Wrong entry

Iterative statements

In Python, iterative statements allow us to execute a block of code repeatedly as long as


the condition is True. We also call it a loop statements.

Python provides us the following two loop statement to perform some actions
repeatedly

1. for loop
2. while loop

Let’s learn each one of them with the examples

for loop in Python

Using for loop, we can iterate any sequence or iterable variable. The sequence can be
string, list, dictionary, set, or tuple.

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 6


Python Basic Concepts-BCA-2nd sem

Python for loop


Syntax of for loop:

for element in sequence:


body of for loop

Example to display first ten numbers using for loop

foriinrange(1,11):
print(i)

Run
Output

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 7


Python Basic Concepts-BCA-2nd sem

10

The range() function returns a sequence of numbers starting from 0 (by default) if the
initial limit is not specified and it increments by 1 (by default) until a final limit is
reached.

The range() function is used with a loop to specify the range (how many times) the
code block will be executed. Let us see with an example.

While loop in Python

In Python, The while loop statement repeatedly executes a code block while a particular
condition is true.

In a while-loop, every time the condition is checked at the beginning of the loop, and if
it is true, then the loop’s body gets executed. When the condition became False, the
controller comes out of the block.

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 8


Python Basic Concepts-BCA-2nd sem

Python while loop


Syntax of while-loop

whilecondition :
body of while loop

Example to calculate the sum of first ten numbers

num=10
sum=0
i=1
whilei<=num:
sum=sum+ i
i=i+1
print("Sum of first 10 number is:",sum)

Run
Output

Sum of first 10 number is: 55

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 9


Python Basic Concepts-BCA-2nd sem

Transfer statements

In Python, transfer statements are used to alter the program’s way of execution in a
certain manner. For this purpose, we use three types of transfer statements.

1. break statement
2. continue statement
3. pass statements

Break Statement in Python

The break statement is used inside the loop to exit out of the loop. It is useful when we
want to terminate the loop as soon as the condition is fulfilled instead of doing the
remaining iterations. It reduces execution time. Whenever the controller encountered a
break statement, it comes out of that loop immediately

Let’s see how to break a for a loop when we found a number greater than 5.

Example of using a break statement

fornuminrange(10):
ifnum>5:
print("stop processing.")
break
print(num)

Run

Output

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 10


Python Basic Concepts-BCA-2nd sem

stop processing.

Continue statement in python

The continue statement is used to skip the current iteration and continue with the
next iteration.

Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the
body of the loop for other numbers.

Example of a continue statement

fornuminrange(3,8):
ifnum==5:
continue
else:
print(num)

Run

Output

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 11


Python Basic Concepts-BCA-2nd sem

exit() function in python

The exit() function in Python is used to exit or terminate the current running script or
program. You can use it to stop the execution of the program at any point. When
the exit() function is called, the program will immediately stop running and exit.

The syntax of the exit() function is:

exit([status])

Here, status is an optional argument that represents the exit status of the program.
The exit status is an integer value that indicates the reason for program termination. By
convention, a status of 0 indicates successful execution, and any non-zero status
indicates an error or abnormal termination.

If the status argument is omitted or not provided, the default value of 0 is used.
Here's an example usage of the exit() function:

print("Before exit")
exit(1)
print("After exit")# This line will not be executed

Python Functions
A Python function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your application and a
high degree of code reusing.

A top-to-down approach towards building the processing logic involves defining blocks
of independent reusable functions. A Python function may be invoked from any other
function by passing required data (called parameters or arguments). The called
function returns its result back to the calling environment.

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 12


Python Basic Concepts-BCA-2nd sem

Types of Python Functions


• Built-in functions
• Functions defined in built-in modules
• User-defined functions

Python's standard library includes number of built-in functions. Some of Python's built-
in functions are print(), int(), len(), sum(), etc. These functions are always available, as
they are loaded into computer's memory as soon as you start Python interpreter.

The standard library also bundles a number of modules. Each module defines a group of
functions. These functions are not readily available. You need to import them into the
memory from their respective modules.

In addition to the built-in functions and functions in the built-in modules, you can also
create your own functions. These functions are called user-defined functions.

Function Definition in Python


You can define custom 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.

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 13


Python Basic Concepts-BCA-2nd sem

• 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_body
return[expression]

By default, parameters have a positional behaviour and you need to inform them in the
same order that they were defined.

Once the function is defined, you can execute it by calling it from another function or
directly from the Python prompt.

Example

The following example shows how to define a function greetings(). The bracket is
empty so there aren't any parameters.

The first line is the docstring. Function block ends with return statement. when this
function is called, Hello world message will be printed.

def greetings():
"This is docstring of greetings function"
print("Hello World")
return

greetings()
Calling a Function in Python

Defining a function only gives it a name, specifies the parameters that are to be included
in the function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −

# Function definition is here

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 14


Python Basic Concepts-BCA-2nd sem

def printme(str):
"This prints a passed string into this function"
print(str)
return;

# Now you can call printme function


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

When the above code is executed, it produces the following

output −

I'm first call to user defined function!


Again second call to the same function

Function Arguments
The process of a function often depends on certain data provided to it while calling it.
While defining a function, you must give a list of variables in which the data passed to it
is collected. The variables in the parentheses are called formal arguments.

When the function is called, value to each of the formal arguments must be provided.
Those are called actual arguments.

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 15


Python Basic Concepts-BCA-2nd sem

Example

Let's modify greetings function and have name an argument. A string passed to the
function as actual argument becomes name variable inside the function.

defgreetings(name):
"This is docstring of greetings function"
print("Hello {}".format(name))
return

greetings("Samay")
greetings("Pratima")
greetings("Steven")

It will produce the following output −

Hello Samay
Hello Pratima
Hello Steven
Function with Return Value

The return keyword as the last statement in function definition indicates end of
function block, and the program flow goes back to the calling function. Although
reduced indent after the last statement in the block also implies return but using explicit
return is a good practice.

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 16


Python Basic Concepts-BCA-2nd sem

Along with the flow control, the function can also return value of an expression to the
calling function. The value of returned expression can be stored in a variable for further
processing.

Example

Let us define the add() function. It adds the two values passed to it and returns the
addition. The returned value is stored in a variable called result.

defadd(x,y):
z=x+y
return z

a=10
b=20
result = add(a,b)
print("a = {} b = {} a+b = {}".format(a, b, result))

It will produce the following output −

a = 10 b = 20 a+b = 30

Example

defgreet():
print('Hello World!')
return
# call the function
greet()

print('Outside function')
Run Code

Output

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 17


Python Basic Concepts-BCA-2nd sem

Hello World!
Outside function

In the above example, we

The return Statement in Python


A Python function may or may not return a value. If we want our function to return
some value to a function call, we use the return statement. For example,

defadd_numbers():
...
return sum

Here, we are returning the variable sum to the function call.

Note: The return statement also denotes that the function has ended. Any code after
return is not executed.

Example:

def square_value(num):

"""This function returns the square value of the entered number"""

return num**2

print(square_value(2))

print(square_value(-4))

Output:
By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 18
Python Basic Concepts-BCA-2nd sem

4
16

Types of Function Arguments


Based on how the arguments are declared while defining a Python function, they are
classified into the following categories −

• Default argument
• Keyword arguments (named arguments)
• Command line Arguments

Order of Arguments

A function can have arguments of any of the types defined above. However, the
arguments must be declared in the following order −

• The argument list begins with the positional-only args, followed by the slash (/)
symbol.
• It is followed by regular positional args that may or may not be called as keyword
arguments.
• Then there may be one or more args with default values.
• If the function has any keyword-only arguments, put an asterisk before their
names start. Some of the keyword-only arguments may have a default value.
• Last in the bracket is argument with two asterisks ** to accept arbitrary number
of keyword arguments.

Default Arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument. The following example illustrates
Default arguments.
• Default arguments are values that are provided while defining functions.
• The assignment operator = is used to assign a default value to the argument.

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 19


Python Basic Concepts-BCA-2nd sem

• Default arguments become optional during the function calls.


• If we provide a value to the default arguments during function calls, it overrides
the default value.
• The function can have any number of default arguments.
• Default arguments should follow non-default arguments.

# Python program to demonstrate

# default arguments

def myFun(x, y, z=50):

q=x+y+z

print(“Q:”,q)

print("x: ", x)

print("y: ", y)

return

# Driver code (We call myFun() with only# argument)

myFun(10,20)

Output:
Q: 80
x: 10
y: 20

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 20


Python Basic Concepts-BCA-2nd sem

Example 2:

defstudent(firstname, lastname ='Mark', standard ='Fifth'):


print(firstname, lastname, 'studies in', standard, 'Standard')
return

# 1 positional argument
student('John')

# 3 positional arguments
student('John', 'Gates', 'Seventh')

# 2 positional arguments
student('John', 'Gates')
student('John', 'Seventh')

Output:

John Mark studies in Fifth Standard


John Gates studies in Seventh Standard
John Gates studies in Fifth Standard
John Seventh studies in Fifth Standard

Example 2:
defadd_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
return

# function call with two arguments


add_numbers(2, 3)

# function call with one argument


add_numbers(a = 2)

# function call with no arguments


add_numbers()

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 21


Python Basic Concepts-BCA-2nd sem

Output

Sum: 5
Sum: 10
Sum: 15

Example:

# function with 2 keyword arguments grade and school


def student(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)
return
# without passing grade and school
# Passing only the mandatory arguments
student('Jon',12)

Output

# Output: Student Details: Jon 12 Five ABC School

Example:

# function with 2 keyword arguments grade and school


defstudent(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)

# not passing a school value (default value is used)


# six is assigned to grade
student('Kelly',12,'Six')

# passign all arguments


student('Jessa',12,'Seven','XYZ School')

Output:

Student Details: Kelly 12 Six ABC School

Student Details: Jessa 12 Seven XYZ School

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 22


Python Basic Concepts-BCA-2nd sem

Keyword Arguments
Usually, at the time of the function call, values get assigned to the arguments according
to their position. So we must pass values in the same sequence defined in a function
definition.

The idea is to allow the caller to specify the argument name with values so that the
caller does not need to remember the order of parameters.

Keyword arguments are those arguments where values get assigned to the arguments
by their keyword (name) when the function is called. It is preceded by the variable
name and an (=) assignment operator. The Keyword Argument is also called a named
argument
Example 1:

• Python3

# Python program to demonstrate Keyword Arguments

def student(firstname, lastname):

print(firstname, lastname)

return

# Keyword arguments

student(firstname='Geeks', lastname='Practice')

student(lastname='Practice', firstname='Geeks')

Output:
Geeks Practice
By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 23
Python Basic Concepts-BCA-2nd sem

Practice Greeks

Example 2:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
return

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Output:

The youngest child is Emil

Example 3:

# function with 2 keyword arguments


defstudent(name, age):
print('Student Details:', name, age)

# default function call


student('Jessa',14)

# both keyword arguments


student(name='Jon', age=12)

# 1 positional and 1 keyword


student('Donald', age=13)

Output:

Student Details: Jessa 14

Student Details: Jon 12

Student Details: Donald 13

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 24


Python Basic Concepts-BCA-2nd sem

Command line Arguments

Python Command Line Arguments provides a convenient way to accept some


information at the command line while running the program. The arguments that are

given after the name of the Python script are known as Command Line Arguments

and they are used to pass some information to the program.

For example -

$ python script.py arg1 arg2 arg3

Here Python script name is script.py and rest of the three arguments - arg1 arg2 arg3
are command line arguments for the program. There are following three Python
modules which are helpful in parsing and managing the command line arguments:

1. sys module
2. getopt module
3. argparse module

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 25


Python Basic Concepts-BCA-2nd sem

4. Positional Parameters in Python


During a function call, values passed through arguments should be in the order of
parameters in the function definition. This is called positional Parameters.
Keyword arguments should follow positional arguments only.
def add(a,b,c):
return (a+b+c)
The above function can be called in two ways:
First, during the function call, all arguments are given as positional arguments. Values
passed through arguments are passed to parameters by their position. 10 is assigned
to a, 20 is assigned to b and 30 is assigned to c.
print (add(10,20,30))
#Output:60
The second way is by giving a mix of positional and keyword arguments. Keyword
arguments should always follow positional arguments.
print (add(10,c=30,b=20))
#Output:60
Default vs. Keyword vs. Positional Arguments

An illustration of positional, default and keyword arguments in Python.

4. Arbitrary Positional Arguments in Python


Variable-length arguments are also known as arbitrary arguments. If we don’t know the
number of arguments needed for the function in advance, we can use arbitrary
arguments. Arbitrary arguments come in two types: arbitrary positional arguments and
arbitrary keyword arguments.
For arbitrary positional argument, an asterisk (*) is placed before a parameter in
function definition which can hold non-keyword variable-length arguments. These

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 26


Python Basic Concepts-BCA-2nd sem

arguments will be wrapped up in a tuple. Before the variable number of arguments, zero
or more normal arguments may occur.
def add(*b):
result=0
for i in b:
result=result+i
return result

print (add(1,2,3,4,5))
#Output:15
print (add(10,20))
#Output:30

5. Arbitrary Keyword Arguments in Python


For arbitrary keyword argument, a double asterisk (**) is placed before a parameter in a
function which can hold keyword variable-length arguments.
def fn(**a):
for i in a.items():
print (i)
fn(numbers=5,colors="blue",fruits="apple")
'''
Output:
('numbers', 5)
('colors', 'blue')
('fruits', 'apple')
'''

By Smt.Kalpana C Dalwai, Assistant Professor, Karnatak Science College Dharwad Page 27

You might also like