Python Basics V3
Python Basics V3
Python Text
In [2]: # This is a comment, starts with '#'
In [4]: x
Out[4]: 10
In [5]: X = 5
In [6]: X
Out[6]: 5
In [8]: f
Out[8]: 10.3
In [10]: # Addition
x + y
Out[10]: 15
In [11]: # Subtraction
x - y
Out[11]: 5
In [12]: # Multiplication
x * y
Out[12]: 50
In [13]: # Division
int(x / y)
Out[13]: 2
In [ ]:
In [17]: my_name
In [18]: type(my_name)
Out[18]: str
In [21]: my_name.lower()
In [ ]:
if statement in python
Creating Conditions in Python
Syntax:
We write if, followed by the condition (e.g., x == 10), then a colon (:).
==
Meaning: Equal to Example: x == y checks if x is equal to y.
!=
Meaning: Not equal to Example: x != y checks if x is not equal to y.
>
Meaning: Greater than Example: x > y checks if x is greater than y.
<
Meaning: Less than Example: x < y checks if x is less than y.
>=
Meaning: Greater than or equal to Example: x >= y checks if x is greater than or equal to y.
<=
Meaning: Less than or equal to Example: x <= y checks if x is less than or equal to y.
is
Meaning: Object identity (checks if both operands refer to the same object) Example: x is y
checks if x and y refer to the same object in memory.
is not
Meaning: Negation of object identity (checks if operands refer to different objects) Example:
x is not y checks if x and y refer to different objects.
in
Meaning: Membership (checks if a value exists within a sequence) Example: x in y checks if
x is an element in y (where y could be a list, tuple, or string).
not in
Meaning: Negation of membership (checks if a value does not exist within a sequence)
Example: x not in y checks if x is not an element in y.
if condition:
print("Condition is true")
()
In [22]: x = 10 # This is assigning x to value of 10
x == 10 # This is checking if x is equals 10, output: True or False
Out[22]: True
In [23]:
1 == 2 # This is checking if 1 is equal 2
Out[23]: False
In [25]: 1 != 2
Out[25]: True
Correct
Instructions:
Create two integer variables k and v .
Assign any values of your choice to k and v .
Write an if statement to check if k is greater than 10:
If k > 10 , add k and v together and print the result.
If k <= 10 , subtract v from k and print the result.
In [ ]:
for loop
User input
In [12]: k = 9
v = 25
-16
In [3]: score = 50
In [ ]:
In [71]: text.title()
In [72]: text.split()
In [79]: text.split('name')
Out[86]: 'Paul-Adeoye,Faith-Jumoke,Glory-Ade'
In [87]: names.split(',')
In [88]: names.split(',')[0]
Out[88]: 'Paul-Adeoye'
In [89]: names.split(',')[0].split('-')
In [90]: names.split(',')[0].split('-')[0]
Out[90]: 'Paul'
In [95]: names
Out[95]: 'Paul-Adeoye,Faith-Jumoke,Glory-Ade'
In [92]: names.find('Faith')
Out[92]: 12
Out[96]: 'Paul-Deaoye,Faith-Jumoke,Glory-Dea'
Out[99]: 34
Python Functions
In [ ]: # Create the functions
# Write the blocks of code to perform an action
# Call the function
In [ ]:
In [ ]:
In [19]: print(names)
Out[20]: 3
In [21]: names[2].upper()
Out[21]: 'YAHAYA'
In [ ]:
In [23]: len(participants_age)
Out[23]: 6
Out[24]: 41
In [25]: participants_age[2]
Out[25]: 34
In [26]: type(participants_age[2])
Out[26]: int
In [ ]:
Abayomi
Musa
Yahaya
Abayomi
Musa
Yahaya
12
15
34
20
57
29
Out[31]: range(0, 5)
In [32]:
range(1,10)
**
0
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
10
11
Out[35]: '*****'
*
**
***
****
*****
In [ ]:
Python Function
In [37]: ## You first define a function
## write the function logic
## Call the function
In [39]: yahaya()
String formatting
In [40]: my_name = "Ade"
print(f"Welcome {my_name}")
Welcome Ade
In [43]:
yahaya("Kelvin")
In [ ]:
In [44]: input()
Out[44]: '7'
Out[8]: '6'
Out[9]: 3
In [ ]:
In [ ]:
Key Points:
In [ ]:
In [ ]:
In [ ]:
Key Concepts:
Indexing: Each element in a list is associated with an index, starting from 0.
1. Positive index: Starts from 0, moving left to right.
2. Negative index: Starts from -1, moving right to left.
[1, 2, 3]
In [3]: my_list[-7]
Out[3]: 0
In [ ]:
In [ ]:
Mutability
In Python, mutability refers to whether an object’s state can be
changed after it has been created. An object that can be changed
is called mutable object, while an object that cannot be changed is
called immutable object. Let's break this down with examples:
In [ ]:
Immutable Variables
In [ ]:
Tuple (tuple): Once a tuple is created, you cannot change its content (no adding,
removing, or modifying elements).
--------------------------------------------------------------------
-------
TypeError Traceback (most recent cal
l last)
Cell In[16], line 2
1 my_tuple = (1, 2, 3)
----> 2 my_tuple[0] = 10
In [ ]:
In [ ]:
Mutable Variables
These variables can be changed after their creation. Both the
elements and their order can be modified.
List: A list in Python is mutable. You can add, remove, or modify elements.
[10, 2, 3]
In [ ]:
Set: A set is also mutable, meaning you can add or remove elements. However, a
set does not allow duplicate elements, and the order of elements is not preserved.
{1, 2, 3, 4}
In [ ]:
A list is like a box with multiple slots, where you can replace or
remove any item. A set is like a basket that can hold unique
objects, where you can add or remove items, but you can't predict
the order. A tuple is like a sealed container where once the items
are placed inside, you cannot modify them.
In [ ]:
In [ ]:
Exercise
localhost:8888/notebooks/Python Basics/Python Basics.ipynb#The-problem-here-is-that-we-have-some-string-data-mixed-with-numeric-data,-and-we-need-to… 15/33
10/10/2024, 23:31 Python Basics - Jupyter Notebook
Practice Exercise 1:
Problem: Write a program that asks for two numbers and outputs their sum.
Steps:
Practice Exercise 2:
Problem: We need to create a system that checks if a user can withdraw money based on
their account balance and the amount they want to withdraw.
Steps:
1. Ask the user for their current balance (data type - float).
2. Ask the user how much they want to withdraw (data type - float).
3. Check if the balance is sufficient for the withdrawal.
4. Print a message to approve or deny the withdrawal based on the balance.
Solution to Exercise 1
In [18]: def add(x, y):
# This function takes in x, y
# Change the data type to integer (number)
# and perform addition operation using '+' sign
z = int(x) + int(y)
In [ ]:
Solution to Exercise 2
In [21]: # Define a function 'withdraw' that takes in two arguments:
# 'current_balance' (the balance in the account)
# and 'withdraw_amount' (the amount to withdraw).
def withdraw(current_balance, withdraw_amount):
## Convert the input values to float, ensuring
## we are working with numbers that can have decimal points.
current_balance = float(current_balance)
withdraw_amount = float(withdraw_amount)
# Check if the current balance is greater
# than or equal to the withdrawal amount.
if current_balance >= withdraw_amount:
# If there is enough balance, subtract
# the withdrawal amount from the current balance.
new_balance = current_balance - withdraw_amount
In [ ]:
[40 70 35 25 45 80 55 23 65 30 75 50]
In [41]: ages.shape
Out[41]: (12,)
In [42]: ages.ndim
Out[42]: 1
In [ ]:
In [ ]:
Minimum Age: 23
Maximum Age: 80
In [ ]:
In [ ]:
In [ ]:
Out[101]:
Name HoursWorked MonthlySalary
Read data from your local directory, note you need to copy this file
from your download folder to this working directory (folder), or
make sure to link the file properly.
Out[108]:
Unique_ID_Chisquares Participant_ID_Chisquares Collection_Wave_Chisquares Data_Sou
0 670559c19e6dfaa1a37e2514 NaN 1
1 670559c29e6dfaa1a37e2516 NaN 1
2 670559c39e6dfaa1a37e2518 NaN 1
3 670559c39e6dfaa1a37e2519 NaN 1
4 670559c39e6dfaa1a37e251a NaN 1
Look for the desired columns for the analysis (hints: columns that
starts with 'X_')
Out[109]:
X_1_25_1_0_name X_2_25_1_0_hoursworked X_3_25_1_0_monthlysalary
2 J. K. 1600.0 5000
In [ ]:
Or you can use this easy method, given the hint above
Out[110]:
X_1_25_1_0_name X_2_25_1_0_hoursworked X_3_25_1_0_monthlysalary
2 J. K. 1600.0 5000
In [ ]:
Out[111]:
name hoursworked monthlysalary
2 J. K. 1600.0 5000
In [ ]:
In [ ]:
Out[112]:
hoursworked
count 25.000000
mean 35982.800000
std 170116.833293
min 8.000000
25% 211.000000
50% 1500.000000
75% 2080.000000
max 852425.000000
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 49 entries, 0 to 48
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 40 non-null object
1 hoursworked 25 non-null float64
2 monthlysalary 24 non-null object
dtypes: float64(1), object(2)
memory usage: 1.3+ KB
Out[114]: 0 500000
1 2300
2 5000
3 NaN
4 500000
5 £1500
6 R20000
7 30000
8 NaN
9 $3000
10 NaN
11 207,000
12 1000
13 2500
14 NaN
15 150,000
16 NaN
17 150,000
18 400000
19 145000
Name: monthlysalary, dtype: object
Regex
Regex (short for regular expression) is a sequence of characters that defines a search
pattern. It’s used for finding, matching, and manipulating text.
Example:
To match all numbers in a string, you might use the pattern \d+ , which means "one or
more digits."
In [115]: import re
text = "Price is $3000 and tax is 500"
pattern = r'\d+' # Match one or more digits
# Find all numbers
numbers = re.findall(pattern, text)
print(numbers) # Output: ['3000', '500']
['3000', '500']
Out[116]:
name hoursworked monthlysalary
2 J. K. 1600.0 5000
In [95]: data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 49 entries, 0 to 48
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 40 non-null object
1 hoursworked 25 non-null float64
2 monthlysalary 23 non-null float64
dtypes: float64(2), object(1)
memory usage: 1.3+ KB
🎉 Great news! 🎉
We've successfully transformed the monthlysalary column into the desired numeric
format! 💪
Now it's all cleaned up and ready for further analysis. 🚀
In [ ]:
Out[75]: name J. K.
hoursworked 1600.0
monthlysalary 5000.0
Name: 2, dtype: object
Out[77]:
name hoursworked monthlysalary
2 J. K. 1600.0 5000.0
You can also select a specific value from the DataFrame using
.iloc[ ], which accesses data by position
Out[78]:
hoursworked monthlysalary
0 3000.0 500000.0
1 1500.0 2300.0
Filtering Data
For example, you can filter employees who work more than 40
hours per week:
Out[80]:
name hoursworked monthlysalary
2 J. K. 1600.0 5000.0
You can achieve the same result using the .query() method:
Out[81]:
name hoursworked monthlysalary
2 J. K. 1600.0 5000.0
In [ ]:
Out[82]:
name hoursworked monthlysalary
Out[83]:
name hoursworked monthlysalary
Out[84]:
name hoursworked monthlysalary
2 J. K. 1600.0 5000.0
10 0 0.0 0.0
Out[96]:
name hoursworked monthlysalary
2 J. K. 1600.0 5000.0
Out[98]:
name hoursworked monthlysalary level
level
Junior 7
Mid-Level 2
Senior 14
Name: name, dtype: int64
Out[100]:
level monthlysalary
0 Junior 1557.142857
1 Mid-Level 3225.500000
2 Senior 226214.285714
In [ ]:
In [ ]: