Ipython¶
IPython is a platform that allows you to interactively work with your code and data. To access it, simply type ipython in the terminal. In Python, you can perform various mathematical calculations using basic operators, such as +(addition), -(subtraction), /(division), *(multiplication), % (modulo), and exponentiation (**):
2+3
2-3
2/3
2*3
2**3 # power
8
Let us start with some foundational tasks: assigning both a text and a number to variables, and then verifying their data types
pi0=3.14
pi1='approximate with two digits'
print(pi0)
print(pi1)
print(type(pi0))
print(type(pi1))
Python supports integer, floats, complex, and boolen.
boolen1= (3 < 4)
boolen2= (4 < 3)
complex = 2 + 0.5j
Module¶
A module (or library) is a collection of data, functions, and resources bundled for execution. After installing the library, you can seamlessly access its functions within Python by importing it.
import os # import os module
os.getcwd() # Run to see the current working directory, The Working directory is a directory that the python actively accesses to its objects, this directory is called the working directory
'/home/sam/GITHUBS/python/Python-for-Data-Analysis/notes'
Put the command in the help to get infor about the function
To obtain information about a function, you can use the help() function in Python. Here's how you can use it:
# Use the help() function to get information about a function
help(function_name)
Replace function_name with the name of the function you want to get information about. When you run this command, Python will provide documentation and details about the specified function, including its parameters, purpose, and usage.
help(os.getcwd)
Help on built-in function getcwd in module posix:
getcwd()
Return a unicode string representing the current working directory.
The following code imports NumPy (NUMerical PYthon), which offers valuable array structures for data manipulation. It's common to use the alias "np" for NumPy to make it more convenient to work with:
# Import NumPy with the alias "np"
import numpy as np
By importing NumPy this way, you can access its functions and classes using the shorter alias "np" throughout your code. For example, you can use np.array() to create arrays or np.mean() to calculate the mean of an array.
Data Structures¶
Python provides a versatile array of valuable data structures, including lists, sets, dictionaries, and the ability for programmers to define their own custom structures known as classes.
list¶
A list is a sequence of values assigned to a variable. The individual values within a list are referred to as elements or items.
weights=[20,15,19,21,16]
type(weights)
colors=['red','blue','green','black','white']
colors
a,*b,c=[1,2,3,4]
You can access the values of a list by using square brackets.
colors[1:3] # Slicing
colors[:3] # The 0 can be left-out
colors[0:3:2]
colors[::-1] # Reversing with a negative step size
colors[3:]
colors[1]
colors[-1] # Indexing from the end
weights[1]=20
weights.append(30) # Appending
weights.sort() # Sort list
weights.extend([30, 31]) # Extends two ellement to list
weights.append([30,20]) # Extends a list to list
weights.remove(30) # Remove the occurence of an element
weights.index(21)
colors + weights # Adding two list together
Tuple¶
Tuple is a sequence of objects like list, but it is immutable. To define tuple, Python uses the parenthesis:
A tuple is a sequence of objects similar to a list, but unlike a list, it is immutable, meaning its elements cannot be changed after creation. To define a tuple in Python, you use parentheses ():
python Copy code my_tuple = (1, 2, 3, "hello") In the example above, my_tuple is defined as a tuple containing integers and a string. Once a tuple is created, you cannot modify its elements. This immutability is the key distinction between tuples and lists in Python.
my_tuple = (1,2,'red', 'blue', 'green', 'black', 'white')
type(my_tuple)
my_tuple[1:3]
In the example above, my_tuple is defined as a tuple containing integers and a string. Once a tuple is created, you cannot modify its elements. This immutability is the key distinction between tuples and lists in Python.
Dictionary¶
Dictionary is a generalized form of list, unlike the list its indices can be any type of values. A dictionary maps a set of objects (keys) to another set of objects (values).
Dictionary includes key and items, the key is actually indices and item is the values. A Python dictionary is a mapping of unique keys to values. Use the curly brackets to construct the dictionary, separate the key and value with colons (:) and with commas (,)between each pair. Keys must be quoted. We can print out the dictionary by printing the reference to it.
A dictionary in Python is a generalized form of a list where the indices, known as keys, can be of any data type. A dictionary maps a set of keys to their corresponding values.
In Python, a dictionary consists of key-value pairs enclosed in curly braces {}. Each key is separated from its associated value by a colon : and the key-value pairs are separated by commas ,. Keys are typically enclosed in quotes (either single or double), especially if they are strings. You can print a dictionary by referencing it. Here's an example:
my_dict = {
'name': 'Ryan',
'age': 4,
'sex': 'M'
}
my_dict.values()
my_dict.keys()
my_dict.items()
my_dict['name']
my_dict['age']
4
In this example, `my_dict`` is a dictionary with keys "name," "age," and "sex", each associated with respective values. The values are accessed using the keys. When printed, it would display the contents of the dictionary.
n-dimensional array¶
The NumPy has a very useful array data structure that called ndarray, which is short for n-dimensional array. The following gives an one dinsion array of list.
a = [1., 2., 3.]
ar1=np.array(a)
ar1[0] #first array
ar1[0:2]# # first and second elements
The NumPy indexing is similar the python list. The following creates a two dimensional array, consisting of two rows and four columns:
X = [[1, 2, 3, 4], [5, 6, 7, 8]]
ar2by4=np.array(X) # creates the array
ar2by4.dtype # show the type
ar2by4.astype(np.int32) # change the type
ar2by4.shape #
ar2by4.ndim # number of dimension
For indexing of arrays with more than one dimension or axis, we separate our indexing or slicing operations by commas.
ar2by4[0,1] # element on first row and second column
ar2by4[:,1] # second column
ar2by4[0,:] # first row
ar2by4[[0,1],[2,3]] # elements on first and second rows and third and fourth columns.
The mathematical operation (+, -, /, *, and **) can be applied directly on the array.
X=np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
Y=np.array( [[0, 1, 0, 1], [1, 0, 1, 0]])
Z=np.array( [[0, 1, 0, 1]])
X+1
X*2
X+Y
X+Z
X-Y
array([[1, 3, 3, 5],
[5, 7, 7, 9]]) Conditionals¶
The value True and False are referred to as logical values that used the same in Python, their corresponding values are 1 and 0. Run the following codes and explains what the codes do.
The values True and False are referred to as Boolean values in Python. They are used to represent truth values, with True indicating a condition is true and False indicating a condition is false. While True and False are often used for logical comparisons, it's important to note that their corresponding integer values are not always 1 and 0.
In Python, you can check the integer values of True and False using the int() function:
print(int(True)) # Outputs: 1
print(int(False)) # Outputs: 0
However, the value of True as 1 and False as 0 is a convention used in some contexts, especially when performing arithmetic operations with Boolean values. Run the following codes and explains what the codes do.
8 < 9
9 < 8
x = 3
y = 9
x < y
Commands involving control structures frequently incorporate conditional statements that utilize comparison operator (>, <, =>, <=, ==, !=, ~, is)
3 < 4
3 != 4
3 == 4
3 is 4
'hi' == 'h' + 'i'
'HI' != 'hi'
[1, 2] != [2, 1]
The structure command of if is as below.
if(condition1)
cons.expr
elif(condition2)
alt.expr1
else
alt.expr2
If condition1 satisfies then cons.expr run otherwise if condition2 satisfies alt.expr1 run, otherwise alt.expr2 runs.
x = 4
y = 4
if x < y:
print('x is less than y')
elif x > y:
print('x greater than y')
else:
print(' x and y are equal')
Function¶
In the context of programming, a function is a sequence of statements that performs a specific computation. Functions consist of three parts: arguments, a script, and an output. Python has two types of functions: built-in functions, which are integral to Python's core or packaged within libraries, and user-defined functions, which are created by the user.
Built-in function¶
Python includes a variety of functions in its core that are consistently accessible, [see](https: // docs.python.org/3/library/functions.html)
x = [1, 2, 3]
type(x)
len(x)
min(x)
To round the value, you can use the round(value, size) function
round(0.12345, 2)
round(0.12345, 3)
User function¶
Functions has three parts; argument, script, and output. It has simple structure
def name (argument):
script
return output
For instance, let's write a function that takes two arguments, adds them together, and returns the result:
def add_numbers(a, b):
result = a + b
return result
# Example usage of the function
num1 = 5
num2 = 7
sum_result = add_numbers(num1, num2)
print("Sum:", sum_result)
In this example, the add_numbers function takes two arguments (a and b), adds them together, and returns the result. When you call the function with add_numbers(num1, num2), it computes the sum of num1 and num2, which is 12 in this case. The result is then printed to the console.
Loops¶
When you have a repetitive task, you can use either a for loop or a while loop. The structure of a while loop is as follows:
while condition:
code goes here
In a while loop, the code inside the loop will be executed repeatedly as long as the specified condition remains True. Once the condition becomes False, the loop terminates, and the program continues with the next instruction after the loop.
count = 0
while count < 10:
print(count)
count = count + 1
You can use the else clause with a while loop in Python. The else block associated with a while loop is executed when the loop's condition becomes False, and the loop naturally exits.
count = 0
while count < 10:
print(count)
count = count + 1
else:
print('count is greater than 10')
In this example, the else block will be executed when count becomes equal to or greater than 10, and the while loop terminates.
The for loop in Python has the following structure:
for variable in iterable:
code
iterable = (0,1,2,3,5,6)
for i in iterable:
if i == 0:
print('i is zero')
next
if a % 2 == 0:
print('i is a even number')
else:
print('i is a odd number')
Sequences are often represented using range(start, end, step), making it a valuable choice.
for i in range(6):
print(i)
This will print numbers 0 through 5.
for i in range(6):
print(i)
else:
print('The loop stops at', i)
0 1 2 3 4 5 The loop stops at 5
This will print numbers 0 through 5, at the end print The loop stops at 5
looping through even number from 0 to 6
for i in range(0,6,2):
print(i)
list Comprehension¶
List comprehension in Python is a concise method for generating a list from an existing sequence. The general syntax for list comprehension is as follows:
new_list = [expression for item in iterable if condition]
Here's a breakdown of the components:
new_list: This is the new list that will be created.
expression: It represents an expression that defines how each item in the iterable will be transformed and added to the new list.
item: It is a variable that takes on each element of the iterable one at a time.
iterable: This is the sequence or iterable from which the elements will be taken.
condition (optional): It specifies an optional filter that determines whether an element from the iterable is included in the new list.
List comprehensions are a powerful and readable way to create lists in Python, and they are often used when you want to apply a transformation or filter to elements from an existing iterable. Below is a list generated using a for loop; rewrite it using a list comprehension.
Original list generation using a for loop:
x = []
for i in range(3):
for j in range(2):
x.append((i, j))
print(x)
List comprehension equivalent:
x=[(i, j) for i in range(3) for j in range(2)]