Unit 2 of 4 · M.Sc IT Sem 1

Unit 2: Python fundamentals

Fundamentals of Computer and Programming in Python notes · PTU syllabus (PGCA1902)

6 min read11 topics10 exam questions
On this page
  1. Unit summary
  2. History, features and applications of Python
  3. Installation and environment setup
  4. Keywords, identifiers, statements and indentation
  5. Variables, data types, type conversion, input and output
  6. Operators and expressions
  7. Decision making and loops
  8. Native data types: numbers
  9. Lists, tuples and dictionaries
  10. Sets
  11. Strings
  12. Mutable vs immutable objects
  13. Key terms
  14. Quick revision
  15. 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
1

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.

Example

Why Python is popular: a data analyst can read a CSV, clean it with pandas and plot a chart in about ten lines. The same language runs web servers (Django), automates tasks and trains machine learning models.

Exam tip

Features: simple syntax, interpreted, dynamically typed, portable, large standard library and open source.

2

Topic 2

Installation and environment setup

After installing Python 3 (and adding it to PATH), you can run code in the interactive shell (REPL), in IDLE, in an IDE such as VS Code or PyCharm, or in Jupyter notebooks. Extra packages are installed with pip.

ProcessSetting up Python
  1. 1

    Download Python 3 from python.org (tick "Add python.exe to PATH" on Windows)

  2. 2

    Verify with python --version in a terminal

  3. 3

    Use the interactive shell (REPL) or IDLE for quick tests

  4. 4

    Write scripts in an editor or IDE — VS Code, PyCharm, Jupyter

  5. 5

    Install packages with pip install package-name

  6. 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).

Example

Checking the setup: python --version prints the installed version; pip install pandas adds a package; saving print("Hello SBS") as hello.py and running python hello.py prints Hello SBS.

Exam tip

Tick 'Add python.exe to PATH' during Windows installation, or the python command will not be found.

3

Topic 3

Keywords, identifiers, statements and indentation

Python uses indentation (usually 4 spaces) instead of braces to mark blocks; wrong indentation gives an IndentationError.

  • 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.

Example

Indentation decides meaning: if marks >= 40: followed by an indented print("Pass") prints only when the condition is true. If the print line is not indented, Python raises an IndentationError.

Exam tip

Python is case-sensitive: Total and total are different identifiers.

4

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 typeExample
int25
float3.14
complex2 + 3j
str"SBS"
boolTrue
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) and print("Hello", name, sep=" ", end="\n").

Example

input() returns a string: a = input("Enter a number: ") with 5 entered gives a + a = "55". Converting with a = int(input(...)) gives a + a = 10. print(f"Total = {a * 2}") uses an f-string for formatted output.

Exam tip

Always convert input with int() or float() before doing arithmetic.

5

Topic 5

Operators and expressions

Key termsPython operators
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.
6

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 loop
  • pass is 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 numbers
7

Topic 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.

Example

Number behaviour: 7 / 2 gives 3.5 (true division), 7 // 2 gives 3 (floor division), 7 % 2 gives 1, 2 ** 10 gives 1024, and 0.1 + 0.2 gives 0.30000000000000004 because of floating-point representation.

Exam tip

Use round() or the decimal module when exact decimal results matter, such as money.

8

Topic 8

Lists, tuples and dictionaries

ComparisonPython collections
Mutable?
Example

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)

Example

Choosing a collection: marks that change → list [70, 82, 65]; a fixed date → tuple (17, 11, 2026); student records looked up by roll number → dictionary {101: "Asha", 102: "Ravi"}, where students[101] gives "Asha".

Exam tip

Lists are mutable, tuples are immutable, dictionaries map keys to values.

9

Topic 9

Sets

A set is an unordered collection of unique elements, useful for removing duplicates and for membership tests and set operations.

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.

Example

Removing duplicates: set([3, 1, 3, 2, 1]) gives {1, 2, 3}. For a = {1, 2, 3, 4} and b = {3, 4, 5}: union {1, 2, 3, 4, 5}, intersection {3, 4}, difference a − b = {1, 2}, symmetric difference {1, 2, 5}.

Exam tip

Sets have no index — s[0] gives an error.

10

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 formatting

Example

String operations: for s = "Python Programming", s[0:6] is "Python", s[-1] is "g", s.upper() is "PYTHON PROGRAMMING", s.split() is ['Python', 'Programming'], and len(s) is 18.

Exam tip

Strings are immutable — methods return a new string instead of changing the original.

11

Topic 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

  1. Q1.State four features of Python.
  2. Q2.What is the role of indentation in Python?
  3. Q3.Distinguish / and // operators.
  4. Q4.Distinguish a list and a tuple.
  5. Q5.How do you remove duplicates from a list?
  6. Q6.What does the else clause of a loop do?

Long-answer questions

  1. Q1.Explain the features and applications of Python.
  2. Q2.Explain Python data types and type conversion with examples.
  3. Q3.Explain the control structures of Python with programs.
  4. 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.

Planning your M.Sc IT in Ludhiana? See the M.Sc IT at SBS →

WhatsApp us