0% found this document useful (0 votes)
75 views6 pages

Oop2 Midterm Module 3

This document provides an introduction to input and output in Python as well as functions. It discusses how to take input from the keyboard or other sources using the input() function. It also covers type casting input to integers, floats, or strings. The document describes how to take multiple inputs in one line using split() or list comprehension. It defines functions in Python and covers default arguments, built-in versus user-defined functions, and recursion.

Uploaded by

CODENAME KAVERI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views6 pages

Oop2 Midterm Module 3

This document provides an introduction to input and output in Python as well as functions. It discusses how to take input from the keyboard or other sources using the input() function. It also covers type casting input to integers, floats, or strings. The document describes how to take multiple inputs in one line using split() or list comprehension. It defines functions in Python and covers default arguments, built-in versus user-defined functions, and recursion.

Uploaded by

CODENAME KAVERI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

OBJECT ORIENTED PROGRAMMING 2

Module 3: Console Input and Functions

Discussions
Introduction
To be useful, a program usually needs to communicate with the outside world by obtaining input data from the user
and displaying result data back to the user. This module will introduce you to Python input and output.

Input may come directly from the user via the keyboard, or from some external source like a file or database. Output
can be displayed directly to the console or IDE, to the screen via a Graphical User Interface (GUI), or again to an external
source.

Reading Input From the Keyboard


Programs often need to obtain data from the user, usually by way of input from the keyboard. The simplest way to
accomplish this in Python is with input().

input() pauses program execution to allow the user to type in a line of input from the keyboard. Once the user
presses the Enter key, all characters typed are read and returned as a string.
# input
input1 = input(“Enter a value: “)

# output print(input1)

Type Casting
We can also type cast this input to integer, float or string by specifying the input() function inside the type.
1. Typecasting the input to Integer: There might be conditions when you might require integer input from
user/Console, the following code takes two input(integer/float) from console and typecasts them to integer then
prints the sum.
# input
num1 = int(input(“Number 1: ”)) num2 =
int(input(“Number 2: ”))

# printing the sum in integer


print(num1 + num2)
2. Typecasting the input to Float: To convert the input to float the following code will work out.
# input
num1 = float(input(“Number 1: ”)) num2 =
float(input(“Number 2: “))

# printing the sum in float


print(num1 + num2)
3. Typecasting the input to String: All kind of input can be converted to string type whether they are float or
integer. We make use of keyword str for typecasting.
# input
string = str(input(“Enter a String Value: ”))

# output print(string)

Taking multiple inputs from user in Python


Developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one
line using scanf but in Python user can take multiple values or inputs in one line by two methods
 Using split() method
 Using List comprehension

Using split() method


This function helps in getting a multiple inputs from user. It breaks the given input by the specified separator.
If a separator is not provided then any white space is a separator. Generally, user use a split() method to split a
Python string but one can use it in taking multiple input.
Syntax :
input().split(separator, maxsplit)

Example:
# taking two inputs at a time
x, y = input("Enter a two value: ").split()
print("Number of boys: ", x) print("Number of girls:
", y)
print()

# taking three inputs at a time


x, y, z = input("Enter a three value: ").split()
print("Total number of students: ", x) print("Number of
boys is : ", y) print("Number of girls is : ", z)
print()

# taking two inputs at a time


a, b = input("Enter a two value: ").split()
print("First number is {} and second number is {}".format(a, b)) print()

# taking multiple inputs at a time


# and type casting using list() function
x = list(map(int, input("Enter a multiple value: ").split())) print("List of
students: ", x)

Using List comprehension


List comprehension is an elegant way to define and create list in Python. We can create lists just like mathematical
statements in one line only. It is also used in getting multiple inputs from a user.
# Python program showing # how to
take multiple input # using List
comprehension

# taking two input at a time


x, y = [int(x) for x in input("Enter two value: ").split()] print("First Number
is: ", x)
print("Second Number is: ", y) print()

# taking three input at a time


x, y, z = [int(x) for x in input("Enter three value: ").split()] print("First
Number is: ", x)
print("Second Number is: ", y)
print("Third Number is: ", z) print()

# taking two inputs at a time


x, y = [int(x) for x in input("Enter two value: ").split()] print("First number
is {} and second number is {}".format(x, y)) print()

# taking multiple inputs at a time


x = [int(x) for x in input("Enter multiple value: ").split()] print("Number of list is:
", x)

Python Functions
A function is a block of code that contains one or more Python statements and used for performing a specific task.
Why use function in Python?
1. Code re-usability: Lets say we are writing an application in Python where we need to perform a specific
task in several places of our code, assume that we need to write 10 lines of code to do that specific task. It
would be better to write those 10 lines of code in a function and just call the function wherever needed,
because writing those 10 lines every time you perform that task is tedious, it would make your code
lengthy, less-readable and increase the chances of human errors.
2. Improves Readability: By using functions for frequent tasks you make your code structured and
readable. It would be easier for anyone to look at the code and be able to understand the flow and
purpose of the code.
3. Avoid redundancy: When you no longer repeat the same lines of code throughout the code and use
functions in places of those, you actually avoiding the redundancy that you may have created by not
using functions.

Syntax of functions in Python Function


declaration:
def function_name(function_parameters): function_body # Set
of Python statements return # optional return statement

Calling the function:


# when function doesn't return anything
function_name(parameters)
OR
# when function returns something
# variable is to store the returned value variable =
function_name(parameters)

Python Function example def


add(num1, num2):
return num1 + num2
sum1 = add(100, 200) sum2 =
add(8, 9) print(sum1)
print(sum2)

Default arguments in Function


Now that we know how to declare and call a function, lets see how can we use the default arguments. By using
default arguments we can avoid the errors that may arise while calling a function without passing all the parameters.
Lets take an example to understand this:
In this example we have provided the default argument for the second parameter, this default argument would be
used when we do not provide the second parameter while calling this function.
# default argument for second parameter def
add(num1, num2=1):
return num1 + num2
sum1 = add(100, 200)
sum2 = add(8) # used default argument for second param sum3 =
add(100) # used default argument for second param print(sum1)
print(sum2)
print(sum3)

Types of functions
There are two types of functions in Python:
1. Built-in functions: These functions are predefined in Python and we need not to declare these functions
before calling them. We can freely invoke them as and when needed.
2. User defined functions: The functions which we create in our code are user-defined functions. The
add() function that we have created in above examples is a user-defined function.

Python Recursion
A function is said to be a recursive if it calls itself. For example, lets say we have a function abc() and in the body of
abc() there is a call to the abc().
Python example of Recursion
In this example we are defining a user-defined function factorial(). This function finds the factorial of a number
by calling itself repeatedly until the base case is reached.

# Example of recursion in Python to # find the


factorial of a given number

def factorial(num):
"""This function calls itself to find the
factorial of a number"""
if num == 1:
return 1 else:
return (num * factorial(num - 1)) num = 5
print("Factorial of", num, "is: ", factorial(num))

What is a base case in recursion?


When working with recursion, we should define a base case for which we already know the answer. In the
above example we are finding factorial of an integer number and we already know that the factorial of 1 is 1 so this
is our base case. Each successive recursive call to the function should bring it closer to the base case, which is
exactly what we are doing in above example. We use base case in recursive function so that the function stops
calling itself when the base case is reached. Without the base case, the function would keep calling itself indefinitely.

We use recursion to break a big problem in small problems and those small problems into further smaller
problems and so on. At the end the solutions of all the smaller subproblems are collectively helps in finding the
solution of the big main problem.
Advantages of recursion
Recursion makes our program:
1. Easier to write.
2. Readable – Code is easier to read and understand.
3. Reduce the lines of code – It takes less lines of code to solve a problem using recursion.
Disadvantages of recursion
1. Not all problems can be solved using recursion.
2. If you don’t define the base case then the code would run indefinitely.
3. Debugging is difficult in recursive functions as the function is calling itself in a loop and it is hard to
understand which call is causing the issue.
4. Memory overhead – Call to the recursive function is not memory efficient.

Module Recap
 Input may come directly from the user via the keyboard, or from some external source like a file or database
 Output can be displayed directly to the console or IDE, to the screen via a Graphical User Interface (GUI), or
again to an external source.
 Programs often need to obtain data from the user, usually by way of input from the keyboard. The simplest
way to accomplish this in Python is with input().
 All kind of input can be converted to string type whether they are float or integer.
 Developer often wants a user to enter multiple values or inputs in one line
 A function is a block of code that contains one or more Python statements and used for performing a specific
task.
 By using functions for frequent tasks you make your code structured and readable.
 A function is said to be a recursive if it calls itself.
 When working with recursion, we should define a base case for which we already know the answer.

You might also like