2.
Describe the process of input, processing, and output in Python programming with a practical
example
In Python programming, the Input, Processing, and Output (IPO) model explains how data flows
through a program:
1. Input
The program takes input from the user or another source (e.g., files, sensors, etc.).
In Python, you can use functions like input() or read from files using open().
2. Processing
The program performs operations on the input data, such as calculations, transformations, or
logic-based decisions.
3. Output
The program produces results, which can be displayed to the user, saved to a file, or passed
to another system.
PROGRAM:
# Input
number = int(input("Enter a number: ")) # User enters a number
# Processing
square = number * number # Calculate the square of the number
# Output
print("The square of", number, "is", square) # Display the result
OUTPUT:
Enter a number: 5
The square of 5 is 25
3. Demonstrate how to format output using the print function in Python, including the use of escape
sequences and string formatting methods.
Here’s a demonstration of how to format output in Python using the print() function, including
escape sequences and string formatting methods:
1. Escape Sequences in print()
Escape sequences allow you to include special characters in strings.
Common Escape Sequences:
\n : Newline
\t : Tab space
\\ : Backslash
\" : Double quote
\' : Single quote
Example:
print("Hello, World!") # Basic output
print("Hello,\nWorld!") # Newline
print("Name:\tJohn Doe") # Tab space
print("He said, \"Python is great!\"") # Double quotes
print("Path: C:\\Program Files\\Python") # Backslash
Output:
Hello, World!
Hello,
World!
Name: John Doe
He said, "Python is great!"
Path: C:\Program Files\Python
2. String Formatting Methods
Python provides several ways to format strings:
(a) Using format() Method
The format() method allows you to insert values into placeholders ({}).
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
print("The number {1} is greater than {0}.".format(10, 20)) # Positional formatting
Output:
My name is Alice and I am 25 years old.
The number 20 is greater than 10.
(b) Using f-Strings (Python 3.6+)
f-Strings allow embedding expressions directly inside string literals.
name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")
print(f"5 + 3 = {5 + 3}") # Expression inside f-string
Output:
My name is Bob and I am 30 years old.
5+3=8
(c) Using % Formatting (Old Style)
This method is less commonly used now but is still functional.
name = "Charlie"
age = 35
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is Charlie and I am 35 years old.
3. Combining Escape Sequences and Formatting
You can combine escape sequences with any string formatting method.
Example:
name = "Diana"
age = 28
print(f"Name:\t{name}\nAge:\t{age}") # Using f-strings with newline and tab
print("Name:\t{}\nAge:\t{}".format(name, age)) # Using format() with newline and tab
Output:
Name: Diana
Age: 28
Name: Diana
Age: 28
Conclusion
Use escape sequences to manage special characters and layout.
Use format(), f-strings, or % formatting to dynamically include variables and expressions in
your output.
f-Strings are the most modern and recommended way for string formatting in Python.
4. Explain how to print multiple values in a single print statement, and how to control the spacing
between them.
Here’s an easy explanation of how to print multiple values in Python and control the spacing:
1. Printing Multiple Values
You can print multiple values by separating them with commas.
print("Hello", "World", 123)
Output:
Hello World 123
2. Controlling Spacing with sep
The sep parameter controls what is printed between the values.
Examples:
Default (space):
print("A", "B", "C")
Output: A B C
Custom Separator:
print("A", "B", "C", sep="-")
Output: A-B-C
No Space:
print("A", "B", "C", sep="")
Output: ABC
3. Printing Each Value on a New Line
Set sep="\n" to print each value on a new line.
print("Apple", "Banana", "Cherry", sep="\n")
Output:
Apple
Banana
Cherry
4. Adding Text After the Output with end
The end parameter controls what is printed at the end (default is a newline).
Examples:
Default:
print("Hello")
print("World")
Output:
Hello
World
Custom Ending:
print("Hello", end="!")
print("World", end=".")
Output: Hello!World.
5. Mixing Numbers and Text
Python automatically converts numbers to strings when printing.
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 25
Summary
Use commas to separate values in print().
Use sep to control the space or symbol between values.
Use end to control what comes after the print output.
5. Discuss the rules and best practices for naming variables in Python.
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.
6. Write a Python program that prompts the user for an integer input and validates it to ensure it's
within a specified range.
PROGRAM:
# Set the range
min_value = 10
max_value = 50
number = int(input(f"Enter a number between {min_value} and {max_value}: "))
if min_value <= number <= max_value:
print("Valid input!")
else:
print("Invalid input! Please enter a number in the correct range.")
OUTPUT1:
Enter a number between 10 and 50: 25
Valid input!
OUTPUT2:
Enter a number between 10 and 50: 5
Invalid input! Please enter a number in the correct range.
7. Explain the order of precedence for arithmetic operators, comparison operators, and logical
operators in Python
8. Demonstrate how to convert values between different data types in Python, such as integers to
floats and strings to numbers
11. Write a Python program that determines whether a given year is a leap year, incorporating
nested if statements
PROGRAM:
year = int(input("Enter a year: "))
if year % 4 == 0: # Divisible by 4
if year % 100 == 0: # Divisible by 100
if year % 400 == 0: # Divisible by 400
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
else:
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
OUTPUT:
Enter a year: 1900
1900 is not a leap year.
12. Explain the use of and, or, and not operators in Python decision-making statements
[Link]
13. Write a Python program that calculates the factorial of a given number using a while loop.
PROGRAM:
num = int(input("Enter a number to calculate its factorial: "))
factorial = 1
i = num
while i > 0:
factorial *= i
i -= 1
print(f"The factorial of {num} is {factorial}.")
OUTPUT:
Enter a number to calculate its factorial: 5
The factorial of 5 is 120.
14. Demonstrate how to iterate over a range of values and a list using for loops in Python
15. Create a Python program that prints a pattern of stars using nested for loops
PROGRAM:
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
for j in range(i):
print("*", end)
print()
OUTPUT:
Enter the number of rows: 5
**
***
****
*****