# Numbers and strings
= 42
integer_num = 3.14
float_num = "Hello, Python!"
string_text
# List: mutable, ordered collection
= ["apple", "banana", "cherry"]
fruits
# Tuple: immutable, ordered collection
= (1920, 1080)
dimensions
# Dictionary: unordered, key-value pairs
= {"name": "Alice", "age": 30, "city": "New York"}
person
# Set: unordered collection of unique items
= {1, 2, 3, 4, 5}
unique_numbers
print("Integer:", integer_num)
print("Float:", float_num)
print("String:", string_text)
print("List of fruits:", fruits)
print("Tuple of dimensions:", dimensions)
print("Dictionary of person:", person)
print("Set of unique numbers:", unique_numbers)
Python basics
Data types
in Python, understanding data types and structures is essential for writting effective code. Data types determine the kind of data a variable can hold, while data structures allow you to organize and manage that data efficiently.
- Numbers: Represent numerical values, including integers and floating-point numbers.
- Strings: Represent sequences of characters, used for text manipulation.
- Booleans: Represent truth values, either True or False.
- Lists: Ordered collections of items, allowing for duplicate values and mutable operations.
- Tuples: Ordered collections of items, similar to lists but immutable.
- Dictionaries: Unordered, Key-value pairs that allow for efficient data retrieval based on unique keys.
- Sets: Unordered collections of unique items, useful for membership testing and eliminating duplicates.
Control flow and Loops
Control flow in Python allows you to make decisions and execute different blocks of code based on conditions. Loops enable you to repeat a block of code multiple times.
Best practices for control flow and loops include: - Keep conditions simple and clear. Break down complex conditions into smaller parts. - Use meaningful variable names to enhance readability. - Avoid deeply nested loops and conditions to maintain code clarity. - Use comments to explain the purpose of complex conditions or loops. - Test edge cases to ensure your control flow behaves as expected.
# Conditional statements
= 10
x if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
# For loop: iterating over a list
for i in range(5):
print("Iteration:", i)
# While loop: continues until a condition is met
= 0
count while count < 5:
print("Count is:", count)
+= 1 count
Python for R users
Install and libraries
-m pip install pandas python3
import pandas as pd
import numpy as np
import matplotlib as plt
## Use a function from library, first specify the library nickname and then
## the function name, separated by a dot:
7) np.log(
library(dplyr)
Pandas data frame
The syntax for the python involves a single argument corresponding to a type of object called a dictionary (a dictionary is defined with curly brackets) whose named entries each contain a python list ([1,2,3,4] and [5,6,7,8]) of the values that will form a column.
= pd.DataFrame(
df
{'a': [1,2,3,4],
'b': [5,6,7,8]
}
)print(df)
Variable
Number
String
Tuple
List
: Mutable, containerDictionary
: Mutable, containerSet
: Mutable, containerNone
: empty value
tuple = (1, 2, 3)
list = [1, 2, 3]
dict = {"ele1":1, "ele2":2, "ele3":3}
Operators
Numerical Operators: - <
: less than - >
: greater than - <=
: less than or equal to - >=
: greater than or equal to - ==
: equal to - !=
: not equal to
String Operators: - ==
: equal to - !=
: not equal to
Logical Operators: - and - or - not
Conditional execution
Conditional execution in Python is achieved using the if/else construct (if and else are reserved words).
# Conidtional execution
= 10
x if x > 10:
print("I am a big number")
else:
print("I am a small number")
# Multi-way if/else
= 10
x if x > 10:
print("I am a big number")
elif x > 5:
print("I am kind of small")
else:
print("I am really number")
Iteration/Lopps
Two looping constructs in Python
For
: used when the number of possible iterations (repetitions) are known in advanceWhile
: used when the number of possible iterations (repetitions) can not be defined in advance. Can lead to infinite loops, if conditions are not handled properly
for customer in [“John”, “Mary”, “Jane”]:
print(“Hello ”, customer)
print(“Please pay”)
collectCash()
giveGoods()
= 9
hour_of_day while hour_of_day < 17:
moveToWarehouse()
locateGoods()
moveGoodsToShip()= getCurrentTime() hour_of_day
What happens if you need to stop early? We use the break
keyword to do this.
It stops the iteration immediately and moves on to the statement that follows the looping
while hour_of_day < 17:
if shipIsFull() == True:
break
moveToWarehouse()
locateGoods()
moveGoodsToShip()= getCurrentTime()
hour_of_day collectPay()
What happens when you want to just skip the rest of the steps? We can use the continue
keyword for this.
It skips the rest of the steps but moves on to the next iteration.
for customer in ["John", "Mary", "Jane"]:
print(“Hello ”, customer)
print(“Please pay”)
= collectCash()
paid if paid == false:
continue
giveGoods()
Exceptions
- Exceptions are errors that are found during execution of the Python program.
- They typically cause the program to fail.
- However we can handle them using the ‘try/except’ construct.
= input("Please enter a number: ")
num try:
= int(num)
num print("number squared is " + str(num**2))
except:
print("You did not enter a valid number")
General functions
help()
type()
len()
range()
list()
tuple()
dict()
Reference
- https://www.py4e.com/
- https://omgenomics.com/
- https://www.coursera.org/learn/bioinformatics
- http://do1.dr-chuck.com/pythonlearn/EN_us/pythonlearn.pdf
- https://www.py4e.com/html3
- http://do1.dr-chuck.com/pythonlearn/EN_us/pythonlearn.epub
- Primer on Python for R Users
- An introduction to Python for R Users
- Datanovia: Master Data Science, Machine Learning and Data Visualization with Python and R.