TechyVia

Mastering Basic Python for Efficient Programming

History of Python

Python was created by Guido van Rossum and first released in 1991. Here are some key milestones in its history:

Variables and Data Types

Variables are used to store data that can be referenced and manipulated in a program. Each variable has a data type that determines the kind of data it can hold.

Basic Operators

Arithmetic Operators

Arithmetic Operators are used to perform mathematical operations:

Comparison Operators

Comparison Operators are used to compare values:

Logical Operators

Logical Operators are used to combine conditional statements:

Control Flow

Control flow in programming determines the order in which statements are executed. It includes conditional statements and loops.

Conditional Statements

Theory: Conditional statements allow a program to make decisions based on certain conditions. They execute different blocks of code depending on whether a condition is true or false.

Real-Life Example: Imagine you’re deciding what to wear based on the weather:

Syntax:

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

Examples:

Simple If Statement:
temperature = 30
if temperature > 25:
    print("It's hot outside.")
If-Else Statement:
temperature = 20
if temperature > 25:
    print("It's hot outside.")
else:
    print("It's not hot outside.")
If-Elif-Else Statement:
temperature = 15
if temperature > 25:
    print("It's hot outside.")
elif temperature > 15:
    print("It's warm outside.")
else:
    print("It's cold outside.")

Loops

Theory: Loops allow a program to repeat a block of code multiple times. They are useful for tasks that require repetition.

Real-Life Example: Think of a morning routine:

Syntax:

For Loop:

for item in iterable:
    # code to execute for each item

While Loop:

while condition:
    # code to execute as long as condition is true

Examples:

For Loop with Range:
for i in range(3):
    print("Iteration:", i)
While Loop with Condition:
count = 0
while count < 3:
    print("Count:", count)
    count += 1
For Loop with List:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
While Loop with Decrement:
number = 3
while number > 0:
    print("Number:", number)
    number -= 1
Nested Loops:
for i in range(2):
    for j in range(2):
        print(f"i: {i}, j: {j}")

Functions

Functions are a fundamental concept in programming that allow you to encapsulate code into reusable blocks. Let’s explore defining functions and built-in functions in Python with theory, real-life examples, syntax, and varied examples.

Defining Functions

Theory: Functions are blocks of code designed to perform a specific task. They help in organizing code, making it reusable, and improving readability.

Real-Life Example: Think of a function as a recipe in a cookbook. The recipe (function) takes ingredients (parameters), follows a series of steps (code), and produces a dish (return value).

Syntax:

def function_name(parameters):
    # code block
    return value

Examples:

Simple Function:
def greet():
    return "Hello, World!"

print(greet())
Function with Parameters:
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
Function Returning Multiple Values:
def get_name_and_age():
    name = "Alice"
    age = 30
    return name, age

name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}")

Built-in Functions

Theory: Python provides many built-in functions that perform common tasks. These functions are always available and do not require importing any modules.

Real-Life Example: Built-in functions are like tools in a toolbox. You use them to perform specific tasks without having to create the tools yourself.

Examples:

Using print() to Display Messages:
print("Hello, World!")
Using len() to Get Length of a List:
fruits = ["apple", "banana", "cherry"]
print(len(fruits))
Using range() to Generate Numbers:
for i in range(5):
    print(i)
Using type() to Check Data Types:
print(type(10))
print(type(10.5))
print(type("Hello"))
Using sum() to Add Numbers in a List:
numbers = [1, 2, 3, 4, 5]
print(sum(numbers))

Data Structures

Lists

Definition: Lists are ordered, mutable collections of items. They can store elements of different data types.

Syntax:

# Creating a list
my_list = [1, 2, 3, "apple", "banana"]

Methods:

Examples:

Creating and Accessing a List:
fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple
Modifying a List:
fruits[1] = "orange"
print(fruits)  # Output: ['apple', 'orange', 'cherry']
Adding Elements:
fruits.append("kiwi")
print(fruits)  # Output: ['apple', 'orange', 'cherry', 'kiwi']
Removing Elements:
fruits.remove("orange")
print(fruits)  # Output: ['apple', 'cherry', 'kiwi']
Sorting a List:
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers)  # Output: [1, 1, 3, 4, 5, 9]

Tuples

Definition: Tuples are ordered, immutable collections of items. Once created, their elements cannot be changed.

Syntax:

# Creating a tuple
my_tuple = (1, 2, 3, "apple", "banana")

Methods:

Examples:

Creating and Accessing a Tuple:
coordinates = (10.0, 20.0)
print(coordinates[0])  # Output: 10.0
Using count() Method:
my_tuple = (1, 2, 2, 3, 4)
print(my_tuple.count(2))  # Output: 2
Using index() Method:
my_tuple = (1, 2, 3, 4)
print(my_tuple.index(3))  # Output: 2
Tuple Unpacking:
person = ("Alice", 30, "Engineer")
name, age, profession = person
print(name)  # Output: Alice
Nested Tuples:
nested_tuple = ((1, 2), (3, 4))
print(nested_tuple[1][0])  # Output: 3

Dictionaries

Definition: Dictionaries are unordered collections of key-value pairs. They are mutable and indexed by keys.

Syntax:

# Creating a dictionary
my_dict = {"name": "Alice", "age": 25}

Methods:

Examples:

Creating and Accessing a Dictionary:
person = {"name": "Alice", "age": 25}
print(person["name"])  # Output: Alice
Modifying a Dictionary:
person["age"] = 26
print(person)  # Output: {'name': 'Alice', 'age': 26}
Adding Key-Value Pairs:
person["city"] = "New York"
print(person)  # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Removing Key-Value Pairs:
del person["age"]
print(person)  # Output: {'name': 'Alice', 'city': 'New York'}
Using items() Method:
for key, value in person.items():
    print(f"{key}: {value}")

Sets

Definition: Sets are unordered collections of unique elements. They are mutable and do not allow duplicate values.

Syntax:

# Creating a set
my_set = {1, 2, 3, "apple", "banana"}

Methods:

Examples:

Creating and Accessing a Set:
fruits = {"apple", "banana", "cherry"}
print(fruits)  # Output: {'apple', 'banana', 'cherry'}
Adding Elements:
fruits.add("orange")
print(fruits)  # Output: {'apple', 'banana', 'cherry', 'orange'}
Removing Elements:
fruits.remove("banana")
print(fruits)  # Output: {'apple', 'cherry', 'orange'}
Union of Sets:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)  # Output: {1, 2, 3, 4, 5}
Intersection of Sets:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {2, 3}