0% found this document useful (0 votes)
4 views12 pages

Introduction To Python Environment

Python, created by Guido van Rossum in 1991, is a versatile programming language known for its readability and ease of use, making it popular in various IT domains such as web development, data science, and AI. It has evolved through three major versions, with Python 3.x being the current standard, and is characterized by features like dynamic typing, object-oriented design, and cross-platform compatibility. The document also outlines the installation process, development environments, syntax rules, and practical tasks for students to familiarize themselves with Python programming.

Uploaded by

kkiah2019
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Introduction To Python Environment

Python, created by Guido van Rossum in 1991, is a versatile programming language known for its readability and ease of use, making it popular in various IT domains such as web development, data science, and AI. It has evolved through three major versions, with Python 3.x being the current standard, and is characterized by features like dynamic typing, object-oriented design, and cross-platform compatibility. The document also outlines the installation process, development environments, syntax rules, and practical tasks for students to familiarize themselves with Python programming.

Uploaded by

kkiah2019
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

WHAT IS PYTHON AND WHY DOES IT MATTER IN IT?

History and Background of Python

Python was created by Guido van Rossum, a Dutch programmer, and was first released in 1991. The
name Python does not come from the snake, it was inspired by the British comedy television series
Monty Python's Flying Circus, which van Rossum was watching while developing the language. He
wanted the language to be fun to use, which is reflected in its clean, readable design philosophy.

Python has gone through three major versions:

• Python 1.x (1991): The original release — functional but limited

• Python 2.x (2000–2020): Widely adopted; officially retired on 1 January 2020

• Python 3.x (2008–present): The current standard; not backward-compatible with Python 2;
all new development uses Python 3

Characteristics of Python

Python is designed around a clear philosophy. The Zen of Python (accessible by typing import this in
the interpreter) summarises it with principles such as:

"Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex."

Key characteristics of Python:

Characteristic Explanation

Python code is executed line by line by the Python interpreter; no separate


Interpreted
compilation step is needed

High-level Python abstracts away low-level details such as memory management

Dynamically
Variable types are determined at runtime; no need to declare types explicitly
typed

Object-oriented Everything in Python is an object; supports classes, inheritance and encapsulation

Used for web development, data science, AI, scripting, automation, cybersecurity,
General-purpose
and more

Open-source Free to use, modify and distribute; backed by a large global community

Cross-platform Runs on Windows, macOS, and Linux without modification

Beginner-friendly Clean syntax resembles natural English; shorter programmes than Java or C++

Why Python for Students?

Python is not a niche academic language — it is the most widely used programming language in the
world as of 2024 (TIOBE Index, Stack Overflow Developer Survey). For an IT professional, Python
appears in virtually every major domain:

IT Domain Python Application

Web Development Django, Flask, FastAPI frameworks


IT Domain Python Application

Data Analytics Pandas, NumPy, data cleaning and exploration

Artificial Intelligence / ML TensorFlow, PyTorch, scikit-learn

Cybersecurity Penetration testing scripts, network scanning, forensics tools

AWS Lambda functions, Google Cloud Functions, infrastructure


Cloud Computing
automation

Database Programming SQLite3, SQLAlchemy, database connectivity and ORM

Automation and Scripting File management, scheduled tasks, system administration

IoT and Embedded


MicroPython on Raspberry Pi and microcontrollers
Systems

Network Programming Socket programming, network monitoring, protocol implementation

Python vs Other Programming Languages

The following comparison is useful for context:

Feature Python Java C++ JavaScript

Syntax complexity Very simple Moderate Complex Moderate

Lines of code for Hello


1 5+ 5+ 1–3
World

Memory management Automatic Automatic (GC) Manual Automatic

Typing Dynamic Static Static Dynamic

General / Data / Enterprise Systems / Web front-


Primary use in IT
AI applications Games end

Learning curve Gentle Steep Very steep Moderate

THE PYTHON PROGRAMMING ENVIRONMENT

Installing Python 3

Step-by-step installation (Windows):

1. Open a browser and navigate to [Link]/downloads

2. Click Download Python 3.11.x (or the latest stable version)

3. Run the installer

4. Critical: On the first screen, tick the checkbox "Add Python to PATH" before clicking Install
Now
5. Click Install Now

6. Verify installation: open Command Prompt and type:

2.2 Development Environments

You will encounter three main environments in this unit. Each has distinct advantages depending on
the task:

Option A — IDLE (Integrated Development and Learning Environment)

IDLE is Python's built-in development environment, installed automatically with Python. It is


lightweight and suitable for small programmes and learning exercises.

• Launch: search for IDLE in the Start menu (Windows) or type idle in terminal

• Features: syntax highlighting, basic auto-complete, integrated Python shell

• Best for: quick experiments, learning syntax, running short scripts

Option B — Visual Studio Code (VS Code)

VS Code is a free, professional-grade code editor developed by Microsoft. It is the recommended


environment for this unit.

Installation:

1. Download from [Link]

2. Install and open VS Code

3. Go to Extensions (Ctrl+Shift+X)

4. Search for and install Python (by Microsoft) and Pylance extensions

5. Open the Command Palette (Ctrl+Shift+P) and type: Python: Select Interpreter — choose
Python 3.11+

Key features useful in this unit:

• IntelliSense (auto-complete and suggestions)

• Integrated terminal for running Python files

• Integrated debugger with breakpoints

• Git integration for version control

• Jupyter Notebook support

Option C — Google Colaboratory (Google Colab)

Google Colab is a free, cloud-based Jupyter Notebook environment that requires no installation.
Students access it through a browser using a Google account.

• Access: [Link]

• Runs Python 3 in the cloud — no local installation needed

• Supports all standard Python libraries

• Free GPU access for data science work in later weeks

• Ideal for students without personal computers capable of running local Python
Comparison Summary:

Environment Installation Best For

IDLE Automatic with Python Quick experiments

VS Code Separate download Full development

Google Colab No installation Data science, library work

Interactive Mode vs Script Mode

Python can be used in two fundamentally different ways, and students must understand both:

Interactive Mode (the Python Shell / REPL)

REPL stands for Read-Evaluate-Print Loop. In interactive mode, Python reads one statement at a
time, evaluates it immediately, prints the result, and waits for the next input.

To start the Python REPL:

• In Command Prompt / Terminal: type python (Windows) or python3 (macOS/Linux)

• In IDLE: the shell opens automatically

• You will see the prompt >>> — type any Python expression and press Enter

python

>>> 2 + 3

>>> 10 * 4

40

>>> "Hello"

'Hello'

>>> 2 ** 8

256

Use interactive mode for:

• Testing a single expression or statement quickly

• Exploring how a function or operator works

• Checking the type of a value

• Quick arithmetic calculations

Script Mode

In script mode, you write a complete Python programme in a .py file, save it, and run the entire file at
once.

To run a Python script:

python [Link] # Windows


In VS Code: press F5 or click the Run button (▷) in the top-right corner.

Use script mode for:

• Writing programmes longer than a few lines

• All assignments, labs and projects in this unit

• Any programme you want to save and run again

Python Syntax Rules

Python's syntax is clean and minimal compared to other languages, but it has strict rules that
students must follow from the very first programme.

Rule 1 — Indentation is mandatory and meaningful

Unlike Java or C++ which use curly braces {} to define code blocks, Python uses indentation (spaces
or tabs). Incorrect indentation causes an Indentation Error and the programme will not run.

Standard indentation: 4 spaces per level (PEP 8 convention). Never mix tabs and spaces.

python

# Correct indentation

if True:

print("This is inside the if block")

print("So is this")

print("This is outside the if block")

# Incorrect — will cause IndentationError

if True:

print("Missing indentation") # ERROR

Rule 2 — Python is case-sensitive

Name, name, and NAME are three completely different identifiers in Python.

python

age = 25

Age = 30

AGE = 35

print(age, Age, AGE) # 25 30 35 — three separate variables

Rule 3 — Statements end at the end of the line

Python does not use semicolons to terminate statements (though they are allowed). Each statement
occupies its own line.

python

x = 10 # One statement per line (standard)


y = 20

z=x+y

x = 10; y = 20 # Allowed but not recommended (PEP 8 discourages this)

Rule 4 — Line continuation

Long statements can be broken across multiple lines using the backslash \ or by placing the
expression inside brackets:

python

# Using backslash

total = 100 + 200 + \

300 + 400

# Using parentheses (preferred)

total = (100 + 200 +

300 + 400)

Rule 5 — Python keywords are reserved

The following words have special meaning in Python and cannot be used as variable names:

False None True and as assert

async await break class continue def

del elif else except finally for

from global if import in is

lambda nonlocal not or pass raise

return try while with yield

Comments in Python

Comments are lines of code that Python ignores completely. They exist solely to explain the code to
human readers.

Single-line comments — use the hash symbol #:

python

# This is a single-line comment

print("Hello") # This comment is at the end of a line of code

Multi-line comments — Python has no dedicated multi-line comment syntax. Programmers use
either multiple # lines or a triple-quoted string (which Python evaluates but discards if it is not
assigned or used):

python
# This is line one of a comment

# This is line two of a comment

# This is line three of a comment

"""

This is a triple-quoted string used as a multi-line comment.

Python evaluates this but does not store it.

It is also used as a docstring when placed at the start

of a function, class, or module.

"""

Good commenting practice:

• Comment why the code does something, not what it does (the code itself shows what)

• Every programme you submit in this unit must have a header comment block:

python

# ============================================================

# Programme: hello_world.py

# Author: Alice Wanjiku

# Student ID: BIT-2024-001

# Date: 15 January 2026

# Description: My first Python programme

# ============================================================

The print() Function

print() is Python's built-in function for displaying output to the screen. It is the most frequently used
function in this unit and in Python generally.

Basic usage:

python

print("Hello, World!")

print("Welcome to Introduction to Python")

Printing multiple items — separate with commas; Python inserts a space between each:

python

print("My name is", "Alice", "and I am", 20, "years old")

# Output: My name is Alice and I am 20 years old

The sep parameter — change the separator between items (default is a space):
python

print("2025", "01", "15", sep="-")

# Output: 2025-01-15

print("Alice", "Bob", "Carol", sep=" | ")

# Output: Alice | Bob | Carol

The end parameter — change what is printed at the end of the line (default is newline \n):

python

print("Loading", end="")

print("...")

# Output: Loading...

print("Item 1", end=", ")

print("Item 2", end=", ")

print("Item 3")

# Output: Item 1, Item 2, Item 3

Escape sequences in strings:

Sequence Meaning Example

\n New line print("Line 1\nLine 2")

\t Horizontal tab print("Name:\tAlice")

\\ Literal backslash print("C:\\Users\\Alice")

\' Single quote inside single-quoted string print('It\'s fine')

\" Double quote inside double-quoted string print("She said \"hello\"")

Printing blank lines:

python

print() # Prints an empty line

print("") # Also prints an empty line

LAB 1: SETTING UP AND FIRST PYTHON PROGRAMMES

Objectives: Set up the Python development environment; write, save and run Python programmes;
practise syntax rules and the print() function.

Pre-Lab Requirements
Before the lab session, students should:

• Have Python 3.11+ downloaded from [Link] (or confirm Google Colab access)

• Have VS Code downloaded from [Link]

• Or Have a Google account for Google Colab access

Task 1 — Environment Setup and Verification

1. Install Python 3.11+ on your computer following the steps in Lecture 2 Section 2.1

3. Click on start on your computer and search for python, open it the installed python version.

4. You should see the >>> prompt. Try the following and record all outputs:

>>> 2 + 2

>>> 10 / 3

>>> 10 // 3

>>> 10 % 3

>>> 2 ** 10

>>> "Hello" + " " + "World"

4. Install VS Code and the Python extension. Create a new folder on your Desktop called
BIT2209_Python. Open this folder in VS Code (File > Open Folder).

5. Create a new file called setup_test.py and type:

python

print("Python is working!")

print("My name is: YOUR NAME HERE")

print("My student ID is: YOUR ID HERE")

Run the file using the Run button or F5. Take a screenshot of the output.

Task 2 — First Python Programme

Create a new file called student_card.py. Write a programme that prints a formatted student
identification card using only the print() function. The card must include:

• A top border using = characters (at least 40 characters wide)

• The university name centred on its line

• The programme name

• Your full name

• Your student ID number

• Your year of study

• The current academic year

• A bottom border matching the top


Expected output format (use your own details):

MOUNT KENYA UNIVERSITY

BSc Information Technology — Year 1

Name : Alice Wanjiku

Student ID : BIT-2024-001

Year : Year 1, Semester 1

Academic Yr : 2025/2026

Requirements:

• Use at least 8 print() statements

• Use the sep and end parameters in at least one print() statement each

• Include the programme header comment block at the top of the file

Task 3 — Syntax Practice and Error Correction

Part A — Trace the output. Without running the code, write down the exact output you expect from
each of the following print() statements. Then run them to verify:

python

print("Information", "Technology", sep="-")

print("Year", 1, sep="")

print("A", "B", "C", sep=" -> ", end=" -> END\n")

print("Line 1\nLine 2\nLine 3")

print("Name:\tAlice\nAge:\t20")

print("=" * 30)

Part B — Find and fix the errors. The following programme has 5 errors. Identify each error, state
what type of error it is (syntax, indentation, or logical), and write the corrected version:

python

# Student information programme

Print("Welcome to Python")

print("Student name: Alice)

print("Student ID:" "BIT-001")

print("Year: " + 1)

print("University: Mount Kenya University")

Task 4 — Explore the Interactive Interpreter

Using the Python interactive interpreter only (not a script file), complete the following explorations.
Record each command you typed and its output:
1. Use Python as a scientific calculator: compute the area of a circle with radius 7 using the
formula 3.14159 * 7 ** 2

2. Convert 37.5 degrees Celsius to Fahrenheit using the formula (37.5 * 9/5) + 32

3. Type import this and press Enter. Read the Zen of Python. Write down three principles that
you find most relevant to programming and explain each in one sentence.

4. Type help(print) and read the documentation for the print() function. Identify two
parameters you have not yet used and describe what they do.

5. Challenge: find out what print.__doc__ displays and explain in one sentence what __doc__
is.

CLASSWORK

Answer the following questions individually in your exercise book:

1. State three characteristics of Python and explain why each characteristic makes it suitable for
Information Technology professionals. (3 marks)

2. Distinguish between interactive mode and script mode in Python. Give one specific use case
where each is more appropriate. (4 marks)

3. The following Python code contains errors. Identify each error and write the corrected line:
(3 marks)

python

Print("Hello World")

print("My age is " + 20)

print("Python is fun")

4. Write a print() statement that produces the following output exactly, using the sep
parameter: (2 marks)

Kenya / Uganda / Tanzania / Rwanda

5. What will the following code display? Explain why: (3 marks)

python

print("A", end="")

print("B", end="")

print("C")

print("D")

ASSIGNMENT 1 (Released Week 2— Due End of Week 3)

Title: My Python Profile Programme

Purpose: To demonstrate competency in setting up the Python environment, applying Python syntax
rules, writing structured programmes, and using the print() function effectively.

Instructions:
Write a Python programme called [Link] that displays a comprehensive personal and academic
profile. The programme must meet all the following requirements:

Content requirements:

• Full name, student ID, programme of study, year, and university

• Your home county/city and country

• Three IT career goals (areas you want to work in after graduating)

• Three reasons why you chose to study Information Technology

• A simple ASCII art design or border that frames the output (created using print() and string
repetition)

• The current date written as a string (e.g., "15 January 2025")

Technical requirements:

• Must include the standard programme header comment block

• Must use the sep parameter in at least two print() statements

• Must use the end parameter in at least two print() statements

• Must use at least one escape sequence (\n, \t, \\, or \")

• Must use string repetition ("=" * 40) for at least one border or divider

• All output must be neatly aligned and professionally formatted

• Code must follow PEP 8 style guidelines — consistent indentation, meaningful spacing

Submission:

• File name: [Link]

• Submit via the LMS by the deadline stated on the LMS

• Late submissions: 10% deducted per day

You might also like