Python Fundamentals
A programming language is a formal system of instructions that allows humans to communicate with
computers to create software, algorithms, and perform tasks. It consists of syntax (structure), semantics
(meaning), and supports data types and control structures. Examples include Python, Java, and C++.
Programming languages enable abstraction and manage complexity in software development.
1. Data Types
Integers
Definition: Whole numbers without a fractional part.
Operations: Basic arithmetic operations like addition (+), subtraction (-), multiplication
(*), and division (/).
Example:
python
RunCopy
num1 = 10
num2 = 3
print(num1 + num2) # Output: 13
print(num1 - num2) # Output: 7
print(num1 * num2) # Output: 30
print(num1 / num2) # Output: 3.333...
Floats
Definition: Numbers that contain a decimal point.
Precision: Used for calculations requiring fractional values.
Example:
python
RunCopy
price = 19.99
tax = 0.07
total_price = price * (1 + tax)
print(total_price) # Output: 21.39
Strings
Definition: A sequence of characters enclosed in quotes.
Immutability: Strings cannot be changed after creation, but they can be concatenated or
sliced.
Common Methods: len(), upper(), lower(), strip().
Example:
python
RunCopy
text = " Hello, World! "
print(text.strip()) # Output: "Hello, World!"
print(text.upper()) # Output: " HELLO, WORLD! "
Booleans
Definition: Represents truth values, True or False.
Use Case: Often used in conditional statements and loops.
Example:
python
RunCopy
is_active = True
if is_active:
print("User is active") # Output: User is active
2. Lists
Overview
Definition: An ordered collection of items that can be of mixed data types.
Mutability: Lists can be modified after creation.
Creating Lists
python
RunCopy
my_list = [1, "Python", 3.14, True]
Accessing Elements
Indexing: Access elements using their index (0-based).
Example:
python
RunCopy
print(my_list[1]) # Output: Python
print(my_list[-1]) # Output: True (last element)
Slicing Lists
Definition: Retrieve a subset of the list.
Example:
python
RunCopy
print(my_list[1:3]) # Output: ["Python", 3.14]
Adding Elements
Methods:
o append(): Adds an item to the end.
o insert(): Adds an item at a specified index.
Example:
python
RunCopy
my_list.append("New Element")
my_list.insert(1, "Inserted Element")
Removing Elements
Methods:
o remove(): Removes the first occurrence of a value.
o pop(): Removes an item at a specified index or the last item.
Example:
python
RunCopy
my_list.remove("Python")
last_item = my_list.pop() # Removes and returns the last item
List Comprehensions
Definition: A concise way to create lists.
Example:
python
RunCopy
squares = [x**2 for x in range(10)] # Creates a list of squares
Nested Lists
Definition: Lists that contain other lists.
Example:
python
RunCopy
nested_list = [[1, 2], [3, 4], [5, 6]]
print(nested_list[1][0]) # Output: 3
Example: Managing Server IPs
python
RunCopy
server_ips = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
for ip in server_ips:
print(f"Connecting to {ip}...")
3. Tuples
Overview
Definition: An ordered collection of items, similar to lists, but immutable.
Use Case: When you want to store a fixed collection of items.
Creating Tuples
python
RunCopy
my_tuple = (1, "DevOps", 3.14)
Accessing Elements
python
RunCopy
print(my_tuple[1]) # Output: DevOps
Tuple Unpacking
Definition: Assigning tuple elements to variables.
Example:
python
RunCopy
coordinates = (10.0, 20.0)
x, y = coordinates
print(f"x: {x}, y: {y}") # Output: x: 10.0, y: 20.0
4. Dictionaries
Overview
Definition: An unordered collection of key-value pairs.
Keys: Must be unique and immutable.
Values: Can be of any data type.
Creating Dictionaries
python
RunCopy
my_dict = {"name": "Alice", "age": 30, "is_active": True}
Accessing Values
python
RunCopy
print(my_dict["name"]) # Output: Alice
Modifying Values
python
RunCopy
my_dict["age"] = 31 # Changing the value associated with the key 'age'
Adding Key-Value Pairs
python
RunCopy
my_dict["email"] = "[email protected]"
Removing Key-Value Pairs
python
RunCopy
del my_dict["is_active"]
Common Methods
get(): Retrieves a value by key, returns None if the key doesn’t exist.
keys(): Returns a view of the dictionary's keys.
values(): Returns a view of the dictionary's values.
items(): Returns a view of the dictionary's key-value pairs.
Example: Configuration Settings
python
RunCopy
config = {
"server": "localhost",
"port": 8080,
"debug": True
}
print(config.get("server")) # Output: localhost
5. Functions
Defining Functions
Definition: A reusable block of code that performs a specific task.
Syntax: Use the def keyword.
Example:
python
RunCopy
def greet(name):
return f"Hello, {name}!"
Default Parameters
Definition: Parameters that assume a default value if no value is provided.
Example:
python
RunCopy
def greet(name="Guest"):
return f"Hello, {name}!"
Variable-Length Arguments
Definition: Allows functions to accept a variable number of arguments.
Syntax: Use *args for non-keyword arguments and **kwargs for keyword arguments.
Example:
python
RunCopy
def add_numbers(*args):
return sum(args)
print(add_numbers(1, 2, 3, 4)) # Output: 10
Example: Deploying an Application
python
RunCopy
def deploy(app_name, version="latest"):
print(f"Deploying {app_name} version {version}...")
6. Control Statements
If Statements
Definition: Control the flow of execution based on conditions.
Structure:
python
RunCopy
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
RunCopy
server_status = "running"
if server_status == "running":
print("Server is operational.")
else:
print("Server is down.")
Loops
For Loop
Definition: Iterates over a sequence (like a list, tuple, or string).
Example:
python
RunCopy
for i in range(5):
print(i) # Prints 0 to 4
While Loop
Definition: Repeats as long as a condition is true.
Example:
python
RunCopy
count = 0
while count < 5:
print(count)
count += 1
Example: Checking Server Status
python
RunCopy
servers = ["web", "database", "cache"]
for server in servers:
print(f"Checking {server} status...")
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1. Variables
Overview
Definition: Containers for storing data values.
Naming Conventions: Use descriptive names, start with a letter or underscore, and avoid
spaces and special characters.
Example:
python
RunCopy
age = 30
name = "Alice"
is_active = True
Small Project: User Profile
Create a simple user profile using variables.
python
RunCopy
# User Profile
user_name = "Alice"
user_age = 30
user_email = "[email protected]"
print(f"User Profile:\nName: {user_name}\nAge: {user_age}\nEmail:
{user_email}")
2. Data Types
Overview
Python has several built-in data types.
Integers
Whole numbers.
Example:
python
RunCopy
num1 = 10
num2 = -5
Floats
Decimal numbers.
Example:
python
RunCopy
price = 19.99
tax = 0.07
Strings
Sequence of characters.
Example:
python
RunCopy
greeting = "Hello, World!"
Booleans
Represents True or False.
Example:
python
RunCopy
is_active = True
Small Project: Shopping Cart
Create a simple shopping cart calculator.
python
RunCopy
# Shopping Cart
item_price = 19.99
quantity = 3
total_cost = item_price * quantity * (1 + tax)
print(f"Total cost for {quantity} items: ${total_cost:.2f}")
3. Lists
Overview
Ordered, mutable collections of items.
Creating Lists
Example:
python
RunCopy
my_list = [1, "Python", 3.14, True]
Accessing Elements
Example:
python
RunCopy
first_element = my_list[0] # 1
Modifying Lists
Example:
python
RunCopy
my_list.append("New Element")
my_list.remove("Python")
List Comprehensions
Example:
python
RunCopy
squares = [x**2 for x in range(10)]
Small Project: Contact List
Create a simple contact list management system.
python
RunCopy
# Contact List
contacts = ["Alice", "Bob", "Charlie"]
contacts.append("David")
print("Contact List:")
for contact in contacts:
print(contact)
4. Tuples
Overview
Ordered, immutable collections.
Creating Tuples
Example:
python
RunCopy
my_tuple = (1, "DevOps", 3.14)
Accessing and Unpacking
Example:
python
RunCopy
x, y = (10, 20)
Small Project: Coordinates
Create a coordinate system using tuples.
python
RunCopy
# Coordinates
coordinates = (10.0, 20.0)
x, y = coordinates
print(f"Coordinates: x={x}, y={y}")
5. Dictionaries
Overview
Unordered collections of key-value pairs.
Creating Dictionaries
Example:
python
RunCopy
my_dict = {"name": "Alice", "age": 30}
Accessing and Modifying
Example:
python
RunCopy
age = my_dict["age"]
my_dict["age"] = 31
Small Project: Employee Records
Create a simple employee record system using dictionaries.
python
RunCopy
# Employee Records
employee = {
"name": "Alice",
"age": 30,
"department": "Engineering"
}
print(f"Employee Info: {employee['name']} works in {employee['department']}.")
6. Functions
Overview
Reusable blocks of code.
Defining Functions
Example:
python
RunCopy
def greet(name):
return f"Hello, {name}!"
Default and Variable-Length Arguments
Example:
python
RunCopy
def add_numbers(*args):
return sum(args)
Small Project: Simple Calculator
Create a simple calculator using functions.
python
RunCopy
# Simple Calculator
def add(a, b):
return a + b
def subtract(a, b):
return a - b
print(f"Addition: {add(5, 3)}")
print(f"Subtraction: {subtract(5, 3)}")
7. Control Statements
If Statements
Example:
python
RunCopy
if is_active:
print("User is active")
Loops
For Loop
Example:
python
RunCopy
for i in range(5):
print(i)
While Loop
Example:
python
RunCopy
count = 0
while count < 5:
print(count)
count += 1
Small Project: Number Guessing Game
Create a simple number guessing game.
python
RunCopy
# Number Guessing Game
import random
number_to_guess = random.randint(1, 10)
guess = 0
while guess != number_to_guess:
guess = int(input("Guess a number between 1 and 10: "))
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
else:
print("Congratulations! You guessed it!")
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Project: Task Management System
Description
The application allows users to manage tasks with the following features:
Add a new task
View all tasks
Update a task's status
Delete a task
Implementation
python
RunCopy
# Task Management System
# Initialize an empty list to store tasks
tasks = []
# Function to display the menu
def display_menu():
print("\nTask Management System")
print("1. Add Task")
print("2. View Tasks")
print("3. Update Task Status")
print("4. Delete Task")
print("5. Exit")
# Function to add a new task
def add_task():
title = input("Enter task title: ")
description = input("Enter task description: ")
task = {
"title": title,
"description": description,
"status": "Pending" # Default status
}
tasks.append(task)
print(f"Task '{title}' added successfully!")
# Function to view all tasks
def view_tasks():
if not tasks:
print("No tasks available.")
return
print("\nCurrent Tasks:")
for index, task in enumerate(tasks):
print(f"{index + 1}. Title: {task['title']}, Status:
{task['status']}")
# Function to update task status
def update_task():
view_tasks()
task_index = int(input("Enter the task number to update: ")) - 1
if 0 <= task_index < len(tasks):
new_status = input("Enter new status (Pending/Completed): ")
tasks[task_index]["status"] = new_status
print(f"Task '{tasks[task_index]['title']}' updated to
'{new_status}'!")
else:
print("Invalid task number.")
# Function to delete a task
def delete_task():
view_tasks()
task_index = int(input("Enter the task number to delete: ")) - 1
if 0 <= task_index < len(tasks):
removed_task = tasks.pop(task_index)
print(f"Task '{removed_task['title']}' deleted successfully!")
else:
print("Invalid task number.")
# Main program loop
def main():
while True:
display_menu()
choice = input("Choose an option: ")
if choice == '1':
add_task()
elif choice == '2':
view_tasks()
elif choice == '3':
update_task()
elif choice == '4':
delete_task()
elif choice == '5':
print("Exiting the Task Management System. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Run the program
if __name__ == "__main__":
main()
Features Explained
1. Variables: Used to store user inputs and task details.
2. Data Types: Strings for task titles and descriptions, lists for storing tasks, and
dictionaries for individual task details.
3. Lists: Used to maintain a list of tasks.
4. Tuples: Not explicitly used here, but could be integrated for immutable configurations
(like predefined statuses).
5. Dictionaries: Each task is represented as a dictionary with keys for title, description, and
status.
6. Functions: Modular functions for each functionality (add, view, update, delete).
7. Control Statements: Used for user input handling and menu navigation.