Unit 2: Python fundamentals
Fundamentals of Computer and Programming in Python notes · PTU syllabus (PGCA1902)
On this page
- Unit summary
- History, features and applications of Python
- Installation and environment setup
- Keywords, identifiers, statements and indentation
- Variables, data types, type conversion, input and output
- Operators and expressions
- Decision making and loops
- Native data types: numbers
- Lists, tuples and dictionaries
- Sets
- Strings
- Mutable vs immutable objects
- Key terms
- Quick revision
- Important questions
Unit summary
Python is readable, versatile and one of the most widely used programming languages. This unit covers its history, features and applications, installation, keywords, identifiers, statements and indentation, variables, data types and conversion, input and output, operators and expressions, decision making and loops, and the native data types — numbers, lists, tuples, sets, dictionaries and strings.
After this unit you can
- Install Python and write programs with correct syntax and indentation
- Use variables, data types, conversions, input and output
- Write expressions and control structures
- Use numbers, lists, tuples, sets, dictionaries and strings
PTU syllabus topics
- History
- features and applications of Python
- installation and environment setup
- keywords
- identifiers
- statements
- indentation
- variables
- data types and conversion
- I/O functions
- operators and expressions
- control structures (decision making, loops)
- native data types — numbers
- lists
- tuples
- sets
- dictionaries
- strings
list
Yes, ordered
[3, 1, 2]
tuple
No, ordered
(10, 20)
set
Yes, unique, unordered
{1, 2, 3}
dict
Yes, key-value
{"id": 7}
str
No, sequence of characters
"hello"
Topic 1
History, features and applications of Python
Python was created by Guido van Rossum and released in 1991. It is interpreted, high-level, dynamically typed and object-oriented, with readable syntax that uses indentation instead of braces. Application areas: web development (Django, Flask), data science and machine learning (NumPy, pandas, scikit-learn), automation and scripting, desktop apps, game development and IoT.
Topic 2
Installation and environment setup
- 1
Download Python 3 from python.org (tick "Add python.exe to PATH" on Windows)
- 2
Verify with python --version in a terminal
- 3
Use the interactive shell (REPL) or IDLE for quick tests
- 4
Write scripts in an editor or IDE — VS Code, PyCharm, Jupyter
- 5
Install packages with pip install package-name
- 6
Optionally create a virtual environment: python -m venv env
- Modes: interactive mode (statements run one at a time at the >>> prompt) and script mode (a .py file run with python file.py).
Topic 3
Keywords, identifiers, statements and indentation
- Keywords: reserved words such as if, else, elif, for, while, def, return, class, import, try, except, lambda, True, False, None (35 in Python 3) — see them with import keyword; keyword.kwlist.
- Identifiers: names for variables, functions and classes; begin with a letter or underscore, may contain digits, are case-sensitive and cannot be keywords.
- Statements: simple (assignment, print) or compound (if, for, def); a long statement can continue on the next line inside brackets or with a backslash.
- Indentation: Python uses indentation (conventionally 4 spaces) instead of braces to mark blocks; inconsistent indentation raises IndentationError.
Topic 4
Variables, data types, type conversion, input and output
- Identifiers start with a letter or underscore and are case-sensitive; keywords (if, else, for, while, def, return, class, import, True, False, None …) are reserved.
| Data type | Example |
|---|---|
| int | 25 |
| float | 3.14 |
| complex | 2 + 3j |
| str | "SBS" |
| bool | True |
| list / tuple / dict / set | [1, 2] / (1, 2) / {"a": 1} / {1, 2} |
- Operators: arithmetic (+, −, ×, /, // floor division, % modulus, ** power), comparison, logical (and, or, not), membership (in, not in) and identity (is, is not).
- Type conversion:
int("5"),float(3),str(10). - Input/output:
name = input("Enter name: ")(always returns a string) andprint("Hello", name, sep=" ", end="\n").
Topic 5
Operators and expressions
- Arithmetic
- + − × (written with the asterisk) / // % and the double-asterisk power operator
- Comparison
- == != > < >= <=
- Logical
- and, or, not
- Assignment
- = += −= and others; walrus := assigns inside expressions
- Bitwise
- &, ^, ~, <<, >> and the bar for OR
- Membership
- in, not in
- Identity
- is, is not
Example
17 // 5 = 3 (floor division); 17 % 5 = 2; 2 to the power 10 = 1024; −7 // 2 = −4 because floor division rounds down.
- Precedence (high to low): parentheses, power, unary minus, multiplication and division, addition and subtraction, comparisons, not, and, or.
Topic 6
Decision making and loops
pythonn = int(input("Number: "))
if n % 2 == 0:
print("Even")
else:
print("Odd")
for i in range(1, 6): # 1 to 5
if i == 3:
continue # skip 3
print(i)
while True:
x = int(input())
if x < 0:
break # exit the looppassis a placeholder that does nothing;exit()(sys.exit) ends the program.range(start, stop, step)generates numbers up to but not including stop.
Exam tip
Python uses indentation to define blocks. Mixing tabs and spaces causes an IndentationError — always use 4 spaces.
python# if-elif-else, nested loop and loop-else
marks = 72
if marks >= 75: grade = "A"
elif marks >= 60: grade = "B"
else: grade = "C"
for n in range(2, 20):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else: # runs only if the inner loop did not break
print(n, end=" ") # prime numbersTopic 7
Native data types: numbers
- int (unlimited precision), float (64-bit double), complex (3 + 4j), bool (True, False — a subtype of int). Useful functions: abs(), round(), pow(), divmod(), and modules math, decimal, fractions, random.
Topic 8
Lists, tuples and dictionaries
List
Yes, ordered
marks = [70, 82, 65]
Tuple
No, ordered
point = (3, 4)
Dictionary
Yes, key-value
student = {"name": "Ana", "roll": 12}
Set
Yes, unique, unordered
{1, 2, 3}
pythonmarks = [70, 82, 65]
marks.append(90); marks.insert(0, 55); marks.remove(65); marks.sort()
print(max(marks), min(marks), sum(marks) / len(marks))
student = {"name": "Ana", "roll": 12}
student["course"] = "BCA"
for k, v in student.items():
print(k, v)Topic 9
Sets
pythona = {1, 2, 3, 4}; b = {3, 4, 5}
print(a | b, a & b, a - b, a ^ b) # union, intersection, difference, symmetric difference
a.add(9); a.discard(1)
print(3 in a, len(a))
unique = set([2, 2, 3, 3, 4]) # removes duplicates → {2, 3, 4}- Sets are unordered collections of unique, immutable items; frozenset is an immutable set.
Topic 10
Strings
Strings are immutable sequences of characters.
pythons = "Python Programming"
print(s[0], s[-1]) # P g
print(s[0:6]) # Python (slicing: start included, end excluded)
print(s[::-1]) # reversed string
print(s.upper(), s.lower(), s.split(), s.replace("Python", "C"))
print(len(s), s.find("Pro"), s.count("m"))
name, marks = "Ana", 91.5
print(f"{name} scored {marks:.1f}") # f-string formattingTopic 11
Mutable vs immutable objects
- Mutable objects (list, dict, set) can be changed in place; when passed to a function, changes inside the function affect the caller's object.
- Immutable objects (int, float, str, tuple) cannot be changed; "changing" creates a new object.
Example
def add(lst): lst.append(5) — calling add(a) changes list a. def inc(n): n += 1 does not change the caller's integer.
Key terms
- Indentation
- Leading spaces defining a block in Python
- Identifier
- Name given to a variable, function or class
- Type conversion
- Changing a value from one type to another
- List
- Ordered, mutable collection
- Dictionary
- Collection of key–value pairs
Quick revision
- History (Guido van Rossum, 1991), features, applications.
- Installation, pip, venv, interactive and script modes.
- Keywords, identifiers, statements, indentation.
- Data types, int(), float(), str(); input() returns a string; print with sep and end.
- Operators and precedence; if-elif-else, for, while, break, continue, pass, loop-else; numbers, lists, tuples, sets, dictionaries, strings.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.State four features of Python.
- Q2.What is the role of indentation in Python?
- Q3.Distinguish / and // operators.
- Q4.Distinguish a list and a tuple.
- Q5.How do you remove duplicates from a list?
- Q6.What does the else clause of a loop do?
Long-answer questions
- Q1.Explain the features and applications of Python.
- Q2.Explain Python data types and type conversion with examples.
- Q3.Explain the control structures of Python with programs.
- Q4.Explain lists, tuples, sets and dictionaries with their methods.
Stuck on this unit?
Message SBS on WhatsApp for help with Fundamentals of Computer and Programming in Python, or to ask about studying M.Sc IT at Synetic.
