Programming basics for Biostatistics 6099

Basics of Python programming

Zhiguang Huo (Caleb)

Tuesday Oct 10th, 2023

Outlines

Jupyter Notebook

How to start Jupyter Notebook

Recommended approach in this class

How to Run Jupyter Notebook

Review Jupyter Notebook markdown (1)

# Header 1
## Header 2
### Header 3
#### Header 4
##### Header 5
###### Header 6
Plain text  
End a line with two spaces to start a new paragraph.  
*italics* and _italics_  
**bold** and __bold__  
<span style="color:red">color</span>  
superscript^2^  
~~strikethrough~~  
[link](www.rstudio.com)   

Review Jupyter Notebook markdown (2)

![](https://caleb-huo.github.io/teaching/2023FALL/logo.png){width=50%}
$A = \pi \times r^{2}$
***

Review Jupyter Notebook markdown (3)

* unordered list
* item 2
    + sub-item 1
    + sub-item 2
1. ordered list
2. item 2
    + sub-item 1
    + sub-item 2

Three ways to run python code

print("hello")
print("hello")
python hello.py

4 basic data type

type(1)
## <class 'int'>
type(3.14)
## <class 'float'>
type("Hello")
## <class 'str'>
type(True)
## <class 'bool'>
type(False)

Conversion among 4 basic data types

int(1.1)
## 1
str(1.1)
## '1.1'
float("3.15")
## 3.15
int(True)
## 1
bool(0)
## False
str(False)
## 'False'

3 basci python data structure

list

names = ["Alice", "Beth", "Carl"]
len(names)
## 3
names[0]
## 'Alice'
names[-1]
## 'Carl'
names[0] = "Alex"
names
## ['Alex', 'Beth', 'Carl']

Tuple

names = ("Alice", "Beth", "Carl")
names2 = "Alice", "Beth", "Carl"
len(names)
## 3
names[0]
## 'Alice'
names[-1]
## 'Carl'
names[0] = "Alex"
names

list and tuple

a = [3,1]
tuple(a)
## (3, 1)
b = (3,1)
list(b)
## [3, 1]
sorted(a)
## [1, 3]
max(a)
## 3
min(b)
## 1

subsetting of list

data = [[1,2,3], [2,3,4]]
len(data)
## 2
data[1]
## [2, 3, 4]
data[1][1]
## 3

dictionary

phonebook = {"Alice": 2341, 
            "Beth": 4971,
            "Carl": 9401
}
phonebook
## {'Alice': 2341, 'Beth': 4971, 'Carl': 9401}
phonebook["Alice"]
## 2341
items = [("Name","Smith"), ("Age", 44)]
d = dict(items)
d
## {'Name': 'Smith', 'Age': 44}
d = dict(Name="Smith", Age=44)
d
## {'Name': 'Smith', 'Age': 44}

Basic python operators

2*4
## 8
2**4 ## raise to the power
## 16
7//4
## 1
"Hello" + "World"
## 'HelloWorld'
False and True
## False
False or True
## True
a = 10
a = a * 5
print(a)
## 50
a = 10
a *= 5
print(a)
## 50

Basic string operators

a = "greetings"
len(a)
## 9
a[0]
## 'g'
a[len(a) - 1]
## 's'
a[0:4]
## 'gree'
a[4]
## 't'

Basic string operators

a = "Hello"
a = a + "World"
print(a)
## HelloWorld
a = "Hello"
a += "World"
print(a)
## HelloWorld

Basic string operators

a = "greetings"
a[1:]
## 'reetings'
a[:3]
## 'gre'
a[:-1]
## 'greeting'
a[0:7:2] ## step size 2, default is 1 
## 'getn'
a[-1:0:-1]
## 'sgniteer'
a[::-1]
## 'sgniteerg'
b = "Hi"
b * 3
## 'HiHiHi'
name = "Lucas"
b + " " + "Lucas" + ", " + a
## 'Hi Lucas, greetings'
res = b + " " + "Lucas" + "\n" + a
print(res)
## Hi Lucas
## greetings

python comments

1+10 ## here is a comment
## 11
"""
XXX
XXXX
"""
a = """
XXX
XXXX
"""

a
## '\nXXX\nXXXX\n'
print(a)
## 
## XXX
## XXXX

python string formatting

name = 'Alex'
age = 27

print('%s is %d years old' % (name, age))
## Alex is 27 years old
print('{} is {} years old'.format(name, age))
## Alex is 27 years old
print(f'{name} is {age} years old') 
## Alex is 27 years old

We will focus on the f-string in this class

f'{}'

Python f-string expressions

bags = 4
apples_in_bag = 10

print(f'There are total of {bags * apples_in_bag} apples')
## There are total of 40 apples
print(f'There are {bags} bags, and {apples_in_bag} apples in each bag.\nSo there are a total of {bags * apples_in_bag} apples')
## There are 4 bags, and 10 apples in each bag.
## So there are a total of 40 apples

f-string formatting float (precision)

val = 12.3

print(f'{val:.2f}')
## 12.30
print(f'{val:.5f}')
## 12.30000

f-string formatting float (width)

val = 12.3

print(f'{val:2}')
## 12.3
print(f'{val:7}')
##    12.3
print(f'{val:07}')
## 00012.3
for x in range(1, 11):
    print(f'{x:02} {x*x:3} {x*x*x:4}')

f-string formatting float

f'{value:{width}.{precision}}'
f'{5.5:10.3f}'
## '     5.500'
from math import pi ## will introduce more about python module in the fuction lecture
pi
## 3.141592653589793
f'{pi:10.6f}'
## '  3.141593'
f'{pi*100000:,.2f}'

Input function

username = input("What is your name?")
print("Hello " + username)
print(f"Hello {username}")
num1 = input("First number:")
num2 = input("Second number:")
res = int(num1) + int(num2)
print(res)
print(f"{num1} plus {num2} is {res}")

Reference