BCA2pythonSEP-pytcontrol
BCA2pythonSEP-pytcontrol
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Conditional statements
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
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
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
number =6
if number >5:
# Calculate square
print(number * number)
print('Next lines of code')
Run
Output
36
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.
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.
if password =="PYnative@#29":
print("Correct password")
else:
print("Incorrect Password")
Run
Output 1:
Correct password
Output 2:
Incorrect Password
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.
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
Output:
Admin
Editor
Guest
Wrong entry
Iterative statements
Python provides us the following two loop statement to perform some actions
repeatedly
1. for loop
2. while loop
Using for loop, we can iterate any sequence or iterable variable. The sequence can be
string, list, dictionary, set, or tuple.
foriinrange(1,11):
print(i)
Run
Output
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.
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.
whilecondition :
body of while loop
num=10
sum=0
i=1
whilei<=num:
sum=sum+ i
i=i+1
print("Sum of first 10 number is:",sum)
Run
Output
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
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.
fornuminrange(10):
ifnum>5:
print("stop processing.")
break
print(num)
Run
Output
stop processing.
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.
fornuminrange(3,8):
ifnum==5:
continue
else:
print(num)
Run
Output
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.
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.
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 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.
Syntax:
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 −
def printme(str):
"This prints a passed string into this function"
print(str)
return;
output −
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.
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")
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.
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))
a = 10 b = 20 a+b = 30
Example
defgreet():
print('Hello World!')
return
# call the function
greet()
print('Outside function')
Run Code
Output
Hello World!
Outside function
defadd_numbers():
...
return sum
Note: The return statement also denotes that the function has ended. Any code after
return is not executed.
Example:
def square_value(num):
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
• 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.
# default arguments
q=x+y+z
print(“Q:”,q)
print("x: ", x)
print("y: ", y)
return
myFun(10,20)
Output:
Q: 80
x: 10
y: 20
Example 2:
# 1 positional argument
student('John')
# 3 positional arguments
student('John', 'Gates', 'Seventh')
# 2 positional arguments
student('John', 'Gates')
student('John', 'Seventh')
Output:
Example 2:
defadd_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
return
Output
Sum: 5
Sum: 10
Sum: 15
Example:
Output
Example:
Output:
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
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
Output:
Example 3:
Output:
given after the name of the Python script are known as Command Line Arguments
For example -
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
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