This tutorial is an introduction to Python 3. This should give you the set of pythonic
skills that you will need to proceed with this tutorial series.
If you don't have the Jupyter installed, shame on you. No just kidding you can follow this tutorial using an online jupyter service:
In [1]:
1+2
Out[1]:
In [2]:
1+1
1+2
Out[2]:
In [3]:
print(1+2)
There are many variable types in Python 3. Here is a list of the most common types:
Notice: In Python 3 integer represents integer and long. Because there is no more long data type, you will not get L
at the end of long integers.
In [4]:
a = 4
b = 1.5
c = 121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212
d = 1j
e = 1/3
f = True
In [5]:
a+b
Out[5]:
In [6]:
a*c
Out[6]:
In [7]:
(b+d)*a
Out[7]:
In [8]:
a+f
Out[8]:
In [9]:
type(1.5)
Out[9]:
In [10]:
my_name = "Roshan"
print(my_name)
In [11]:
my_list = [1,2,3,4,5]
my_list
Out[11]:
In [12]:
my_list + [6]
Out[12]:
In [13]:
my_list
Out[13]:
In [14]:
my_list += [6,7,8]
my_list
Out[14]:
In [15]:
my_list.append(9)
my_list
Out[15]:
In [16]:
my_tuple = (1,2,3)
my_tuple
Out[16]:
In [17]:
my_tuple + (4,5,6)
Out[17]:
In [18]:
my_dict = {"name":"Roshan", "credit":100}
my_dict
Out[18]:
In [19]:
my_dict["name"]
Out[19]:
In [20]:
my_dict["level"] = 4
my_dict
Out[20]:
In [21]:
my_dict.values()
Out[21]:
In [22]:
my_dict.keys()
Out[22]:
In [23]:
len(my_list)
Out[23]:
To access a single value in a list use this syntax:
list_name[index]
In [24]:
my_list[0]
Out[24]:
To select multiple value from a list use this syntax:
index[start:end:step]
In [25]:
my_list[1:2]
Out[25]:
In [26]:
my_list[:3]
Out[26]:
In [27]:
my_list[3:]
Out[27]:
Notice: negative index selected from the end of the list
In [28]:
my_list[-1]
Out[28]:
In [29]:
my_list[-2]
Out[29]:
You can use negative indexing in selecting multiple values.
In [30]:
my_list[-2:]
Out[30]:
In [31]:
my_list[:-2]
Out[31]:
In [32]:
my_list[3:-1]
Out[32]:
The third location in the index is the step
. If the step
is negative the the list is returned in descending order.
In [33]:
my_list[::2]
Out[33]:
In [34]:
my_list[3::2]
Out[34]:
In [35]:
my_list[::-1]
Out[35]:
In [36]:
my_name
Out[36]:
In [37]:
my_name[0]
Out[37]:
Notice: You can also use negative indexing.
In [38]:
my_name[:2]
Out[38]:
In [39]:
# Sorted by most spoken languages in order
divide_by_zero = {"zho":"你不能除以零",
"eng":"You cannot divide by zero",
"esp":"No se puede dividir por cero",
"hin":"आप शून्य से विभाजित नहीं किया जा सकता \u2248",
"arb":"لا يمكن القسمة على صفر"}
print(divide_by_zero["hin"])
type(divide_by_zero["hin"])
Out[39]:
In [40]:
first_name = "Roshan"
last_name = "Rush"
formatted_name = "%s, %s." % (last_name, first_name[0])
print(formatted_name)
Other formatters could be used to format numbers:
In [41]:
print("π ≈ %.2f" % 3.14159)
To find unicode symbols:
In [42]:
homeworks = 15.75
midterm = 22
final = 51
total = homeworks + midterm + final
print("Homeworks: %.2f\nMid-term: %.2f\nFinal: %.2f\nTotal: %.2f/100" % (homeworks, midterm, final, total))
In [43]:
url = "http://{language}.wikipedia.org/"
url = url.format(language="en")
url
Out[43]:
In [44]:
1+1
Out[44]:
In [45]:
4-5
Out[45]:
Notice: The default behavior of division in Python 3 is float division. To use integer division like Python 2, use //
In [46]:
14/5
Out[46]:
In [47]:
14//5
Out[47]:
In [48]:
2*5
Out[48]:
To raise a number to any power use down asterisk **
. To represent $a^{n}$:
a**n
In [49]:
2**3
Out[49]:
To calculate the remainder (modulo operator) use %
. To represent $a \mod b = r$:
a % b # Returns r
In [50]:
10 % 3
Out[50]:
You can
You can use the math
library to access a varaity of tools for algebra and geometry. To import a library, you can use one of these syntaxes:
import library_name
import library_name as alias
from module_name import some_class
In [51]:
import math
In [52]:
n=52
k=1
math.factorial(n) / (math.factorial(k) * math.factorial(n-k))
Out[52]:
In [53]:
for counter in [1,2,3,4]:
print(counter)
In Python 3 range
is a data type that generates a list of numbers.
range(stop)
range(start,stop[ ,step])
Notice: In Python 2 range
is a function that returns a list. In Python 3, range
returns an iterable of type range
. If you need to get a list you can use the list()
function:
list(range(start,stop[, step]))
In [54]:
for counter in range(5):
print(counter)
Notice: The list doesn't reach the stop
value and stops one step
before. The reason behind that is to make this syntax possible:
In [55]:
list(range(1,10)) == list(range(1,5)) + list(range(5,10))
Out[55]:
Notice: In Python 3 use use ==
to check if two values are equal. To check if two values are not equal use !=
and don't use <>
from Python 2 because it is not supported any more in Python 3.
In [56]:
for counter in range(1,5):
print(counter)
In [57]:
for counter in range(2,10,2):
print(counter)
In [58]:
counter =1
while counter < 5:
print(counter)
counter += 1
In [59]:
if math.pi == 3.2:
print("Edward J. Goodwin was right!")
else:
print("π is irrational")
In [60]:
if math.sqrt(2) == (10/7):
print("Edward J. Goodwin was right!")
elif math.sqrt(2) != (10/7):
print("Square root of 2 is irrational")
Fun story about pi where it was almost set by law to be equal to 3.2!
If you don't what is the "pi bill" you can read about it here: http://en.wikipedia.org/wiki/Indiana_Pi_Bill
Or watch Numberphile video about it: https://www.youtube.com/watch?v=bFNjA9LOPsg
In [61]:
probability = 0.3
if probability >= 0.75:
print("Sure thing")
elif probability >= 0.5:
print("Maybe")
elif probability >= 0.25:
print("Unusual")
else:
print("No way")
In [62]:
def get_circumference(r):
return math.pi * r * 2
In [63]:
get_circumference(5)
Out[63]:
In [64]:
def binomilal_coef(n,k):
"""
This function returns the binominal coef
Parameters:
===========
n, k int
return n!/(k!*(n-k)!)
"""
value = math.factorial(n)/(math.factorial(k)*math.factorial(n-k))
return value
binomilal_coef(52,2)
Out[64]:
Notice: Use can use SHIFT+TAB to show the docstring of a function.
This was the binomial function which tells you how many ways are there to select k number of samples from a sample space with n items if order didn't matter and chosen samples could not be repeated (chosen again).
As an example, How many ways to select 2 card from a deck of 52 cards if order of selection didn't matter and you where not allowed to choose the same card twice?
$${n \choose k} = {n! \over {k!(n-k)!}}$$$${52 \choose 2} = {52! \over {2!(52-2)!}} = {52! \over {2!(50)!}} = 1326$$How many ways to select 2 cards from a deck of 52 cards if order didn't matter and you could choose the same card twice?
hints:
Read about k-combination with repetitions: http://en.wikipedia.org/wiki/Combination#Number_of_combinations_with_repetition
The equation $$\left(\!\!\!\binom{n}{k}\!\!\!\right) = {{n+k-1} \choose k}$$
To make your life easier: