Strings
A string in Python is a sequence of characters enclosed in single (‘),
double (“), or triple (‘’’ or “””) quotes.
Python String Input Output Operation
Input Operation in Python
Output Operation in Python
Input Operations in Python
When the user enters data, the input() method always returns a string
data type. If we want to change the data type of our inputs, we have to
use a different conversion method.
Example 1: String Input in Python
The input() method in Python allows you to get user-supplied string input.
The input() method asks the user to enter a string and returns the result
as a string. In this example, the below code takes the user to input their
name and stores it in the variable “name”. Then, it prints out the entered
name with a descriptive message.
Example:
# Prompt the user to enter a string
Name = input(“Enter your name: “)
# Display the input string
print(“You entered:”, name)
Output
Enter your name: abc
You entered: abc
Output Operations in Python
Output operations in Python involve providing information to the user in a
variety of ways, including printing to the console, writing to files,
formatting strings, and creating graphical user interfaces (GUIs). When
creating our code, we must display the results of specific operations that
are executed done in our code. We can do this with the print() method.
The complete syntax for the print() function is:
Example 1: Basic Print Statement in Python
The most basic type of output in Python is printing information to the
console with the print() function. You can print strings, variables, and
expressions as well as modifying the output with formatting choices.
print(“Hello World!”)
Output
Hello World!
String Handling function
String handling functions are essential tools for manipulating text data.
Here’s an overview of some commonly used string functions in Python:
Join(): Concatenates a sequence of strings into a single string, using a
specified separator.
Replace(): Substitutes occurrences of a substring with another string.
Find(): Returns the index of the first occurrence of a substring; returns -1
if not found
Swapcase(): Converts uppercase letters to lowercase and vice versa.
Capitalize(): Converts the first character of the string to uppercase and
the rest to lowercase.
Lower(): Converts all uppercase characters in a string into lowercase
Upper(): Converts all lowercase characters in a string into uppercase
Title(): Convert string to title case.
Example:
Text = ‘geeKs For geEkS’
print(“\nConverted String:”)
print(text.upper())
print(“\nConverted String:”)
print(text.lower())
print(“\nConverted String:”)
print(text.title())
print(“\nConverted String:”)
print(text.swapcase())
print(“\nConverted String:”)
print(text.capitalize())
print(“\nOriginal String”)
print(text)
Output
Converted String:
GEEKS FOR GEEKS
Converted String:
Geeks for geeks
Converted String:
Geeks For Geeks
Converted String:
GEEkS fOR GEeKs
Original String
geeKs For geEkS
Function Prototypes:
i. Function without arguments and without return type
In this type no argument is passed through the function call and no
output is return to main function
The sub function will read the input values perform the operation
and print the result in the same block.
Example :
def add():
A=int(input(“enter a”))
B=int(input(“enter b”))
C=a+b
print(c)
add()
OUTPUT:
Enter a 5
Enter b 10
ii) Function with arguments and without return type
Arguments are passed through the function call but output is not
return to the main function.
Example:
def add(a,b):
C=a+b
print(c)
A=int(input(“enter a”))
B=int(input(“enter b”))
add(a,b)
OUTPUT:
Enter a 5
Enter b 10
15
iii) Function without arguments and with return type
In this type no argument is passed through the function call but
output is return to the main.
Example
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
return c
c=add()
print(c)
OUTPUT:
Enter a 5
Enter b 10
15
iv) Function with arguments and with return type
In this type arguments are passed through the function call and output is
return to the main function.
Example
def add(a,b):
c=a+b
return c
a=int(input(“enter a”))
b=int(input(“enter b”))
c=add(a,b)
print(c)
OUTPUT:
Enter a 5
Enter b 10
15
Return Statement
The Python return statement marks the end of a function and
specifies the value or values to pass back from the function. Return
statements can return data of any type, including integers, floats, strings,
lists, dictionaries, and even other functions. If no return statement is used,
or if a return statement is used without a value, the function will implicitly
return
Example:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
Nesting of Functions
Nesting functions involves defining a function inside another function,
also known as inner or nested functions. These inner functions can access
the enclosing function’s Example:
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
closure = outer_function(10)
print(closure(5)) # Output: 15
Categories of Functions
Python functions can be categorized as follows:
Built-in functions: These are functions that are readily available in
Python without requiring any additional imports. Examples include print(),
len(), abs(), range(), sum(), max(), min(), etc.
Example
result = max([1, 5, 3, 9, 2]) # Using the built-in max() function
print(result) # Output: 9
User-defined functions: These are functions created by the
programmer to perform specific tasks. They are defined using the def
keyword, followed by the function name, parentheses for parameters, and
a colon. The function body is indented below the definition line.
Example
def greet(name):
print(“Hello, “ + name + “!”)
greet(“Alice”) # Output: Hello, Alice!
Lambda functions (anonymous functions): These are small, single-
expression functions that can be defined without a name using the
lambda keyword. They are often used for short, simple operations.
Example
add = lambda x, y: x + y
result = add(5, 3) # Output: 8
Recursive functions: These are functions that call themselves within
their own definition. They are useful for solving problems that can be
broken down into smaller, self-similar subproblems.
Example
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n – 1)
result = factorial(5) # Output: 120
Recursive functions:
A recursive function is defined like any other function, but it includes a
call to itself. The syntax and structure of a recursive function follow the
typical function definition in Python, with the addition of one or more
conditions that lead to the function calling itself.
Example
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n – 1)
print(factorial(5)) # Output: 120
Parameter Passing by Address & by Value
Immutable objects (e.g., int, float, str, tuple) behave like pass by value
because changes inside the function do not affect the original object.
Mutable objects (e.g., list, dict, set) behave like pass by reference
because changes inside the function modify the original object.
Pass by Value (Immutable Objects)
Immutable objects cannot be changed inside a function. If modified, a new
object is created instead of modifying the original one.
Example (Pass by Value)
def modify(x):
x= 10 # This creates a new local variable, not modifying the original
print(“Inside function:”, x)
a= 5
modify(a)
print(“Outside function:”, a) # Original value remains unchanged
Output
Inside function: 10
Outside function: 5
Pass by Reference (Mutable Objects)
Mutable objects can be modified inside a function, affecting the original
object.
Example (Pass by Reference)
def modify_list(lst):
lst.append(4) # Modifying the original list
numbers = [1, 2, 3]
modify_list(numbers)
print(numbers) # The change reflects in the original list
Output:
[1, 2, 3, 4]
Global and Local Variables in Python
Python Local Variables
Local variables in Python are those which are initialized inside a function
and belong only to that particular function. It cannot be accessed
anywhere outside the function.
def func():
X = 10 # Local variable
print(x)
func() #Output 10
Python Global Variables
These are those which are defined outside any function and which are
accessible throughout the program, i.e., inside and outside of every
function. Let’s see how to create a Python global variable.
x = 10 # Global variable
def func():
global x
x = 20 # Modifies global variable
func()
print(x) # Output: 20
Storage Classes in Python
Python does not have explicit storage classes like automatic, external,
static, and register. However, Python provides similar behavior through
variable scope and lifetime management.
Automatic Storage (Local Variables)
Variables declared inside a function are local and exist only during
the function’s execution.
Automatically created and destroyed when the function finishes
execution.
Example (Automatic Variable)
def func():
x = 10 # Local variable (automatic storage)
print(x)
func()
Output: 10
External Storage (Global Variables)
Global variables exist throughout the program’s execution.
Declared outside functions and can be accessed anywhere.
Use the global keyword inside a function to modify a global variable.
Example
def compute():
a, b = 5, 10 # Local variables (optimized)
return a + b
print(compute()) # Output: 15
Static Storage (Using nonlocal)
In nested functions, nonlocal behaves like static storage in C.
Retains value between function calls within the same scope.
Example
def outer():
x = 0 # Static-like variable
def inner():
nonlocal x # Retains value between calls
x += 1
print(x)
return inner
counter = outer()
counter() # Output: 1
counter() # Output: 2
counter() # Output: 3
Register Storage (Optimized by Python Interpreter)
Python does not allow direct access to CPU registers like C.
However, Python optimizes frequently accessed variables internally.
The best practice is to use local variables for fast access.
Example
def compute():
a, b = 5, 10 # Local variables (optimized)
return a + b
print(compute()) # Output: 15