Renaissance University, Indore
School Of Computer Science
BCA /[Link] III Sem
Subject:- Fundamentals Of Python
Unit - II
1. Input and Output
Input in Python:
In Python, input from the user is taken using the input() function. This function
prompts the user to enter data, and it always returns the data as a string.
Syntax:
variable = input("Enter a value: ")
The string inside input() is optional and can be used to display a prompt
message to the user.
To handle numerical inputs, the string returned by input() can be
converted to other types like int() or float().
Example:
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
age is stored as an integer, and height as a floating-point number.
Note: Always ensure to type-cast inputs when you expect a non-string value, as
input() by default returns a string.
Output in Python:
To display output, Python uses the print() function. It can be used to display
values, variables, or expressions on the screen.
Basic Syntax:
print("Hello, world!")
You can also display multiple values, variables, and expressions by separating
them with commas.
Example:
name = "Ram"
age = 25
print("Name:", name, "Age:", age)
You can use formatted strings for cleaner output using f-strings, available
in Python 3.6 and later.
Formatted Strings (f-strings):
print(f"Hello, {name}. You are {age} years old.")
This provides a more readable way to output variables inside strings.
2. Command Line Arguments
Command line arguments allow you to pass data to the Python script when it is
executed. This is especially useful for scripts that need to process files or work
with user input from the terminal.
Using [Link]:
The [Link] list contains the arguments passed to the script from the command
line.
Syntax:
import sys
[Link][0] refers to the name of the script itself.
[Link][1], [Link][2], etc., refer to the command line arguments
passed.
Example:
Let's say you run the Python script like this:
python [Link] Hello World
In the script, you can access these arguments using [Link]:
import sys
print("Script Name:", [Link][0]) # Outputs: [Link]
print("First Argument:", [Link][1]) # Outputs: Hello
print("Second Argument:", [Link][2]) # Outputs: World
Converting Command Line Arguments:
Since [Link] elements are strings by default, you may need to convert them to
appropriate data types.
Example:
import sys
num1 = int([Link][1]) # Convert to integer
num2 = float([Link][2]) # Convert to float
result = num1 + num2
print(f"Sum: {result}")
You can also handle potential errors when users input invalid data by using
exception handling (more on this later).
3. Control Statements
Control statements determine the flow of execution in the program. These
statements allow us to execute certain blocks of code based on conditions
(decision-making) or repeat tasks (loops).
Conditional Statements (if-else):
Conditional statements are used to execute code based on a condition.
If: If the condition is True, the code block inside the if is executed.
Else: If the condition is False, the code block inside the else is executed.
Elif: Short for "else if", this allows you to check multiple conditions.
Syntax:
if condition:
# Code block to execute if condition is true
else:
# Code block to execute if condition is false
Example:
x = 10
if x > 0:
print("x is positive")
else:
print("x is not positive")
Chained Conditional Statements (if-elif-else):
If there are multiple conditions to check, use elif (else if) to create a chain of
conditions.
Example:
x = 10
if x < 0:
print("x is negative")
elif x == 0:
print("x is zero")
else:
print("x is positive")
Iteration (Loops):
Python provides two types of loops: while and for loops.
While Loop:
A while loop repeats a block of code as long as the condition is true. OR
In Python, a while loop is used to execute a block of statements repeatedly until a
given condition is satisfied. When the condition becomes false, the line
immediately after the loop in the program is executed.
Syntax:
while condition:
# Code to execute
Example:
count = 0
while count < 5:
print(count)
count += 1
In the above example, the loop will print the values from 0 to 4.
For Loop:
A for loop is used to iterate over a sequence, like a list, tuple, or string, or a
range of numbers using range().
It allow to execute a block of code repeatedly, once for each item in the
sequence.
Syntax:
for element in sequence:
# Code to execute for each element
Example:
for i in range(5): # This will iterate from 0 to 4
print(i)
Breaking and Continuing Loops:
Break: Terminates the loop prematurely.
Continue: Skips the current iteration and moves to the next one.
Example:
for i in range(5):
if i == 3:
break # Exits the loop when i equals 3
print(i) # Outputs: 0, 1, 2
for i in range(5):
if i == 3:
continue # Skips printing 3
print(i) # Outputs: 0, 1, 2, 4
4. Functions and Scope
Functions:
Python Functions are a block of statements that does a specific task. The idea is
to put some commonly or repeatedly done task together and make a function so
that instead of writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and over again.
Functions allow you to group code that performs a specific task into reusable
blocks. Functions are defined using the def keyword.
Syntax:
def function_name(parameters):
# Code block
return result
Example:
def greet(name):
print(f"Hello, {name}!")
Parameters are the inputs to the function, and return is used to send back
the result.
Returning Values from Functions:
Functions can return values using the return keyword. The value returned can be
stored in a variable and used later.
Example:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Outputs: 8
Scope:
In Python, there are two types of variable scopes:
Global Scope: Variables declared outside any function are accessible
globally.
Local Scope: Variables declared inside a function are accessible only
within that function.
Example:
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print(x + y) # Accessing global and local variables
my_function() # Outputs: 15
Recursion:
Recursion is a programming technique where a function calls itself either
directly or indirectly to solve a problem by breaking it into smaller, simpler
subproblems.
In Python, recursion is especially useful for problems that can be divided into
identical smaller tasks, such as mathematical calculations, tree traversals or
divide-and-conquer algorithms.
Example (Factorial Calculation):
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Outputs: 120
Packages and Modules:
Modules: A module is a Python file that contains definitions (functions,
classes, variables) that can be imported into other Python scripts.
Packages: Python packages are a way to organize and structure code by
grouping related modules into directories. A package is essentially a
folder that contains an __init__.py file and one or more Python files
(modules). This organization helps manage and reuse code effectively,
especially in larger projects. It also allows functionality to be easily
shared and distributed across different applications. Packages act like
toolboxes, storing and organizing tools (functions and classes) for
efficient access and reuse.
Key Components of a Python Package
Module: A single Python file containing reusable code (e.g., [Link]).
Package: A directory containing modules and a special __init__.py file.
Sub-Packages: Packages nested within other packages for deeper
organization.
Example:
import math
print([Link](16)) # Outputs: 4.0
To create your own module, save Python code in a .py file, then import it in
other scripts.