0% found this document useful (0 votes)
11 views57 pages

Python Ss1 Notes

Uploaded by

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

Python Ss1 Notes

Uploaded by

chinoprecious29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

TEC PYTHON COURSE:

BASICS OF PYTHON
Week 1-2: Introduction to Python

Definition and Importance of Python

Python is a high-level, interpreted programming language known for its


simplicity and readability. It was created by Guido van Rossum and first
released in 1991. Python's design philosophy emphasizes code readability
and simplicity, making it an excellent choice for beginners and experienced
programmers alike.

Importance of Python:

- Versatility: Python can be used for web development, data analysis,


machine learning, automation, scientific computing, and more.

- Readability: Python's syntax is clear and easy to understand, which reduces


the learning curve for new programmers.

- Community Support: Python has a large and active community, providing


extensive libraries, frameworks, and tools.

- Cross-Platform: Python runs on various operating systems, including


Windows, macOS, and Linux.

Installing Python and Setting Up the Development Environment

1. Download and Install Python:

- Visit the official Python website: (https://www.python.org/)

- Download the latest version of Python for your operating system.

- Run the installer and follow the instructions. Make sure to check the box
that says "Add Python to PATH" during installation.

2. Verify Installation:

- Open a terminal or command prompt.


- Type `python --version` and press Enter. You should see the installed
Python version.

3. Install an Integrated Development Environment (IDE):

- IDLE: Python's built-in IDE, which comes with the Python installation.

-VS Code: A popular, free code editor with Python support. Download from
(https://code.visualstudio.com/).

- PyCharm: A powerful IDE for Python development. Download from


(https://www.jetbrains.com/pycharm/).

Writing and Running Your First Python Program

1. Open Your IDE:

- Launch your chosen IDE (IDLE, VS Code, or PyCharm).

2. Create a New Python File:

- In your IDE, create a new file and save it with a `.py` extension (e.g.,
`hello.py`).

3. Write Your First Python Program:

- Type the following code into your new file:

```python

print("Hello, World!")

```

4. Run Your Python Program:

- In IDLE: Press `F5` or go to `Run > Run Module`.

- In VS Code: Right-click the file and select `Run Python File in Terminal`.

- In PyCharm: Right-click the file and select `Run 'hello'`.


You should see the output `Hello, World!` displayed in the terminal or
console.

Illustrations and Examples

-Example Code:

```python

# This is a comment

print("Hello, World!") # This prints a message to the screen

```

- Explanation:

- `# This is a comment`: Comments are ignored by the Python interpreter


and are used to explain the code.

- `print("Hello, World!")`: The `print()` function outputs the specified


message to the screen.

Quiz and Exercises

1. Quiz Questions:

- What is Python, and why is it important?

- How do you install Python on your computer?

- What is the purpose of the `print()` function in Python?

2. Exercises:

- Write a Python program that prints your name and age.

- Write a Python program that prints the result of adding two numbers.
Answers to Quiz Questions

1. Python is a high-level, interpreted programming language known for its


simplicity and readability. It is important because of its versatility,
readability, community support, and cross-platform compatibility.

2. To install Python, visit the official Python website, download the latest
version for your operating system, run the installer, and follow the
instructions. Make sure to add Python to PATH during installation.

3. The `print()` function in Python outputs the specified message to the


screen.

Week 3-4: Basic Syntax and Variables

Python Syntax and Indentation

Python syntax refers to the set of rules that define how a Python program is
written and interpreted. One of the key features of Python is its use of
indentation to define the structure of the code. Unlike other programming
languages that use braces `{}` or keywords to define code blocks, Python
uses indentation (whitespace) to indicate a block of code.

Example:
```python

if True:

print("This is inside the if block")

if False:

print("This is inside the nested if block")

print("This is outside the if block")

```

In the example above, the indentation indicates that the `print` statements
are part of the `if` blocks.

Key Points:

- Indentation is mandatory in Python and must be consistent.

- The standard indentation is four spaces, but you can use tabs as long as
you are consistent.

- Incorrect indentation will result in an `IndentationError`.

Variables and Data Types

Variables are used to store data that can be used and manipulated
throughout a program. In Python, you do not need to declare the type of a
variable explicitly. The type is inferred from the value assigned to the
variable.
Common Data Types:

1. Integers: Whole numbers (e.g., `5`, `-3`)

2. Floats: Decimal numbers (e.g., `3.14`, `-0.001`)

3. Strings: Text enclosed in quotes (e.g., `"Hello"`, `'World'`)

4. Booleans: True or False values (`True`, `False`)

Example:

```python

# Integer

age = 25

# Float

height = 5.9

# String

name = "Alice"

# Boolean

is_student = True

```

Type Checking:

You can check the type of a variable using the `type()` function.
```python

print(type(age)) # Output: <class 'int'>

print(type(height)) # Output: <class 'float'>

print(type(name)) # Output: <class 'str'>

print(type(is_student))# Output: <class 'bool'>

```

Basic Input and Output Functions

Python provides built-in functions for input and output operations.

Output:

The `print()` function is used to display output to the screen.

```python

print("Hello, World!")

print("My name is", name)

```
Input:

The `input()` function is used to take input from the user. The input is always
returned as a string.

```python

user_name = input("Enter your name: ")

print("Hello, " + user_name + "!")

```

Example Program:

```python

# Taking user input

name = input("Enter your name: ")

age = int(input("Enter your age: ")) # Converting input to integer

# Displaying output
print("Hello, " + name + "!")

print("You are " + str(age) + " years old.")

```

Illustrations and Examples

- Example Code:

```python

# Variables and Data Types

name = "John"

age = 30

height = 5.8

is_student = False

# Output
print("Name:", name)

print("Age:", age)

print("Height:", height)

print("Is Student:", is_student)

# Input

favorite_color = input("Enter your favorite color: ")

print("Your favorite color is " + favorite_color)

```

- Explanation:

- Variables `name`, `age`, `height`, and `is_student` store different types


of data.

- The `print()` function displays the values of the variables.

- The `input()` function takes user input and stores it in the variable
`favorite_color`.

Quiz and Exercises

1. Quiz Questions:

- What is the purpose of indentation in Python?

- Name four common data types in Python.

- How do you take input from the user in Python?

2. Exercises:

- Write a Python program that takes the user's name and age as input and
prints a greeting message.

- Write a Python program that calculates the area of a rectangle. Take the
length and width as input from the user.
Answers to Quiz Questions

1. Indentation in Python is used to define the structure of the code and


indicate code blocks.

2. Four common data types in Python are integers, floats, strings, and
booleans.

3. You take input from the user in Python using the `input()` function.

Week 5-6: Operators and Expressions

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations on


numbers. Here are the common arithmetic operators in Python:

1. Addition (`+`): Adds two numbers.

```python

result = 5 + 3

print(result) # Output: 8

```

2. Subtraction (`-`): Subtracts the second number from the first.


```python

result = 10 - 4

print(result) # Output: 6

```

3. Multiplication (`*`): Multiplies two numbers.

```python

result = 7 * 2

print(result) # Output: 14

```

4. Division (`/`): Divides the first number by the second. The result is a
float.

```python

result = 15 / 3
print(result) # Output: 5.0

```

5. **Modulus (`%`)**: Returns the remainder of the division of the first


number by the second.

```python

result = 10 % 3

print(result) # Output: 1

```

Comparison Operators

Comparison operators are used to compare two values. They return a


boolean value (`True` or `False`).
1. Equal to (`==`): Checks if two values are equal.

```python

result = (5 == 5)

print(result) # Output: True

```

2. Not equal to (`!=`): Checks if two values are not equal.

```python

result = (5 != 3)

print(result) # Output: True

```
3. Greater than (`>`): Checks if the first value is greater than the second.

```python

result = (7 > 5)

print(result) # Output: True

```

4. Less than (`<`): Checks if the first value is less than the second.

```python

result = (3 < 8)

print(result) # Output: True

```
5. Greater than or equal to (`>=`): Checks if the first value is greater than or
equal to the second.

```python

result = (6 >= 6)

print(result) # Output: True

```

6. Less than or equal to (`<=`): Checks if the first value is less than or equal
to the second.

```python

result = (4 <= 5)

print(result) # Output: True

```

Logical Operators

Logical operators are used to combine conditional statements. They return a


boolean value.
1. And (`and`): Returns `True` if both statements are true.

```python

result = (5 > 3 and 8 > 6)

print(result) # Output: True

```

2. Or (`or`): Returns `True` if at least one of the statements is true.

```python

result = (5 > 3 or 8 < 6)

print(result) # Output: True

```
3. Not (`not`): Reverses the result, returns `False` if the result is true.

```python

result = not(5 > 3)

print(result) # Output: False

```

Illustrations and Examples

- Example Code:
```python
Arithmetic Operators

addition = 10 + 5

subtraction = 10 - 5

multiplication = 10 * 5

division = 10 / 5

modulus = 10 % 3

print("Addition:", addition) # Output: 15

print("Subtraction:", subtraction) # Output: 5

print("Multiplication:", multiplication) # Output: 50

print("Division:", division) # Output: 2.0

print("Modulus:", modulus) # Output: 1

Comparison Operators

equal = (10 == 10)

not_equal = (10 != 5)

greater_than = (10 > 5)

less_than = (5 < 10)

greater_equal = (10 >= 10)

less_equal = (5 <= 10)

print("Equal:", equal) # Output: True

print("Not Equal:", not_equal) # Output: True

print("Greater Than:", greater_than) # Output: True

print("Less Than:", less_than) # Output: True

print("Greater or Equal:", greater_equal) # Output: True

print("Less or Equal:", less_equal) # Output: True


Logical Operators

logical_and = (10 > 5 and 5 < 10)

logical_or = (10 > 5 or 5 > 10)

logical_not = not(10 > 5)

print("Logical AND:", logical_and) # Output: True

print("Logical OR:", logical_or) # Output: True

print("Logical NOT:", logical_not) # Output: False

```

- Explanation:

- Arithmetic operators perform basic mathematical operations.

- Comparison operators compare two values and return a boolean result.

- Logical operators combine conditional statements and return a boolean


result.

Quiz and Exercises

1. Quiz Questions:

- What is the result of `10 % 3`?

- How do you check if two values are equal in Python?

- What does the `and` operator do?

2. Exercises:

- Write a Python program that takes two numbers as input and prints their
sum, difference, product, and quotient.

- Write a Python program that checks if a number is positive, negative, or


zero using comparison operators.
- Write a Python program that takes three boolean values as input and
prints the result of combining them using logical operators.

Answers to Quiz Questions

1. The result of `10 % 3` is `1`.

2. You check if two values are equal in Python using the `==` operator.

3. The `and` operator returns `True` if both statements are true.

Week 7-8: Control Structures

Conditional Statements (`if`, `elif`, `else`)

Conditional statements allow you to execute different blocks of code based


on certain conditions. In Python, you use `if`, `elif`, and `else` to create
conditional statements.

Syntax:

```python

if condition:

# Code to execute if condition is true

elif another_condition:
# Code to execute if another_condition is true

else:

# Code to execute if none of the above conditions are true

```

Example:

```python

age = 18

if age < 18:

print("You are a minor.")

elif age == 18:

print("You just became an adult!")

else:

print("You are an adult.")

```

Output:

```

You just became an adult!

```
Explanation:

- The `if` statement checks if `age` is less than 18. If true, it prints "You are a
minor."

- The `elif` statement checks if `age` is equal to 18. If true, it prints "You just
became an adult!"

- The `else` statement executes if none of the above conditions are true,
printing "You are an adult."

Loops (`for`, `while`)

Loops allow you to execute a block of code multiple times. Python provides
two types of loops: `for` and `while`.

For Loop:

The `for` loop iterates over a sequence (e.g., list, tuple, string) and executes
a block of code for each item in the sequence.
Syntax:

```python

for item in sequence:

# Code to execute for each item

```

Example:

```python
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

```

Output:

```

apple

banana

cherry

```

Explanation:

- The `for` loop iterates over the list `fruits` and prints each fruit.

While Loop:

The `while` loop executes a block of code as long as a specified condition is


true.

Syntax:
```python

while condition:

# Code to execute while condition is true

```

Example:

```python

count = 1
while count <= 5:

print("Count:", count)

count += 1

```

**Output**:

```

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

```

Explanation:

- The `while` loop continues to execute as long as `count` is less than or


equal to 5. It prints the value of `count` and increments it by 1 in each
iteration.

Break and Continue Statements

The `break` and `continue` statements are used to control the flow of loops.

Break Statement:

The `break` statement terminates the loop prematurely.

Example:
```python

for i in range(1, 11):

if i == 5:

break

print(i)

```

Output:

```

```
Explanation:

- The `for` loop iterates from 1 to 10. When `i` equals 5, the `break`
statement terminates the loop.

Continue Statement:

The `continue` statement skips the current iteration and moves to the next
iteration.

Example:

```python

for i in range(1, 6):

if i == 3:

continue

print(i)
```

Output:

```

```

Explanation:

- The `for` loop iterates from 1 to 5. When `i` equals 3, the `continue`
statement skips the current iteration, so 3 is not printed.

Illustrations and Examples

- Example Code:
```python

#Conditional Statements
temperature = 30

if temperature > 35:

print("It's very hot!")

elif temperature > 25:

print("It's warm.")

else:

print("It's cool.")

# For Loop

numbers = [1, 2, 3, 4, 5]

for number in numbers:

print(number)

# While Loop

count = 0

while count < 3:

print("Count:", count)

count += 1

# Break Statement

for i in range(1, 6):

if i == 4:

break

print(i)
# Continue Statement

for i in range(1, 6):

if i == 2:

continue

print(i)

```

- Explanation:

- Conditional statements execute different blocks of code based on


conditions.

- The `for` loop iterates over a sequence and executes a block of code for
each item.

- The `while` loop executes a block of code as long as a specified condition


is true.

- The `break` statement terminates the loop prematurely.

- The `continue` statement skips the current iteration and moves to the
next iteration.

Quiz and Exercises

1. Quiz Questions:

- What is the purpose of the `elif` statement in Python?

- How does a `for` loop differ from a `while` loop?

- What does the `break` statement do in a loop?

2. Exercises:

- Write a Python program that takes a number as input and checks if it is


positive, negative, or zero using conditional statements.
- Write a Python program that prints the first 10 natural numbers using a
`for` loop.

- Write a Python program that prints the numbers from 1 to 10, but skips
the number 5 using a `while` loop and the `continue` statement.

Answers to Quiz Questions

1. The `elif` statement in Python allows you to check multiple conditions


after an initial `if` statement.

2. A `for` loop iterates over a sequence and executes a block of code for
each item, while a `while` loop executes a block of code as long as a
specified condition is true.

3. The `break` statement terminates the loop prematurely.

Week 9-10: Functions

Defining and Calling Functions

Functions are reusable blocks of code that perform a specific task. They help
in organizing code, making it more readable and maintainable. In Python,
you define a function using the `def` keyword, followed by the function name
and parentheses `()`.

Syntax:
```python

def function_name():

# Code to execute

```

**Example**:

```python

def greet():

print("Hello, World!")
# Calling the function

greet()

```

Output:

```

Hello, World!

```

Explanation:

- The `def` keyword is used to define the function `greet`.

- The function contains a single `print` statement.

- The function is called using its name followed by parentheses `greet()`.

Function Parameters and Return Values

Functions can accept parameters (also known as arguments) to make them


more flexible and reusable. Parameters are specified within the parentheses
of the function definition. Functions can also return values using the `return`
statement.
Syntax:

```python

def function_name(parameter1, parameter2):

# Code to execute

return value

```

Example:

```python
def add(a, b):

result = a + b

return result

# Calling the function with arguments

sum = add(5, 3)

print("Sum:", sum)

```

Output:

```

Sum: 8

```

Explanation:

- The function `add` takes two parameters `a` and `b`.

- It calculates the sum of `a` and `b` and returns the result.

- The function is called with arguments `5` and `3`, and the returned value is
stored in the variable `sum`.

Scope and Local/Global Variables

The scope of a variable determines where it can be accessed within the


code. Variables defined inside a function are called local variables, and they
can only be accessed within that function. Variables defined outside any
function are called global variables, and they can be accessed throughout
the program.

Example:
```python

# Global variable

x = 10

def my_function():

# Local variable

y=5

print("Inside function, x:", x)

print("Inside function, y:", y)


my_function()

print("Outside function, x:", x)

# print("Outside function, y:", y) # This will cause an error

```

Output:

```

Inside function, x: 10

Inside function, y: 5

Outside function, x: 10

```

Explanation:

- The variable `x` is a global variable and can be accessed both inside and
outside the function.

- The variable `y` is a local variable and can only be accessed within the
function `my_function`.

Illustrations and Examples

- Example Code:
```python

# Defining and Calling Functions

def greet(name):

print("Hello, " + name + "!")

greet("Alice")

greet("Bob")

# Function with Return Value


def multiply(a, b):

return a * b

product = multiply(4, 5)

print("Product:", product)

# Scope and Variables

z = 20 # Global variable

def example_function():

z = 10 # Local variable

print("Inside function, z:", z)

example_function()

print("Outside function, z:", z)

```

- Explanation:

- The `greet` function takes a parameter `name` and prints a greeting


message.

- The `multiply` function takes two parameters `a` and `b`, multiplies
them, and returns the result.

- The variable `z` is defined both globally and locally within the
`example_function`. The local variable `z` inside the function does not affect
the global variable `z`.

Quiz and Exercises

1. Quiz Question:
- How do you define a function in Python?

- What is the purpose of the `return` statement in a function?

- What is the difference between local and global variables?

2. Exercises:

- Write a Python function that takes two numbers as parameters and


returns their difference.

- Write a Python function that takes a list of numbers as a parameter and


returns the sum of all the numbers in the list.

- Write a Python program that demonstrates the use of local and global
variables.

Answers to Quiz Questions

1. You define a function in Python using the `def` keyword, followed by the
function name and parentheses `()`.

2. The `return` statement in a function is used to return a value from the


function to the caller.

3. Local variables are defined inside a function and can only be accessed
within that function, while global variables are defined outside any function
and can be accessed throughout the program.

Week 11-12: Project Work

In Weeks 11-12, students will apply the concepts they have learned
throughout the term by creating simple Python programs. This hands-on
project will help reinforce their understanding and provide practical
experience. Students will also present their projects and receive feedback.

Project Ideas

Project 1: Simple Calculator


Description: Create a simple calculator that performs basic arithmetic
operations (addition, subtraction, multiplication, division).

Features:

- Take two numbers as input from the user.

- Perform addition, subtraction, multiplication, and division.

- Display the results.

Example Code:

```python

def add(a, b):


return a + b

def subtract(a, b):

return a - b

def multiply(a, b):

return a * b

def divide(a, b):

if b != 0:

return a / b

else:

return "Error! Division by zero."

# Taking input from the user

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Performing operations

print("Addition:", add(num1, num2))

print("Subtraction:", subtract(num1, num2))

print("Multiplication:", multiply(num1, num2))

print("Division:", divide(num1, num2))

```

Output:
```

Enter the first number: 10

Enter the second number: 5

Addition: 15.0

Subtraction: 5.0

Multiplication: 50.0

Division: 2.0

```

Explanation:

- The program defines four functions: `add`, `subtract`, `multiply`, and


`divide`.

- It takes two numbers as input from the user.

- It performs the arithmetic operations and displays the results.

Project 2: Temperature Converter

Description: Create a program that converts temperatures between Celsius


and Fahrenheit.
Features:

- Take a temperature value and the unit (Celsius or Fahrenheit) as input from
the user.

- Convert the temperature to the other unit.

- Display the converted temperature.

Example Code:
```python

def celsius_to_fahrenheit(celsius):

return (celsius * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9

# Taking input from the user

temp = float(input("Enter the temperature: "))

unit = input("Enter the unit (C/F): ").upper()

# Performing conversion

if unit == "C":

converted_temp = celsius_to_fahrenheit(temp)

print(f"{temp}°C is equal to {converted_temp}°F")

elif unit == "F":

converted_temp = fahrenheit_to_celsius(temp)

print(f"{temp}°F is equal to {converted_temp}°C")

else:

print("Invalid unit!")

```

Output:

```

Enter the temperature: 100

Enter the unit (C/F): C

100.0°C is equal to 212.0°F

```

Explanation:

- The program defines two functions: `celsius_to_fahrenheit` and


`fahrenheit_to_celsius`.
- It takes a temperature value and the unit as input from the user.

- It converts the temperature to the other unit and displays the result.

Project 3: Simple To-Do List

Description: Create a simple to-do list application that allows users to add,
view, and remove tasks.

Features:

- Add tasks to the to-do list.

- View the list of tasks.

- Remove tasks from the list.

Example Code:
```python
def add_task(tasks, task):

tasks.append(task)

def view_tasks(tasks):

for i, task in enumerate(tasks, 1):

print(f"{i}. {task}")

def remove_task(tasks, task_number):

if 0 < task_number <= len(tasks):

tasks.pop(task_number - 1)

else:

print("Invalid task number!")

# Main program

tasks = []

while True:

print("\nTo-Do List")

print("1. Add Task")

print("2. View Tasks")

print("3. Remove Task")

print("4. Exit")

choice = input("Enter your choice: ")

if choice == "1":

task = input("Enter the task: ")


add_task(tasks, task)

elif choice == "2":

view_tasks(tasks)

elif choice == "3":

task_number = int(input("Enter the task number to remove: "))

remove_task(tasks, task_number)

elif choice == "4":

break

else:

print("Invalid choice!")

```

Output:

```
To-Do List

1. Add Task

2. View Tasks

3. Remove Task

4. Exit

Enter your choice: 1

Enter the task: Buy groceries

To-Do List

1. Add Task

2. View Tasks

3. Remove Task

4. Exit

Enter your choice: 2

1. Buy groceries

```

Explanation:

- The program defines three functions: `add_task`, `view_tasks`, and


`remove_task`.

- It provides a menu for the user to add, view, and remove tasks.

- The tasks are stored in a list and manipulated based on the user's choices.

### Presentation and Feedback

1. Presentation:

- Students will present their projects to the class.


- They will explain the functionality of their programs and demonstrate how
they work.

- They will discuss any challenges they faced and how they overcame
them.

2. Feedback:

- The teacher and classmates will provide constructive feedback on the


projects.

- Feedback will focus on the correctness, efficiency, and readability of the


code.

- Suggestions for improvement and additional features will be provided.

Quiz and Exercises

1. Quiz Questions:

- What is the purpose of defining functions in a program?

- How do you handle invalid input in a program?

- What are some common challenges faced when writing a program?

2. Exercises:

- Write a Python program that takes a list of numbers as input and returns
the largest number in the list.

- Write a Python program that calculates the factorial of a number using a


function.

- Write a Python program that simulates a simple banking system with


options to deposit, withdraw, and check balance.

Answers to Quiz Questions

1. The purpose of defining functions in a program is to create reusable blocks


of code that perform specific tasks, making the code more organized and
maintainable.
2. To handle invalid input in a program, you can use conditional statements
to check the input and provide appropriate error messages or prompts for
the user to enter valid input.

3. Some common challenges faced when writing a program include


debugging errors, handling edge cases, and ensuring the code is efficient
and readable.

You might also like