Python Basics

Overview

Teaching: 130 min
Exercises: 130 min
Questions
  • What is Python, and why is it popular?

  • How do you declare a variable in Python?

  • What are the basic data types in Python?

  • What is the difference between if, elif, and else statements?

  • How do you define a function in Python?

Objectives
  • Understand Python’s role in programming and its applications.

  • Learn the basics of Python syntax and structure.

  • Explore Python data types, variables, and operators.

  • Write and execute Python scripts for simple tasks.

  • Practice debugging and handling errors.

Python Basics

Training Agenda

  1. Introduction to Python
  2. Basic Syntax and Structure
  3. Variables and Data Types
  4. Lists, Dictionaries, and Tuples
  5. Operators
  6. Control Structures
  7. Functions
  8. Error Handling
  9. Python Modules
  10. Exercise

Introduction to Python: What is Python?

Abstraction of Programming Languages

Hello, World, in Different Languages

Assembly Language

section  data
    hello db 'Hello, World!',10
    len equ $ - hello

section  text
    global _start

_start:
    ; write our string to stdout
    mov eax, 4         ; sys_write
    mov ebx, 1         ; file descriptor 1 (stdout)
    mov ecx, hello     ; message to write
    mov edx, len       ; message length
    int 0x80           ; syscall
    ; exit
    mov eax, 1         ; sys_exit
    xor ebx, ebx       ; exit status 0
    int 0x80           ; syscall

Java Language

public class HelloWorld {
    public static void main(String[] args) {
        System out println("Hello, World!");
    }
}

C Language

#include <stdio h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

R Language

print("Hello, World!")

Python Language

print("Hello, World!")

Key Features of Python

Versatility/Multi-Purpose

In-Demand Skill

Rich Ecosystem/Extensive Libraries

Collaboration and Community Support/Large Community

Open source

Platform-independent

Efficent in development

Downsides of Python


Basic Syntax and Structure

Writing your first Python program

     print("Hello, World!")

Python indentation rules

# Check if a number is positive or not.
number = 10  # Assigning a value to a variable

# This block executes if the condition is true
if number > 0:
    print("The number is positive.")
     
# This block executes if the condition is false
else:
    print("The number is not positive.")

Comments and documentation

Single-line Comments
# This is a single-line comment
print("Single-line comments start with a hash (#).")
Multi-line Comments
"""
This is an example of a multi-line comment.
It can be used to describe a block of code or provide detailed information.
print("Multi-line comments are written using triple quotes.")
"""
Inline Comments
number = 42  # This variable stores the answer to life, the universe, and everything
print(number)

Variables and Data Types

Declaring variables

Declaring and Print variables
name = "yonas"      # String type
print("Name:", name)
age = 25             # Integer type
print("Age:", age)
height = 5.7         # Float type
print("Height:", height)
is_student = True    # Boolean type
print("Is student:", is_student)
x = 1.0 - 1.0j   # Complex numbers
print("Complex numbers:", x)

Exploring data types

# Integer example
number = 42
print("The type of", number, "is", type(number))
# Float example
pi = 3.14
print("The type of", pi, "is", type(pi))
# String example
message = "Hello, Python!"
print("The type of", message, "is", type(message))
# Boolean example
is_sunny = False
print("The type of", is_sunny, "is", type(is_sunny))
# List example
colors = ["red", "green", "blue"]
print("The type of", colors, "is", type(colors))

Lists, Dictionaries, and Tuples

Lists

Creating a List
fruits = ["apple", "banana", "cherry"]

# Print the list
print(fruits)  
Accessing List Elements
print(fruits[0])  
print(fruits[-1]) 
Modifying a List
fruits[1] = "blueberry"
print(fruits)  
List Methods
# Add an item to the end of the list
fruits.append("orange")
print(fruits)  # Output: ['apple', 'blueberry', 'cherry', 'orange']

# Remove an item by value
fruits.remove("cherry")
print(fruits)  # Output: ['apple', 'blueberry', 'orange']

# Insert an item at a specific index
fruits.insert(1, "banana")
print(fruits)  # Output: ['apple', 'banana', 'blueberry', 'orange']

# Sort the list
fruits.sort()
print(fruits)  # Output: ['apple', 'banana', 'blueberry', 'orange']

Dictionaries

Creating a Dictionary
# Define a dictionary with information about a book
book = {
    "title": "1984",
    "author": "George Orwell",
    "year": 1949
}

# Print the dictionary
print(book) 
Accessing Values by Key
print(book["title"])  
Modifying a Dictionary
# Change the value of an existing key
book["year"] = 1950
print(book) 

# Add a new key-value pair
book["genre"] = "Dystopian"
print(book)  
Dictionary Methods
# Get all keys
print(book.keys()) 

# Get all values
print(book.values())  

# Remove a key-value pair
book.pop("genre")
print(book)

Tuples

Creating a Tuple
# Define a tuple
coordinates = (10, 20, 30)

# Print the tuple
print(coordinates)  
Accessing Tuple Elements
# Access elements by index
print(coordinates[0])

print(coordinates[-1]) 
Tuple Immutability
# Attempting to modify a tuple results in an error
coordinates[0] = 15  
Unpacking a Tuple

print(x, y, z)


##### Tuple Methods

```python
# Get the length of a tuple
print(len(coordinates))  

# Count occurrences of an element
print(coordinates.count(20))  

# Find the index of an element
print(coordinates.index(30))  

Summary of Differences: Lists, Dictionaries, and Tuples

Feature List Dictionary Tuple
Syntax [] {} ()
Mutable Yes Yes No
Ordered Yes (since Python 3.7) Yes (since Python 3.7) Yes
Duplicates Yes No (keys must be unique) Yes

Operators

1) Arithmetic Operators
2) Comparison Operators
3) Logical Operators

Arithmetic Operators

# Define and y
x = 10
y = 3
print("Addition:", x + y)        # Addition
print("Subtraction:", x - y)     # Subtraction
print("Multiplication:", x * y)  # Multiplication
print("Division:", x / y)        # Division
print("Floor Division:", x // y) # Floor Division
print("Modulus:", x % y)         # Modulus (remainder)
print("Exponentiation:", x ** y) # Exponentiation

Comparison Operators

print("Equal to:", x == y)       # Equal to
print("Not equal to:", x != y)   # Not equal to
print("Greater than:", x > y)    # Greater than
print("Less than:", x < y)       # Less than
print("Greater or equal:", x >= y) # Greater than or equal to
print("Less or equal:", x <= y)   # Less than or equal to

Logical Operators

# Define a and b
a = True
b = False
print("AND operator:", a and b) # Logical AND
print("OR operator:", a or b)   # Logical OR
print("NOT operator:", not a)   # Logical NOT

Control Structures

1) If-else Statement
2) While Loop
3) For Loop

If-else Statement

# Checking if a number is positive or negative

number = 5  # Assign a number to the variable 'number'

if number > 0:

    # This block will run if the condition (number > 0) is True
    print(f"The number {number} is positive.")

else:

    # This block will run if the condition (number > 0) is False
    print(f"The number {number} is negative.")

Nested if-else

# Checking if a number is positive, negative, or zero

number = -3  # Change the value to test other cases

if number > 0:
    print(f"The number {number} is positive.")

elif number == 0:
    print("The number is zero.")

else:
    print(f"The number {number} is negative.")

While Loop

# Start with the number 1
number = 1

while number <= 5:  # The loop runs as long as 'number' is less than or equal to 5

    print(number)  # Print the current value of 'number'

    number += 1  # Increment 'number' by 1 in each iteration

For Loop


# Print each fruit in the list
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

    # Loop through each element in the list 'fruits'
    print(f"I like {fruit}")
# Print numbers from 1 to 5

for num in range(1, 6):  # range(start, stop) generates numbers from start to stop-1
    print(num)

Functions

Defining and Calling Functions

Function without a Parameter
# Define the function
def greet():
    # This function prints a greeting message
    print("Hello, welcome to the training!")

# Call the function
greet()  # Output: Hello, welcome to the training!
Function with a Parameter
# Define the function
def greet_user(name):

    # This function greets the user by their name
    print(f"Hello, {name}! Welcome to the training.")

# Call the function with an argument
greet_user("Yonas")  # Output: Hello, Yonas! Welcome to the training.
# Define the function
def add_numbers(a, b):

    # This function returns the sum of two numbers
    return a + b

# Call the function and store the result

result = add_numbers(3, 5)  
print(f"The sum is: {result}")  
Returning Multiple Values
# Define the function
def calculate_area_and_perimeter(length, width):

    # This function calculates the area and perimeter of a rectangle
    area = length * width
    perimeter = 2 * (length + width)
    return area, perimeter  # Return both values

# Call the function and unpack the results
area, perimeter = calculate_area_and_perimeter(5, 3)

print(f"Area: {area}, Perimeter: {perimeter}")

Error Handling

Common Python Errors

SyntaxError
# print("Hello  # Missing closing quotation mark

print("Hello")  # Corrected version
NameError
print(value)  # Trying to print a variable that hasn't been defined

# Corrected version:
value = 10
print(value)  # Output: 10
TypeError
number = 5
text = "hello"

print(number + text)  # Trying to add a number to a string

# Corrected version:
print(f"{number} {text}")  # Output: 5 hello

IndexError
numbers = [1, 2, 3]

print(numbers[3])  # Accessing an index that doesn't exist

# Corrected version:
print(numbers[2])  

Debugging Basics

Catch a specific type of error

try:
    result = 10 / 0  # Division by zero causes ZeroDivisionError

except ZeroDivisionError: # except block catches specific errors and prevents the program from crashing.
    print("Error: Cannot divide by zero!")

Catch different types of errors

try:
    value = int("text")  # This will cause a ValueError
except ValueError:
    print("Error: Cannot convert text to an integer!")
except TypeError:
    print("Error: There was a type mismatch!")

Catch any error

try:
    result = 10 / 0  # This will cause a ZeroDivisionError
except Exception as e:
    print(f"An error occurred: {e}")

Python Modules

Types of Loading Modules

Import the entire module
# Importing the math module
import math

# Use the sqrt function from the math module
result = math.sqrt(16)
print(result) 
Importing Specific Functions or Variables
# Importing only the sqrt function from math

from math import sqrt

# Directly use the sqrt function
result = sqrt(25)
print(result)
Using an Alias ‘
# Using an alias for math
import math as m

# Use the alias to call functions
result = m.pow(2, 3)  # 2 raised to the power of 3
print(result)  
Importing All Contents of a Module
# Importing all contents of math
from math import *

# Use functions without the module name
result = factorial(5)
print(result) 

Built-in vs. External Modules

Built-in Modules

External Modules

Getting Help with Modules

# Getting help on the math module
import math
help(math)
# Listing all functions in the math module
import math
print(dir(math)

Creating Your Own Module

def greet(name):
    return f"Hello, {name}!"
import my_module

message = my_module.greet("Yonas")
print(message) 

Exercise

  1. Create a loop that prints all the odd numbers between 1 and 20.
  2. Write a function that takes a number and returns its square.
  3. Create a function that takes two numbers and returns their average.
  4. Write a function with a default argument that prints a farewell message (e.g., “Goodbye, Guest!”).
  5. Write a program that handles a ValueError when converting user input to an integer.
  6. Use a try-except block to handle a FileNotFoundError when opening a non-existent file.
  7. Debug a program by printing variable values at different points.

Key Points

  • Python is a versatile and beginner-friendly programming language.

  • Variables and data types are the building blocks of Python programming.

  • Conditional statements and loops are essential for controlling program flow.

  • Functions help organize reusable blocks of code.

  • Python has a rich standard library and supports external libraries for advanced functionalities.

Copyright © 2024 UNECA-ACS

Contact