Docsity

Python Programming for Beginners: Complete Undergraduate Notes, Practical Examples and Exa, Lecture notes of Computer Programming

Partial preview of the text

Download Python Programming for Beginners: Complete Undergraduate Notes, Practical Examples and Exa and more Lecture notes Computer Programming in PDF only on Docsity!

PYTHON PROGRAMMING

A Complete Beginner-to-Undergraduate Study Guide

Detailed notes • Practical code examples • Exercises • Model answers

For Computer Science, BBIT, Information Technology and related programmes

How to Use These Notes

This guide introduces Python programming from the foundations and gradually develops the ability to design, write,

test and explain programs. Type and run the examples yourself, modify them, and attempt the exercises before

reading the model answers.

 Beginners should study the topics in order and practise each example.

 For examinations, revise definitions, trace program output and practise writing short programs.

 Use Python 3 with IDLE, Visual Studio Code, PyCharm or another trusted Python environment.

Learning Outcomes

 Explain programming concepts and Python features.

 Use variables, data types, operators, input and output.

 Apply selection, loops and functions.

 Process strings and built-in data structures.

 Read and write files and handle exceptions.

 Understand introductory object-oriented programming.

 Design algorithms, test programs and debug errors.

Contents

 Introduction to Programming and Python

 Setting Up Python and First Program

 Variables, Constants and Data Types

 Operators and Expressions

 Input and Output

 Selection Statements

 Loops and Iteration

 Functions and Modules

 Strings

 Lists, Tuples, Sets and Dictionaries

 File Handling

 Errors and Exception Handling

 Object-Oriented Programming

 Algorithms and Flowcharts

 Testing, Good Practice and Secure Coding

 Practical Mini-Projects

 Exam Questions and Model Answers

 Practical Exercises and Solutions

 Glossary and References

1. Introduction to Programming and Python 1.1 Computer programming

A computer program is an ordered set of instructions that tells a computer how to perform a task. Programming is the

process of analysing a problem, designing a solution, writing instructions in a programming language, testing the

result and maintaining it.

2.1 First program print("Hello, World!")

Save the file as hello.py and run it with python hello.py. On some systems the command is python3 hello.py. The

output is Hello, World!

2.2 Understanding the code

 print() is a built-in function that displays information.

 Text inside quotation marks is a string literal.

 Parentheses contain the value passed to the function.

2.3 Comments and indentation

A comment explains code to human readers and begins with #. Python uses indentation to identify blocks of code;

four spaces per indentation level is the usual convention.

Display a welcome message\nprint("Welcome to Python")\n\nif 5 > 2:\n print("Five is greater than two")

3. Variables, Constants and Data Types

A variable is a name that refers to a value or object. Assignment creates or reassigns a variable.

student_name = "Amina"\nage = 20\ncourse = "BBIT"

Names may contain letters, digits and underscores, but cannot begin with a digit. Names are case-sensitive and

reserved keywords cannot be used as variable names. Use meaningful names such as total_marks.

3.1 Constants

A constant is a value intended not to change. Python does not enforce constants with a special declaration keyword;

uppercase names are used by convention.

TAX_RATE = 0.16\nPI = 3. 3.2 Common data types Type Meaning Example int Whole number count = 12 float Decimal number price = 45. str Text name = 'Brian' bool True or False active = True list Ordered, mutable collection marks = [70, 65, 82] tuple Ordered, immutable collection point = (4, 7) set Unique elements codes = {1, 2, 3} dict Key-value mapping person = {'name':'Ali'} NoneType No value result = None 3.3 Type checking and conversion age = 21\nprint(type(age))\nage_text = "19"\nage = int(age_text)\nheight = float("1.72")\nprint(age + 1)

type() checks a value's type. Common conversion functions include int(), float(), str() and bool(). Conversion may

fail: int('hello') raises ValueError.

4. Operators and Expressions

An operator performs an operation on one or more values. An expression combines values and operators to produce a

result.

Category Operators Purpose Arithmetic + - * / Basic calculations. Floor division // Division rounded down. Modulus % Remainder after division. Exponentiation ** Power calculation. Comparison == != > < >= <= Compares values; result is Boolean. Logical and, or, not Combines or reverses conditions. Assignment = += -= *= /= Assigns or updates values. Membership in, not in Checks membership in a collection. Identity is, is not Checks whether references identify the same object. a = 17\nb = 5\nprint(a + b) # 22\nprint(a // b) # 3\nprint(a % b) # 2\nprint(a ** 2) # 289

Operator precedence determines evaluation order. Use parentheses to make the intended order clear: answer = (4 + 2)

5. Input and Output 5.1 Output with print() name = "Lina"\nprint("Welcome", name)\nprint("A", "B", "C", sep="-")

print() displays values. Its sep parameter controls the separator between values, while end controls what is printed at

the end.

5.2 Input with input() name = input("Enter your name: ")\nprint("Hello", name)

input() returns text, even when a user types digits. Convert input to a number before performing arithmetic.

first = int(input("First number: "))\nsecond = int(input("Second number: "))\nprint("Total:", first + second) 5.3 Formatted strings name = "Lina"\nmarks = 84\nprint(f"{name} scored {marks} marks.")

6. Decision-Making and Selection

Selection allows a program to choose which instructions to execute according to a condition.

6.1 if and if-else number = 8\nif number % 2 == 0:\n print("Even")\nelse:\n print("Odd") 6.2 if-elif-else marks = 73\nif marks >= 70:\n grade = "A"\nelif marks >= 60:\n grade = "B"\nelif marks >= 50:\n grade = "C"\nelse:\n grade = "Below C"\nprint(grade)

Conditions are evaluated from top to bottom. The first true branch runs. Nested selection means placing one decision

structure inside another.

6.3 Common errors

 Using = instead of == for comparison.

 Forgetting the colon after if, elif or else.

 Using inconsistent indentation.

 Placing overlapping grade conditions in the wrong order.

message = "Computer Science"\nprint(message[0]) # C\nprint(message[0:8]) # Computer\nprint(len(message))

Indexing accesses a character. Positive indexes begin at zero; negative indexes count from the end. Slicing uses

text[start:stop:step], with the stop position excluded.

Method Purpose Example lower() Lowercase text 'HELLO'.lower() upper() Uppercase text 'hello'.upper() strip() Remove surrounding whitespace ' hi '.strip() replace() Replace text 'cat'.replace('c','b') split() Split into a list 'a,b'.split(',') join() Join strings '-'.join(['a','b']) find() Find position or return -1 'python'.find('t') startswith() Check prefix 'python'.startswith('py') full_name = " Amina Otieno "\nclean_name = full_name.strip().title()\nprint(clean_name)

10. Lists, Tuples, Sets and Dictionaries

A data structure organises data so that it can be stored, accessed and processed effectively.

Structure Ordered? Mutable? Duplicates? Typical use List Yes Yes Yes Changeable sequence. Tuple Yes No Yes Fixed sequence. Set No positional order Yes No Unique values and set operations. Dictionary Insertion order preserved Yes Keys unique Key-value records. 10.1 Lists

A list is an ordered, mutable collection. It can contain different types, although consistent element types often make

processing clearer.

marks = [72, 65, 81, 90]\nprint(marks[0])\nmarks.append(76)\nmarks[1] = 68\nprint(marks)

Common methods: append() adds one item; extend() adds multiple items; insert() adds at a position; remove() deletes

a matching value; pop() removes and returns an item; sort() sorts in place; reverse() reverses in place; count() counts

occurrences.

10.2 List traversal and comprehensions marks = [72, 65, 81, 90]\ntotal = 0\nfor mark in marks:\n total += mark\naverage = total / len(marks)\nprint(total, average) squares = [n ** 2 for n in range(1, 6)]\nevens = [n for n in range(1, 11) if n % 2 == 0] 10.3 Tuples

A tuple is an ordered, immutable collection.

coordinates = (10, 20)\nprint(coordinates[0])\nsingle_item = (5,) 10.4 Sets

A set stores unique elements and supports union, intersection and difference.

first = {1, 2, 3, 4}\nsecond = {3, 4, 5}\nprint(first | second) # union\nprint(first & second) # intersection\nprint(first - second) # difference 10.5 Dictionaries

A dictionary stores key-value pairs. Keys are unique and retrieve associated values.

student = {"name": "Amina", "course": "BBIT", "year": 2}\nprint(student["name"])\nstudent["year"] = 3\nstudent["email"] =

"[email protected]"\nprint(student.get("phone", "Not provided"))

11. File Handling

File handling allows a program to store data permanently and retrieve it later. open() opens a file and file methods

read or write its contents.

Mode Meaning r Read an existing file. w Write; creates or replaces contents. a Append to the end. x Create a new file; fails if it exists. b Binary mode modifier. t Text mode modifier; default. 11.1 Writing and reading with open("notes.txt", "w", encoding="utf-8") as file:\n file.write("Learn Python step by step.\n")\n\nwith open("notes.txt", "r", encoding="utf-8") as file:\n content = file.read()\n print(content)

The with statement closes the file automatically when the block finishes. readline() reads one line; readlines() returns

a list of lines. For large files, process one line at a time.

11.2 File safety

 Check file paths and handle missing-file errors.

 Use an appropriate encoding such as UTF-8.

 Avoid write mode if existing content must be preserved.

 Do not process untrusted files without considering their contents.

12. Errors, Exceptions and Debugging Error type Explanation Example Syntax error Code breaks Python grammar. Missing parenthesis. Runtime exception Problem occurs during execution. Division by zero. Logical error Program runs but result is wrong. Using addition instead of multiplication. 12.1 try and except try:\n age = int(input("Enter age: "))\n print("Next year:", age + 1)\nexcept ValueError:\n print("Please enter a whole number.")

An exception interrupts normal program execution. try and except allow the program to respond to expected failures.

12.2 else and finally

else runs when the try block has no exception. finally runs whether an exception occurred or not and is useful for

cleanup.

try:\n number = int("25")\nexcept ValueError:\n print("Invalid number")\nelse:\n print("Converted:", number)\nfinally:\n print("Finished") 12.3 Debugging

 Read the full error message and inspect the reported line.

 Check variable values using print() or a debugger.

 Test one small part at a time.

 Use normal, boundary and invalid test values.

 After fixing a defect, rerun earlier tests.

5. Test normal, boundary and invalid cases.

6. Debug and improve readability and efficiency.

7. Document and maintain the solution.

15. Testing, Good Practice and Secure Coding

Testing checks whether a program behaves as expected and helps identify defects.

Testing type Purpose Unit Tests an individual function or component. Integration Checks whether combined components work together. System Tests the complete application. Acceptance Checks whether user or business requirements are met. Regression Checks that changes have not broken existing behaviour. 15.1 Test data Type Example for age input Valid 21 Boundary 0 or maximum allowed age, depending on rules Invalid abc when a number is required Empty No value entered 15.2 Good programming practices

 Use meaningful names and consistent indentation.

 Keep functions focused on one task.

 Comment complex reasoning rather than obvious statements.

 Validate inputs and handle expected exceptions.

 Avoid unnecessary duplication and use version control.

15.3 Introductory secure coding

 Never hard-code passwords, secret keys or access tokens.

 Validate input and use safe APIs for files, databases and web services.

 Keep Python and dependencies updated from trusted sources.

 Apply least privilege: grant a program only the permissions it needs.

 Do not execute unknown code or install packages from untrusted sources.

 Protect personal information and never log secrets.

Security depends on the complete system, not just the programming language. A Python application can still be

insecure if it mishandles input, credentials, permissions or confidential data.

16. Practical Mini-Projects 16.1 Student marks calculator

Objective: accept three marks, calculate the total and average, and display a performance category.

m1 = float(input("Mark 1: "))\nm2 = float(input("Mark 2: "))\nm3 = float(input("Mark 3: "))\ntotal = m1 + m2 + m3\naverage = total / 3\nprint(f"Total: {total:.1f}")\nprint(f"Average: {average:.1f}")\nif average >= 70:\n print("Excellent")\nelif average >= 50:\n print("Satisfactory")\nelse:\n print("Needs improvement")

Extension: validate marks against the permitted range, handle non-numeric input and save results to a file.

16.2 Shopping bill item = input("Item: ")\nprice = float(input("Price: "))\nquantity = int(input("Quantity: "))\ntotal = price * quantity\nprint(f"{item}: {quantity} x {price:.2f}")\nprint(f"Total: {total:.2f}") 16.3 Number guessing game secret = 7\nguess = None\nwhile guess != secret:\n guess = int(input("Guess (1-10): "))\n if guess < secret: print("Too low")\n elif guess > secret: print("Too high")\n else: print("Correct!") 16.4 Contact book contacts = {}\ncontacts["Amina"] = "0712345678"\ncontacts["Brian"] = "0798765432"\nname = input("Search name: ") \nprint(contacts.get(name, "Contact not found"))

17. Examination Revision Questions and Model Answers

1. Define programming. (2 marks)

Programming is the process of designing and writing instructions that a computer executes to perform tasks or solve

problems.

2. State four features of Python. (4 marks)

Python has readable syntax, is high-level, is available across major platforms and has a large standard library. It also

supports multiple programming paradigms.

3. Differentiate between a compiler and an interpreter. (4 marks)

A compiler generally translates source code into another form before execution. An interpreter executes instructions

through a runtime environment. Actual language implementations may combine compilation and interpretation

stages.

4. Distinguish between a variable and a constant. (4 marks)

A variable is a named reference that may be reassigned. A constant is intended to remain unchanged; Python indicates

this by convention, commonly using uppercase names.

5. Differentiate = and ==. (2 marks)

= assigns a value; == compares two values for equality and returns True or False.

6. Differentiate a for loop and a while loop. (4 marks)

A for loop iterates over items in an iterable. A while loop repeats while a condition remains true. A for loop is

suitable for processing a collection; while is useful when repetition depends on a condition.

7. Define a function and state two benefits. (4 marks)

A function is a named reusable block of code that performs a task. It reduces repetition and divides a program into

manageable, testable components.

8. Distinguish between a list and a tuple. (4 marks)

Both are ordered and may contain duplicates. A list is mutable; a tuple is immutable.

9. Explain exception handling. (4 marks)

It is responding to runtime errors using constructs such as try and except. It allows expected failures to be handled

and useful messages to be displayed.

10. State four characteristics of a good algorithm. (4 marks)

It has clearly defined inputs, produces outputs, uses unambiguous steps, terminates in finite time and uses effective

operations.

Class Blueprint for creating objects. Debugging Finding and correcting defects. Exception Event that interrupts normal execution. Expression Values and operators that produce a result. Function Reusable named block of code. IDE Integrated Development Environment. Iteration Repeating instructions. List Ordered, mutable Python collection. Module Python file that can be imported. Object Instance of a class. Parameter Variable in a function definition. Pseudocode Language-independent description of an algorithm. String Sequence of text characters. Syntax Rules for valid statements. Variable Name referring to a value or object. Official references

 Python Software Foundation, Python 3 Documentation: https://docs.python.org/3/

 The Python Tutorial: https://docs.python.org/3/tutorial/

 Python Built-in Functions: https://docs.python.org/3/library/functions.html

 Python Standard Library: https://docs.python.org/3/library/

 Python Packaging User Guide: https://packaging.python.org/

 PEP 8 – Style Guide for Python Code: https://peps.python.org/pep-0008/

Python evolves over time. Consult the official Python 3 documentation for version-specific behaviour. The examples

in this guide are introductory and should be run and adapted by the learner.

Conclusion

Python programming develops the ability to translate problems into logical, testable instructions. A strong foundation

requires more than memorising syntax: practise tracing code, writing small programs, testing unusual inputs and

explaining why a solution works. Progress from basic statements to functions, collections, files and object-oriented

concepts, then build projects that solve practical problems.