ACS101 · Programming Languages · Unit 4
Python Introduction
Unit Scope & Exam Weightage: This unit switches language from C to Python: Why Python — where it is used (AI, Data Science, Web, Automation), Python basics — variables, data types, print, input, operators, Python control flow — if/else, for loop, while loop, and Python functions — def, return, default arguments. No PYQ cluster is attached to this unit in the solutions file; the worked questions below are clearly labelled predictions derived from the exact syllabus topics. Expect one 7-mark program and one or two 2-mark definitions in a 2026-27 paper.
Front Page: Importance-Wise Topic Roadmap (Predicted from Syllabus)
| Priority | Topic (Exact Syllabus) | PYQs Asked | Marks Weightage | Tag |
|---|---|---|---|---|
| 1 | Python basics — variables / data types / print / input / operators | 0 genuine PYQs | predicted 7m + 2m | Predicted Program |
| 2 | Python control flow — if/else / for loop / while loop | 0 genuine PYQs | predicted 7m | Predicted Program |
| 3 | Python functions — def / return / default arguments | 0 genuine PYQs | predicted 7m + 2m | Predicted Program |
| 4 | Why Python — where it is used (AI, Data Science, Web, Automation) | 0 genuine PYQs | predicted 2m | Predicted Theory |
| 5 | Data Science / and automation — same syntax, more power, less boilerplate | 0 genuine PYQs | integrated in #1, #4 | Real Connect |
| 6 | default arguments Real connect: Python is #1 in AI/ML | 0 genuine PYQs | integrated in #3 | Real Connect |
2-Hour Last-Night Survival Checklist:
- No semicolons, no braces: Python blocks are marked by indentation (four spaces). A missing colon after
if,for,whileordefis the most common syntax error. - Input is always text:
input()returns astr; wrap withint()orfloat()before arithmetic. Write this line explicitly in every program. print()separator:print(a, b, sep="-")controls spacing;end=""suppresses the newline. Useful in pattern questions.- Default argument rule: parameters with defaults come after parameters without defaults:
def si(p, r, t=1):. The default is used only when the caller omits that argument. - Range end is exclusive:
range(1,6)yields1,2,3,4,5;range(5)yields0..4. State this in any trace question.
1. Why Python — Where It Is Used
Python is a high-level, interpreted, dynamically typed language with clean syntax. Its design goal is readable code with less boilerplate than C or Java, which is why the same short program can express a data pipeline, a web route, or a model-training loop.
| Domain | Typical Python use | Concrete library/example |
|---|---|---|
| AI / ML | Model definition and training | TensorFlow/PyTorch models built as Python classes |
| Data Science | Cleaning, analysing, visualising data | pandas DataFrame, NumPy arrays, Matplotlib plots |
| Web | Server-side routes and APIs | Flask @app.route('/marks') |
| Automation | File renaming, report generation, scraping | os, shutil, requests scripts |
| Engineering reports | Plotting and numerical work | NumPy + Matplotlib, later in Unit 5 |
C vs Python (2-mark comparison): C is compiled, statically typed, manually memory-managed and uses braces/semicolons; Python is interpreted/bytecode-executed, dynamically typed, garbage-collected and uses indentation. C is chosen for embedded firmware and OS kernels; Python is chosen for AI/ML and automation because development is faster.
%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart LR
A["Python source .py"] --> B["Bytecode compile"]
B --> C["Python Virtual Machine"]
C --> D["Program output"]
A --> E["AI / Data Science"]
A --> F["Web / Automation"]
Examiner Tip: For “Why Python?”, give three named domains from the syllabus (AI, Data Science, Web, Automation) and one concrete reason each (libraries, readable syntax, rapid development). Do not merely write “easy language”.
2. Python Basics: Variables, Data Types, print, input, Operators
Variable: a name bound to an object; no type declaration is needed. type(x) reveals the inferred type. Python is dynamically typed: the same name can later refer to a different type.
| Type | Literal example | type() result |
Notes |
|---|---|---|---|
| Integer | 85 |
int |
Arbitrary precision |
| Float | 85.5 |
float |
Double precision |
| String | "Asha" |
str |
Immutable sequence |
| Boolean | True |
bool |
Subclass of int; True == 1 |
| None | None |
NoneType |
Absence of value |
roll = 21 # int
name = "Asha" # str
marks = 88.5 # float
passed = True # bool
print(name, "rolled", roll, "scored", marks, sep=" | ")
age = int(input("Enter age: ")) # input() gives str; convert!
print("Next year:", age + 1)
2.1 Operators
| Category | Operators | Example | Result |
|---|---|---|---|
| Arithmetic | + - * / // % ** |
7 // 2, 7 % 2, 2 ** 3 |
3, 1, 8 |
| Comparison | == != < <= > >= |
7 == 7.0 |
True |
| Logical | and or not |
True and False |
False |
| Assignment | = += -= *= /= |
x += 3 |
adds 3 |
| Membership | in, not in |
"a" in "cat" |
True |
| Identity | is, is not |
x is None |
object identity |
Division distinction: / always returns float (7/2 = 3.5), while // returns floor quotient (7//2 = 3). This differs from C, where 7/2 is integer 3.
a, b = 7, 2
print(a / b, a // b, a % b) # 3.5 3 1
3. Python Control Flow: if/else, for, while
Control flow decides which statements run and how many times. Python uses a colon and an indented block; there is no switch in basic Python—if/elif/else performs the same role.
marks = int(input("Marks: "))
if marks >= 80:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "F"
print("Grade:", grade)
| Loop | Form | Typical use | Execution count |
|---|---|---|---|
for |
for i in range(n): |
known iteration count | n times (0..n-1) |
for over sequence |
for ch in "ABC": |
iterate characters/items | length of sequence |
while |
while condition: |
condition-driven | until condition false |
break |
inside a loop | exit immediately | — |
continue |
inside a loop | skip current iteration | — |
# sum of first 5 natural numbers with for
total = 0
for i in range(1, 6): # 1,2,3,4,5
total += i
print(total) # 15
# same with while
i, total = 1, 0
while i <= 5:
total += i
i += 1
print(total) # 15
%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
A[Read marks] --> B{marks >= 80?}
B -->|yes| C[A]
B -->|no| D{marks >= 60?}
D -->|yes| E[B]
D -->|no| F{marks >= 40?}
F -->|yes| G[C]
F -->|no| H[F]
C --> I[Print grade]
E --> I
G --> I
H --> I
Examiner Tip: Trace questions reward writing the exact sequence produced by range. For range(2, 10, 3) write 2, 5, 8 before answering; the stop value 10 is not included.
4. Python Functions: def, return, Default Arguments
Function: a named reusable block defined with def name(parameters):. return sends a value back; if omitted, Python returns None. A default argument is used when the caller supplies no value for that parameter.
def simple_interest(principal, rate, time=1):
si = principal * rate * time / 100
return si
print(simple_interest(10000, 8)) # 800.0 (time = 1)
print(simple_interest(10000, 8, 2)) # 1600.0
| Rule | Correct | Wrong |
|---|---|---|
| Defaults after required params | def f(a, b=2): |
def f(a=2, b): |
| Colon and indentation | def f(): then indented body |
def f() |
| Call with keyword | f(b=5, a=1) |
positional mismatch silently changes meaning |
| Multiple returns | return min_v, max_v (tuple) |
two separate return statements expected |
Scope note: variables assigned inside a function are local by default; use global x only when intentionally modifying a module-level name. Parameters are passed by object reference—rebinding inside the function does not change the caller's variable, but mutating a list does.
5. Real Connect: Same Syntax, More Power, Less Boilerplate
| Task | C | Python |
|---|---|---|
printf("%d\n", x); |
print(x) |
|
| Read int | scanf("%d", &x); |
x = int(input()) |
| Swap | needs temp or bitwise trick |
a, b = b, a |
| Loop 0..4 | for(i=0;i<5;i++) |
for i in range(5): |
| Sum a list | manual loop with index | sum(marks) |
Python's concision is why the same student who learned loops in C can write a Data Science pipeline in the next unit with the same control-flow ideas. This is the “same syntax, more power, less boilerplate” link stated in the syllabus.
6. Predicted Exam-Ready Questions (Solved — Not Verbatim PYQs)
Predicted Q1 (7 Marks | Variables, input, Operators)
Q (predicted from “Python basics — variables, data types, print, input, operators”): Write a Python program that reads two integers, prints their sum, integer quotient, remainder and power using appropriate operators. Convert the input correctly.
Solution:
a = int(input("First number: "))
b = int(input("Second number: "))
print("Sum:", a + b)
print("Integer quotient:", a // b)
print("Remainder:", a % b)
print("Power:", a ** b)
print("True division:", a / b)
For a=7, b=2 the output is Sum: 9, Integer quotient: 3, Remainder: 1, Power: 49, True division: 3.5. The conversion int(input(...)) is essential because input() returns a string.
Predicted Q2 (7 Marks | if/elif/else, for, range)
Q (predicted from “Python control flow — if/else, for loop, while loop”): Write a Python program that reads five marks, prints each mark with its grade using if/elif/else inside a for loop, and counts how many students passed (marks ≥ 40).
Solution:
passed = 0
for i in range(5):
m = float(input(f"Marks of student {i+1}: "))
if m >= 80:
g = "A"
elif m >= 60:
g = "B"
elif m >= 40:
g = "C"
else:
g = "F"
if m >= 40:
passed += 1
print(f"Student {i+1}: {m:.1f} -> {g}")
print("Passed:", passed)
range(5) produces 0,1,2,3,4; i+1 is used only for display. The if chain tests high marks first so that a value like 85 is not incorrectly graded B.
Predicted Q3 (7 Marks | Function, return, Default Argument)
Q (predicted from “Python functions — def, return, default arguments”): Define a function grade(marks, pass_mark=40) that returns "Pass" or "Fail". Call it once with the default and once with pass_mark=50, and print both results.
Solution:
def grade(marks, pass_mark=40):
if marks >= pass_mark:
return "Pass"
return "Fail"
print(grade(45)) # Pass (uses 40)
print(grade(45, 50)) # Fail (caller overrides)
print(grade(55, pass_mark=50)) # Pass (keyword call)
The default argument must appear after the required parameter. The function returns a str; the caller decides how to display it.
Predicted Q4 (2 Marks | Why Python)
Q (predicted from “Why Python — where it is used (AI, Data Science, Web, Automation)”): Name two application areas of Python and give one reason why each prefers Python over C.
Solution: AI/ML: frameworks such as TensorFlow and PyTorch expose Python APIs, so models are written as short Python classes with library-backed numerical code. Automation: Python's os, shutil and requests modules perform file/system/network tasks in a few lines without manual compilation or memory management. Both benefit from readable syntax and a large standard library.
7. Practice Questions (Self-Test)
- (2 Marks) What is the output of
print(7/2, 7//2, 7%2)? (Ans:3.5 3 1.) - (7 Marks) Write a
whileloop that prints multiples of 3 from 3 to 15 and counts them. - (7 Marks) Write a function
def stats(a, b, c):that returns minimum, maximum and average using multiple return values. - (2 Marks) Why must
int()be used withinput()before adding two numbers? - (7 Marks) Write a Python program that prints a right-angled triangle of
*with 5 rows using nestedforloops.