Comments & Input/Output Operations in Python
If a student types 19 into input, Python initially stores the characters as a string. Convert to int before adding one, or string concatenation will give a different result. A comment can explain why an input must be converted.
1. Comments in Python
Comments are non-executable explanatory notes written inside source code to make the program easier for humans to understand. The Python Interpreter completely ignores comments during execution.
In Python, comments are written in three ways:
A hash sign starts a comment outside a string literal. A docstring is a string in a specific leading position that documents a module, class or function.
- 1. Single-Line Comment (#) — Starts with the hash symbol # and continues till the end of that line
- 3. Docstrings (“”“…”“”) — Triple-quoted string placed as the first line inside a function/class; accessible via doc
1. Single-Line Comments (#)
Any text starting with a hash symbol (#) is treated as a single-line comment. It can be placed on its own line or inline at the end of a code statement:
# Calculate area of a circle
radius = 5
area = 3.14159 * (radius ** 2) # Inline comment: ** is power operator
2. Multi-Line Comments
When you need to write a comment spanning several lines, you can either put # at the start of each line OR enclose the block inside triple quotes (''' ... ''' or """ ... """):
# Author : CampusNotes Team
# Course : BCA (DAVV Indore)
# Subject : Python Programming - Unit 1
3. Docstrings (Documentation Strings — """ ... """)
A Docstring is a special multi-line string literal enclosed in triple quotes (""" ... """) that appears as the very first statement inside a module, function, class, or method definition.
- Difference between a Comment and a Docstring: Unlike
#comments (which are stripped out and ignored by Python), Docstrings are retained at runtime and can be inspected usingfunction_name.__doc__orhelp(function_name)!
def add_numbers(a, b):
"""This function takes two numbers and returns their sum."""
return a + b
print(add_numbers.__doc__)
# Output: This function takes two numbers and returns their sum.
View diagram · Figure 1.6: Types of Comments & Documentation Strings in Python
2. Input Operations in Python (input() Function)
To make a program interactive, we need to accept input from the user via the keyboard. Python provides the built-in input() function for this purpose.
Syntax of input():
variable_name = input("Prompt message displayed to user: ")
Golden Rule of input() in Python:
input() ALWAYS returns the user’s input as a String (str)!
Even if the user types a number like 25 or 99.5, input() returns it as the string "25" or "99.5". Therefore, to perform mathematical calculations, you must explicitly type-cast input() using int(), float(), or eval()!
# 1. Reading a String input (No type-casting needed)
name = input("Enter your name: ")
# 2. Reading an Integer input using int(input())
age = int(input("Enter your age: "))
# 3. Reading a Float (decimal) input using float(input())
percentage = float(input("Enter your 12th percentage: "))
# 4. Reading MULTIPLE space-separated inputs on a single line using .split()
x, y = map(int, input("Enter two numbers separated by space: ").split())
print("Sum =", x + y)
3. Output Operations in Python (print() Function)
To display output on the console screen, Python provides the built-in print() function.
Complete Syntax of print():
print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Two Super-Important Parameters of print(): sep and end
This is a favorite 2-mark and 5-mark question in DAVV BCA exams!
sep(Separator Parameter — Default is a single space' '): Specifies the character or string used to separate multiple values passed inside a singleprint()call.end(End Parameter — Default is a newline'\n'): Specifies what character is printed at the very end of theprint()statement. By default,print()moves to a new line (\n), but settingend=" "keeps the nextprint()on the same line!
# 1. Default print (sep=' ', end='\n')
print("BCA", "DAVV", "Indore")
# Output: BCA DAVV Indore
# 2. Using custom 'sep' parameter
print("02", "04", "2026", sep="-")
# Output: 02-04-2026
print("ishaan", "campusnotes.in", sep="@")
# Output: ishaan@campusnotes.in
# 3. Using custom 'end' parameter to print on the SAME line
print("Hello", end=" ")
print("World!")
# Output: Hello World!
4. 3 Ways of Formatting Output in Python
When displaying variables mixed with text, Python offers three formatting styles (with f-strings being the cleanest modern standard):
Formatted string literals insert expressions inside braces and format can fill named or numbered fields. Percent formatting uses conversion markers to place values in text.
- f-Strings (Formatted String Literals — Python 3.6+) — Prefix string with f and put variables directly inside { } : f“Name: {name}, Marks: {marks}”
- The str.format() Method — Uses { } placeholders filled by .format() : “Name: {}, Marks: {}”.format(name, marks)
- Old C-Style % Operator — Uses %s (string), %d (int), %.2f (float): “Name: %s, Marks: %d” % (name, marks)
Complete Program Demonstrating Input, Calculation & Formatted Output:
# Program to read student details and display a formatted marksheet
name = input("Enter Student Name: ")
roll = int(input("Enter Roll Number: "))
m1, m2, m3 = map(float, input("Enter marks of 3 subjects: ").split())
total = m1 + m2 + m3
percentage = total / 3
print("\n" + "=" * 35)
# Using f-string formatting (:.2f rounds float to 2 decimal places)
print(f"Student Name : {name}")
print(f"Roll Number : {roll}")
print(f"Total Marks : {total} / 300")
print(f"Percentage : {percentage:.2f}%")
print("=" * 35)
Sample Run:
Enter Student Name: Ananya Sharma
Enter Roll Number: 105
Enter marks of 3 subjects: 85 90 88
===================================
Student Name : Ananya Sharma
Roll Number : 105
Total Marks : 263.0 / 300
Percentage : 87.67%
===================================
View diagram · Figure 1.7: Three Ways to Format Output Strings in Python
💡 Exam Preparation Tips for DAVV BCA
- Always mention that
input()returns astrby default, soint(input())orfloat(input())is required for numeric input! - In any question on Output operations, always demonstrate the
sepandendkeyword arguments ofprint()along with f-strings (f"...").