Introduction To Python

Importance of Python

Python is a powerful and easy-to-learn programming language used for web development, data science, AI, and automation. It is popular because of its simple syntax, large library support, and strong community. Python works on all platforms and is highly demanded in the tech industry.


What is the print() Function in Python?

The print() function in Python is used to display information on the screen. It’s one of the most commonly used functions — perfect for showing text, numbers, and results of calculations.

Basic Example:


print("Hello, Python Learners!")
  

🧠 Explanation: The message inside the quotation marks will appear on the screen when the program runs.

Printing Numbers


print(25)
print(10 + 5)
  

You can print numbers directly or display the result of a calculation.

Printing Multiple Items

You can use commas , to print several things at once:


name = "Bright"
age = 18
print("My name is", name, "and I am", age, "years old.")
  

Using Escape Characters

Escape characters help format your output. For example: \n = new line, \t = tab space.


print("Python is fun!\nLet's keep learning.")
print("Name:\tBright")
  

Tip: The print() function is great for debugging and checking your program's output.


How to Install Python

Installing Python is the first step to start coding. Follow these steps to install it on your computer:

  1. Go to the official Python website: python.org/downloads
  2. Download the latest version for your operating system (Windows, macOS, or Linux).
  3. Run the installer and make sure to check the box that says “Add Python to PATH”.
  4. Click “Install Now” and wait for it to finish.
  5. After installation, open your terminal or command prompt and type:
python --version

If you see a version number like Python 3.x.x, congratulations! Python is successfully installed 🎉

🎥 Watch this video tutorial

Here’s a short video to guide you step-by-step through the installation process:

What is a String in Python?

In Python, a string is a sequence of characters enclosed in quotes. You can use either single quotes (' ') or double quotes (" ") to create a string.

Example:


# Using single quotes
name = 'Bright'

# Using double quotes
greeting = "Hello, world!"

# Printing strings
print(name)
print(greeting)
  

Strings are one of the most commonly used data types in Python. You can use them to store text like names, sentences, or even entire paragraphs.

String Operations

You can perform many operations on strings, such as joining, slicing, and changing case:


text = "Python Programming"

# Accessing characters
print(text[0])   # P

# Slicing
print(text[0:6]) # Python

# Changing to upper case
print(text.upper())  # PYTHON PROGRAMMING

# Combining strings
first = "Hello"
second = "Python"
print(first + " " + second)  # Hello Python
  

Tip: Strings are immutable, meaning once created, their characters cannot be changed directly.


Functions in Python

A function in Python is a block of code that performs a specific task. Functions help you organize your code and avoid repetition. You can define a function once and use (or "call") it many times.

Creating a Function

In Python, you define a function using the def keyword, followed by the function name and parentheses ().


def greet():
    print("Hello, welcome to Python!")
  

To run this function, you just need to call it:


greet()
  

Functions with Parameters

You can pass information into a function using parameters. Parameters let your function work with different inputs.


def greet_user(name):
    print("Hello, " + name + "!")

# Calling the function
greet_user("Bright")
greet_user("Ama")
  

Functions with Return Values

Some functions send back a result using the return keyword.


def add_numbers(a, b):
    return a + b

# Using the returned value
result = add_numbers(5, 3)
print("The sum is:", result)
  

Tip: Functions make your code easier to read, reuse, and debug.

Types of Functions in Python

In Python, there are two main types of functions:

1️⃣ Built-in Functions

These are functions that come pre-installed with Python. You can use them anytime without defining them yourself.

Examples:


# Some common built-in functions
print("Hello, Python!")      # Displays text on the screen
len("Bright")                # Returns length of a string
type(25)                     # Returns the data type of the value
max(5, 10, 15)               # Returns the largest number
min(5, 10, 15)               # Returns the smallest number
sum([1, 2, 3, 4, 5])         # Adds all the numbers in a list
  

These built-in functions make coding easier and faster because you don’t have to write the logic yourself.

2️⃣ User-defined Functions

These are functions that you create yourself to perform a specific task. You define them using the def keyword.

Example:


def multiply(a, b):
    result = a * b
    return result

print(multiply(4, 6))  # Output: 24
  

You can define as many user-defined functions as you want, depending on your program’s needs.

Summary:

Tip: Use functions to make your code reusable and easy to maintain.


How to Use Important Built-in Functions in Python

Python provides many built-in functions that make programming easier and faster. You can use them without importing any external library.

1️⃣ The print() Function

Displays output on the screen.


print("Welcome to Python!")  
print(5 + 3)
  

2️⃣ The len() Function

Returns the number of items in a list, string, or other collection.


name = "Bright"
print(len(name))   # Output: 6
  

3️⃣ The type() Function

Shows the data type of a variable or value.


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

4️⃣ The input() Function

Takes input from the user.


name = input("Enter your name: ")
print("Hello,", name)
  

5️⃣ The max() and min() Functions

These functions find the largest or smallest number in a group.


numbers = [3, 7, 1, 9, 5]
print(max(numbers))  # Output: 9
print(min(numbers))  # Output: 1
  

6️⃣ The sum() Function

Adds up all numbers in a list.


numbers = [1, 2, 3, 4, 5]
print(sum(numbers))  # Output: 15
  

7️⃣ The round() Function

Rounds a floating-point number to a specific number of decimal places.


pi = 3.14159
print(round(pi, 2))  # Output: 3.14
  

8️⃣ The abs() Function

Returns the absolute (positive) value of a number.


print(abs(-10))  # Output: 10
  

9️⃣ The sorted() Function

Returns a sorted list of numbers or strings.


names = ["Ama", "Kofi", "Bright", "Yaw"]
print(sorted(names))
  

🔟 The range() Function

Generates a sequence of numbers, often used with loops.


for i in range(5):
    print(i)
# Output: 0 1 2 3 4
  

Tip: You can explore more built-in functions by typing help('builtins') in your Python shell.


Variables in Python

A variable in Python is used to store data that can be used later in your program. Think of a variable as a container that holds a value — like a box that stores information.

How to Create a Variable

You create a variable by giving it a name and assigning it a value using the = sign.


name = "Bright"
age = 20
height = 1.75

print(name)
print(age)
print(height)
  

In this example:

Variable Naming Rules

Examples of Valid and Invalid Variables


# ✅ Valid variable names
user_name = "Ama"
score = 90
_age = 25

# ❌ Invalid variable names
2name = "Bright"    # Starts with a number
user-name = "Ama"   # Contains a hyphen
class = "Python"    # 'class' is a reserved keyword
  

Changing Variable Values

You can update a variable’s value by assigning it again.


language = "Java"
language = "Python"
print(language)   # Output: Python
  

Assigning Multiple Variables

Python allows you to assign values to multiple variables in one line.


x, y, z = 5, 10, 15
print(x, y, z)
  

Summary

Tip: Use clear variable names that describe their purpose, like student_name or total_score.


Data Types in Python

In Python, data types are the different kinds of values that can be stored in a variable. They tell Python what kind of data is being handled — like numbers, text, or lists.

Common Python Data Types

Examples:


# Integer
age = 18

# Float
price = 25.99

# String
name = "Bright"

# Boolean
is_student = True

# List
fruits = ["apple", "banana", "cherry"]

# Tuple
colors = ("red", "green", "blue")

# Dictionary
person = {"name": "Ama", "age": 25}

# Set
unique_numbers = {1, 2, 3, 4}
  

You can check the type of any value using the type() function:


print(type(age))       # Output: <class 'int'>
print(type(name))      # Output: <class 'str'>
print(type(fruits))    # Output: <class 'list'>
  

Tip: Knowing data types helps you store and process information correctly in your programs.


Input in Python

The input() function in Python allows users to type information while a program is running. It helps make your programs more interactive by collecting data directly from the user.

Basic Example:


name = input("Enter your name: ")
print("Hello, " + name + "!")
  

🧠 Explanation: The program displays the message inside the quotes ("Enter your name: ") and waits for the user to type something. Whatever the user types is stored in the variable name.

Getting Numbers as Input

The input() function always returns data as a string. If you need a number, you must convert it using int() or float().


age = int(input("Enter your age: "))
print("You will be", age + 1, "next year.")
  

Multiple Inputs Example


name = input("What is your name? ")
country = input("Where are you from? ")
print("Hello", name, "from", country + "!")
  

Tip: Always convert user input to the right data type if you plan to use it in calculations.


Comments in Python

Comments in Python are lines in your code that are ignored by the computer. They are used to explain what your code does or to make notes for yourself or others.

Why Use Comments?

Single-line Comment

Use the # symbol to write a comment on one line.


# This is a single-line comment
print("Hello, Python!")  # This prints a message
  

Multi-line Comment

Python does not have a special symbol for multi-line comments, but you can use triple quotes ''' ... ''' or """ ... """ to write comments on multiple lines.


'''
This is a multi-line comment.
You can write as many lines as you want here.
'''
print("Learning Python is fun!")
  

Tip:

Writing clear comments helps others (and your future self) understand your code faster.


Conditional Statements in Python

Conditional statements let your program make decisions. They check if a condition is True or False and then run specific code depending on the result.

1️⃣ The if Statement

The if statement runs a block of code only if a condition is true.


age = 18

if age >= 18:
    print("You are an adult.")
  

2️⃣ The if...else Statement

Use else to run code when the if condition is false.


age = 15

if age >= 18:
    print("You can vote.")
else:
    print("You are too young to vote.")
  

3️⃣ The if...elif...else Statement

Use elif (short for "else if") to check multiple conditions.


score = 75

if score >= 90:
    print("Excellent!")
elif score >= 70:
    print("Good job!")
elif score >= 50:
    print("You passed.")
else:
    print("You failed.")
  

4️⃣ Nested if Statements

You can put an if statement inside another to check multiple levels of conditions.


age = 20
country = "Ghana"

if country == "Ghana":
    if age >= 18:
        print("You can vote in Ghana.")
    else:
        print("You are too young to vote.")
  

Tip: Use indentation (spaces) carefully in Python — it shows which code belongs to which condition.


Loops in Python

Loops in Python are used to repeat a block of code multiple times. They help you run the same code again and again without writing it many times.

1️⃣ The for Loop

The for loop is used to iterate over a sequence such as a list, tuple, string, or range.


# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
  

# Using range() to loop numbers
for i in range(5):
    print("Number:", i)
  

2️⃣ The while Loop

The while loop keeps running as long as a condition is True.


count = 1
while count <= 5:
    print("Counting:", count)
    count += 1
  

3️⃣ The break Statement

The break statement stops a loop even if the condition is still true.


for num in range(10):
    if num == 5:
        break
    print(num)
  

4️⃣ The continue Statement

The continue statement skips the rest of the code in the loop for that iteration and goes to the next one.


for num in range(6):
    if num == 3:
        continue
    print(num)
  

5️⃣ The else in Loops

The else block in a loop runs only when the loop finishes normally (without a break).


for i in range(3):
    print(i)
else:
    print("Loop finished!")
  

Tip: Loops make your code efficient — use them to process lists, data, or repeat tasks automatically.


. recommend video


🧠 Python Basics Quiz

1. What is the correct way to display text in Python?



2. Which of these is a string in Python?



3. What is a variable used for?



4. What keyword is used to create a function in Python?



5. Which function is used to take user input?