Share
Explore

# Python Workbook for Beginners: From First PrinciplesPython Workbook for Beginners: From First Principles

Visual Roadmap of the Landscape of Python Programming:

Welcome to the world of Python!
This workbook will guide you through the foundational concepts of Python programming, starting from the very basics. By the end of this workbook, you'll have a solid understanding of Python's core concepts and will be ready to explore more advanced topics.

Future Work:
Python Data analysis on HR or other data sets.
How use to PYTHON in Excel, to amplify the Data Analysis we an do with Excel.
PowerBI: How to us PYTHON to create custom Visuals in Power BI.
1. Variable Declaration and Assignment
Concept:
In Python, a variable is used to store data that can be used and manipulated throughout a program. Variables are declared by simply assigning a value to a name.
Example:
pythonCopy code
x = 5
name = "Alice"

Drill 1.1:
Declare two variables: age with a value of 20 and city with a value of "New York".
Solution:
pythonCopy code
age = 20
city = "New York"

2. Variable Comparison
Concept:
Variables can be compared using comparison operators. The result of a comparison is a Boolean value (True or False).
Example:
pythonCopy code
x = 10
y = 20
result = x < y # True because 10 is less than 20

Drill 2.1:
Declare two variables a = 5 and b = 8. Check if a is greater than b.
Solution:
pythonCopy code
a = 5
b = 8
is_a_greater = a > b # False

3. If-Then Statements
Concept:
The if statement allows you to execute a block of code if a condition is True.
Example:
pythonCopy code
age = 18
if age >= 18:
print("You are an adult.")

Drill 3.1:
Declare a variable temperature = 30. If the temperature is above 25, print "It's hot!"
Solution:
pythonCopy code
temperature = 30
if temperature > 25:
print("It's hot!")

### In Python, the if-then-else construct is used to make decisions based on conditions. Here's the basic structure:

pythonCopy code
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

The elif and else parts are optional, and you can have multiple elif statements if needed.
Example:
Let's say we want to categorize a person's age:
pythonCopy code
age = 25

if age < 13:
print("Child")
elif age < 18:
print("Teenager")
elif age < 60:
else:
print("Senior")

In this example, since age is 25, the output will be:
Copy code

The program checks each condition from top to bottom. Once it finds a condition that evaluates to True, it executes the corresponding block of code and then skips the rest of the if-elif-else construct. If none of the conditions are True, it executes the else block (if provided).

4. Switch-Case Statements
Note: Python doesn't have a built-in switch-case construct. However, we can mimic this behavior using dictionaries.
Concept:
A switch-case allows you to execute different blocks of code based on a variable's value.
Example:
pythonCopy code
def switch_case(day):
switcher = {
1: "Monday",
2: "Tuesday",
3: "Wednesday",
}
return switcher.get(day, "Invalid day")

print(switch_case(2)) # Outputs: Tuesday

Drill 4.1:
Create a switch-case function for the first 3 months of the year. If the input is 1, it should return "January", and so on.
Solution:
pythonCopy code
def month_name(month):
months = {
1: "January",
2: "February",
3: "March",
}
return months.get(month, "Invalid month")

print(month_name(2)) # Outputs: February

### Let's break down the provided code step by step.

pythonCopy code
def month_name(month):

This line defines a new function named month_name that takes a single parameter, month.
The purpose of this function, as suggested by its name, is to return the name of a month based on a given numeric value.
pythonCopy code
months = {
1: "January",
2: "February",
3: "March",
}

Inside the function, we declare a dictionary named months. In Python, a dictionary is a collection of key-value pairs. In this particular dictionary:
The keys are integers representing month numbers (1 for January, 2 for February, and so on).
The values are strings representing the names of the months.
So, the dictionary months maps month numbers to their respective names. In this example, we've only defined mappings for the first three months, but in a real-world scenario, you'd likely have mappings for all 12 months.
pythonCopy code
return months.get(month, "Invalid month")

This line is where the function returns its result. The get() method is a built-in method for dictionaries in Python. It's used to retrieve the value for a given key. The get() method takes two arguments:
The key you want to look up (in this case, month).
A default value to return if the key is not found in the dictionary.
Here's what happens in this line:
If the month value (the function's parameter) is found in the months dictionary, the corresponding month name is returned.
If the month value is not found (for example, if someone calls month_name(5) but we haven't defined a mapping for May), the function will return the string "Invalid month" because that's the default value we provided to the get() method.
In Summary:
The month_name function takes a numeric month value as input and returns the corresponding month's name. If the provided month number isn't defined in the months dictionary, the function returns "Invalid month". This function showcases the utility of Python dictionaries and the flexibility of the get() method for safe key lookups.
5. Looping: For and While
Concept:
Loops allow you to execute a block of code multiple times. You will use variables and variable comparisons to control the number of times the LOOP is executed.
Watch out! If you don’t manage your LOOP CONTROLLER VARIABLES PROPERLY — You will be caught in an infinite loop!
Example:
pythonCopy code
# Using for loop
for i in range(3):
print(i)

# Using while loop
count = 0
while count < 3:
print(count)
count += 1

Drill 5.1:
Use a for loop to print numbers from 5 to 10.
Solution:
pythonCopy code
for num in range(5, 11):
print(num)

6. Arrays (Lists in Python) (resume here)
Concept:
A list is a collection of items.
Example:
pythonCopy code
fruits = ["apple", "banana", "cherry"]

Drill 6.1:
Declare a list of three colors: red, blue, and green.
Solution:
pythonCopy code
colors = ["red", "blue", "green"]

7. Iterating Over Arrays (Lists)
Concept:
You can use loops to iterate over each item in a list.
Example:
pythonCopy code
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Drill 7.1:
Print each color from the colors list declared in Drill 6.1.
Solution:
pythonCopy code
colors = ["red", "blue", "green"]
for color in colors:
print(color)

8. Handling Numbers and Strings
Concept:
Python provides various operations for numbers and strings.

### Let's dive into a drill that encompasses strings, string comparison operators, and substrings.

Drill: Strings and Their Operations
Objective: Understand and practice string manipulations, comparisons, and substring operations in Python.
1. Basic String Declaration
Task: Declare a string variable named greeting with the value "Hello, World!".
Solution:
pythonCopy code
greeting = "Hello, World!"

2. String Comparison
Task: Declare two string variables: string1 with the value "apple" and string2 with the value "banana". Compare the two strings to see if they are equal and print the result.
Solution:
pythonCopy code
string1 = "apple"
string2 = "banana"

result = string1 == string2
print(result) # Outputs: False

3. String Case-Insensitive Comparison
Task: Given two strings stringA = "Python" and stringB = "python", compare them in a case-insensitive manner.
Solution:
pythonCopy code
stringA = "Python"
stringB = "python"

result = stringA.lower() == stringB.lower()
print(result) # Outputs: True

4. Substring Check
Task: Check if the word "sun" is present in the string "The sun is shining.".
Solution:
pythonCopy code
sentence = "The sun is shining."
substring = "sun"

result = substring in sentence
print(result) # Outputs: True

5. Extracting a Substring
Task: Extract the word "world" from the string "Hello world!".
Solution:
pythonCopy code
text = "Hello world!"
extracted_word = text[6:11]
print(extracted_word) # Outputs: world

6. String Concatenation
Task: Concatenate the strings "Python" and "Rocks!" with a space in between.
Solution:
pythonCopy code
string1 = "Python"
string2 = "Rocks!"
concatenated_string = string1 + " " + string2
print(concatenated_string) # Outputs: Python Rocks!

7. String Repetition
Task: Repeat the string "echo" 3 times with a dash in between.
Solution:
pythonCopy code
word = "echo"
repeated_word = (word + "-") * 2 + word
print(repeated_word) # Outputs: echo-echo-echo

Remember, strings are one of the most commonly used data types in programming. Mastering string operations is crucial for various tasks, from simple text manipulations to complex text processing algorithms. Practice regularly to solidify your understanding!
Example:
pythonCopy code
# Numbers
x = 5 + 3 # Addition

# Strings
greeting = "Hello, " + "Alice!" # Concatenation

Drill 8.1:
Concatenate two strings: "Python" and "Rocks!".
Solution:
pythonCopy code
message = "Python" + " Rocks!"
print(message) # Outputs: Python Rocks!

This workbook provides a foundational understanding of Python's core concepts. As you progress, remember to practice regularly, explore further, and always stay curious. Happy coding!
Python Functions Workbook: Exercises and Solutions
Introduction:
Functions are reusable blocks of code that perform a specific task. They can take inputs, process them, and return a result. This section will guide you through creating and invoking functions in Python.
Exercise 1: Basic Function Creation
Create a function named greet that prints "Hello, World!".
Solution:
pythonCopy code
def greet():
print("Hello, World!")

greet()

Exercise 2: Function with Parameters
Create a function named say_hello that takes a name as a parameter and prints "Hello, [name]!".
Solution:
pythonCopy code
def say_hello(name):
print(f"Hello, {name}!")

say_hello("Alice")

Exercise 3: Function Returning a Value
Create a function named add that takes two numbers and returns their sum.
Solution:
pythonCopy code