Week 1: Get Started with Python
Introduction & Refreshment
Contents
Part 1: A Number Guessing Game
Part 2: Data Types
Part 3: Basic Operations
Part 4: Conditions, Loops, Functions, Randomness
Part 5: Pandas DataFrame
Let's start with a sensational YouTubeVideo
In [1]: # import command "YouTubeVideo" from library "[Link]"
from [Link] import YouTubeVideo
# from [Link] import Audio,Image,YouTubeVideo
YouTubeVideo(id='2DLnhdnSUVs',width=500,height=250)
Out[1]:
Part 1: A Number Guessing Game
Game Rule
Guess a numner between 1 to 6, up to 3 times
In [2]: # import a python library (or module) called random (random number generator)
import random
# use randint function to generate a random number between 1 to 6
num = [Link](1,6)
# there are up to 3 chances to guess
chances = 0
print("Guess a number (between 1 and 6):")
# While loop to count the number of chances
while chances < 3:
# Enter a number
guess = int(input())
# Compare the guess number
if guess == num:
# if guess=num using "break" to stop the loop
print("Congratulation: You are right!!!")
break
# Check if the guess number is smaller than num
elif guess < num:
print("Too low!", guess)
# Or, the number is greater than age
else:
print("Too high!", guess)
# Increase the value of chance by 1, "chances += 1" equals "chances = chances +
1"
chances += 1
# Check whether the user guessed the correct number
if chances == 3:
print("YOU LOSE!!! The number is", num)
Guess a number (between 1 and 6):
6
Too high! 6
3
Too high! 3
2
Too high! 2
YOU LOSE!!! The number is 1
Note :
This gaming example involves: import a library (random), a loop (while), a set of conditions (if, elseif, else),
and an iteractive function (input)
Most of our coding practices will be more straightforward than this example!
Part 2: Data Types
Text Type : str
Numeric Types : int, float
Boolean Type : bool
Sequence Types : list, tuple, set, range
Mapping Type : dict
String
In [3]: x="Hello, Python!"
print(x)
type(x)
Hello, Python!
Out[3]: str
Note : Use quotation marks, either '...' (single) or "..." (double), for strings. Removing the quotations will
get an error message.
Integer & float
In [4]: x=100
type(x)
Out[4]: int
In [5]: x=100.001
type(x)
Out[5]: float
In [6]: x=1.2345678e7
print(x)
type(x)
12345678.0
Out[6]: float
Boolean
In [7]: x=True
print(x)
type(x)
True
Out[7]: bool
In [8]: # compare numbers >,<,==
x=100<100.1
print(x)
type(x)
True
Out[8]: bool
In [9]: # comapre strings (ordering)
"A">"B"
Out[9]: False
In [10]: x='Tom'
y='tom'
x is not y
Out[10]: True
Note : Python is case-sensitive!
List, Tuple, Set & Dic (dictionary)
Note:
Lists [...] (bracket) are mutable (changable), while tuples (...) (parethesis) are not (inmutable); sets {...}
(brace) are collections which contain all unique elements!
{...} can be used for dictionaries as well!
In [11]: x=[1,2,3,4,5]
print(x)
type(x)
[1, 2, 3, 4, 5]
Out[11]: list
In [12]: # replace the first place [0] of x by 10
x[0]=10
x
Out[12]: [10, 2, 3, 4, 5]
In [13]: x=['3030AFE','Predictive Analytics', 2022]
print(x)
type(x)
['3030AFE', 'Predictive Analytics', 2022]
Out[13]: list
In [14]: xx=(1,2,3,4,5)
print(xx)
type(xx)
(1, 2, 3, 4, 5)
Out[14]: tuple
In [15]: # will get an error message... why?
xx[0]=10
xx
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-7bb3de9a832b> in <module>
1 # will get an error message... why?
----> 2 xx[0]=10
3 xx
TypeError: 'tuple' object does not support item assignment
In [16]: xx=('3030AFE','Predictive Analytics', 2022)
print(xx)
type(xx)
('3030AFE', 'Predictive Analytics', 2022)
Out[16]: tuple
In [17]: s1={1,2,3}
print(s1)
type(s1)
{1, 2, 3}
Out[17]: set
In [18]: s2={1,2,2,2,3}
print(s2)
type(s2)
{1, 2, 3}
Out[18]: set
In [19]: s1==s2
Out[19]: True
In [20]: x1=[1,2,3]
xx1=(1,2,3)
s1={1,2,3}
x2=[1,1,2,2,3]
In [21]: x1==xx1
Out[21]: False
In [22]: x1==s1
Out[22]: False
In [23]: x1==x2
Out[23]: False
Dictionary
Note : dictionary = {key1: values=1, key2: value2, ... }
In [24]: x = {"Name": "Business Data Analytics", "Year" : 2020, "Enrolment": 70}
print(x)
type(x)
{'Name': 'Business Data Analytics', 'Year': 2020, 'Enrolment': 70}
Out[24]: dict
Range
Note : range(start, stop, step) (ends at "stop-1")
In [25]: r=range(10)
print(r)
print(list(r))
type(r)
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Out[25]: range
In [26]: r=range(1,20,1)
print(list(r))
type(r)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Out[26]: range
range(1,20,1): 1,2,...,"19" (start from 1, stop "before" 20, each step increase by 1)
In [27]: r=range(5,50,10)
print(list(r))
type(r)
[5, 15, 25, 35, 45]
Out[27]: range
In [28]: r=range(5,-50,-10)
print(list(r))
type(r)
[5, -5, -15, -25, -35, -45]
Out[28]: range
Slicing
pick characters out by calling the position index i
**s[i:j]** -- characters from ***i*** to ***j-1***
Position -- start with 0!
In [29]: # slicing: s[i:j], characters from i to j-1
x="Hello, Python!"
x[0:4]
Out[29]: 'Hell'
In [30]: # Let's try the following -- "-1" is the last position
print(x[:])
print(x[-1])
print(x[13])
print(x[5:8])
Hello, Python!
!
!
, P
Part 3: Basic Operations
Arithmetic operations
x + y: sum of x and y
x - y: difference of x and y
x * y: product of x and y
x / y: quotient of x and y
x // y: floored quotient of x and y
x % y: remainder of x / y
-x: x negated
+x: x unchanged
abs(x): absolute value or magnitude of x
int(x): x converted to integer
float(x): x converted to floating point
x ** y: x to the power y
In [31]: 2+5
Out[31]: 7
In [32]: 2-5
Out[32]: -3
In [33]: 2*5
Out[33]: 10
In [34]: 1/5
Out[34]: 0.2
In [35]: 11//5
Out[35]: 2
In [36]: 11%5
Out[36]: 1
In [37]: -2
Out[37]: -2
In [38]: --2
Out[38]: 2
In [39]: abs(-2)
Out[39]: 2
In [40]: int(3.9)
Out[40]: 3
In [41]: float(3)
Out[41]: 3.0
In [42]: 2**3
Out[42]: 8
In [43]: 2**(1/2)
Out[43]: 1.4142135623730951
Logic operations
x | y: or
x & y: and
In [44]: A=False
B=True
A|B
Out[44]: True
In [45]: A&B
Out[45]: False
In [46]: (2>1)|(1>2)|(1==2)
Out[46]: True
In [47]: (2>1)|(1>2)&(1==2)
Out[47]: True
In [48]: (2>1)&(1>2)|(1==2)
Out[48]: False
In [49]: 'Love'=='love'
Out[49]: False
Part 4: Conditions, Loops, Functions & Randomness
Conditions
In [50]: # if (don't forget colon :)
x=10
if x<5:
x=x+1
x
Out[50]: 10
In [51]: # if ... else
x=8
if x<5:
x=x+2
else:
x=x-2
x
Out[51]: 6
Loops
while
for -- for is more flexible than while (to be applied more often)
In [52]: # while "condition" -- keep going when the condition is met
i=1
while i <= 10:
print(i, end=".")
i += 1
# i += 1 (i=i+1)
[Link].[Link].9.10.
In [53]: # for...in -- keep going if "in"
ll=range(1,10,2)
print(list(ll))
for i in ll:
print(i)
[1, 3, 5, 7, 9]
1
3
5
7
9
In [54]: ll=["Mon","Tue","Wed","Thu","Fri"]
for i in ll:
print(i, end='...')
Mon...Tue...Wed...Thu...Fri...
In [55]: for i in "banana":
print(i+i+i)
bbb
aaa
nnn
aaa
nnn
aaa
In [56]: for i in "banana":
print(i+i+i, end='')
bbbaaannnaaannnaaa
Functions
Use def & lambda to define a function
Use def
In [57]: # Define a function F1 with "def" with one input & one output (using print)
# Beware of ":" and indention
def F1(name):
print("Hello,", name, end='!!!')
In [58]: # execute def
F1("Sam")
Hello, Sam!!!
In [59]: # F2
def F2(nlist):
s=sum(nlist)
n=len(nlist)
mean=s/n
print('sum=', s, '\nsize=', n, '\nave=', mean)
return(s,n,mean,[s,n,mean])
In [60]: # execute F2
nlist = [1,2,3,4,5,6,7,8,9]
x=F2(nlist)
x
sum= 45
size= 9
ave= 5.0
Out[60]: (45, 9, 5.0, [45, 9, 5.0])
In [61]: type(x)
Out[61]: tuple
In [62]: # generate nlist with range
nlist=range(1,10,2)
print(list(nlist))
F2(nlist)
[1, 3, 5, 7, 9]
sum= 25
size= 5
ave= 5.0
Out[62]: (25, 5, 5.0, [25, 5, 5.0])
Alternatively, use the "average" function from "numpy" (import numpy is required)
In [63]: import numpy as np
[Link](nlist)
Out[63]: 5.0
Use "lambda"
In [64]: # Use lambda to define a simple function
# x, y, z are inputs and the function is fun1 = x*(y^z)
L_1=lambda x, y, z: x*y**z
In [65]: L_1(2,5,2)
Out[65]: 50
In [66]: # Use lambda to define a simple function, watch out the operation oreder
# x, y, z are inputs and the function is fun2 = (x*y)^z
L_2=lambda x, y, z: (x*y)**z
In [67]: L_2(2,5,2)
Out[67]: 100
Part 5: Pandas & Dataframe
pandas is one of the most useful library of Python for data analysis
need to call in ( import ) pandas when starting a data analysis project, just once!
In [68]: # import pandas library, following the convention, let's name it as pd (for simplicit
y)
import pandas as pd
In [69]: # data in the form of list of tuples
data1 = [('Peter', 18, 7),
('Mike', 19, 6),
('Emily', 17, 6),
('Michel', 18, 7),
('Susan', 20, 5) ]
data1
Out[69]: [('Peter', 18, 7),
('Mike', 19, 6),
('Emily', 17, 6),
('Michel', 18, 7),
('Susan', 20, 5)]
In [70]: # conver list to dataframe
df1 = [Link](data1)
df1
Out[70]:
0 1 2
0 Peter 18 7
1 Mike 19 6
2 Emily 17 6
3 Michel 18 7
4 Susan 20 5
Note : DataFrame is 2-dimentional (5 rows by 3 columns, the above case), very much like Excel.
In [71]: # add column names
col1 = ['Name', 'Age', 'Grade']
[Link] = col1
df1
Out[71]:
Name Age Grade
0 Peter 18 7
1 Mike 19 6
2 Emily 17 6
3 Michel 18 7
4 Susan 20 5
In [72]: # data in the form of dict
data2 = {'Peter': [18, 7],
'Mike': [19, 6],
'Emily': [17, 6],
'Michel': [18,7],
'Susan': [20,5]}
data2
Out[72]: {'Peter': [18, 7],
'Mike': [19, 6],
'Emily': [17, 6],
'Michel': [18, 7],
'Susan': [20, 5]}
In [73]: # convert dict to dataframe
df2=[Link](data2)
df2
Out[73]:
Peter Mike Emily Michel Susan
0 18 19 17 18 20
1 7 6 6 7 5
In [74]: # transpose dataframe
df2=[Link](data2).T
df2
Out[74]:
0 1
Peter 18 7
Mike 19 6
Emily 17 6
Michel 18 7
Susan 20 5
In [75]: col =['Age', 'Grade']
[Link]=col
df2
Out[75]:
Age Grade
Peter 18 7
Mike 19 6
Emily 17 6
Michel 18 7
Susan 20 5
End of Week 1
Appendix
Use Esc H to show shortcut list
Try: Ctrl + Z , Esc + Z , Shift + Tab (very useful!!!)
Ctrl + Z: recover deleted stuff in a cell
Esc + Z: recover deleted cell
Shift + Tab: show documentation of a command
In [ ]: