Data and Types

Boolean

In [4]:
True
Out[4]:
True
False
In [5]:
True and False
Out[5]:
False
In [6]:
False or False
Out[6]:
False
In [7]:
not True
Out[7]:
False

Variable

A variable holds a value that can change over time

Assignment statement

In [8]:
x = 20
y = 40
z = y + 20
print(x,y,z)
20 40 60

Numbers

In [9]:
x = 2.5
y = x * x
print(y)
6.25

mod (%) and div (//) operators

In [10]:
7 % 2
Out[10]:
1
In [11]:
7 // 2
Out[11]:
3
In [12]:
7/2
Out[12]:
3.5

Characters and Strings

In [21]:
x = "Raj"
y = 'Sunderraman'
z = '''Hello, How are you?'''
print(x)
print(y)
print(z)
print(x,y,z)
Raj
Sunderraman
Hello, How are you?
Raj Sunderraman Hello, How are you?
In [30]:
u     =     x +  " " +   y
print(u)
Raj Sunderraman
In [27]:
print(u[5])
n
In [31]:
u[0:3]
Out[31]:
'Raj'
In [32]:
u[4:]
Out[32]:
'Sunderraman'
In [33]:
ord('a')
Out[33]:
97
In [34]:
ord('b')
Out[34]:
98
In [35]:
ord('A')
Out[35]:
65
In [36]:
chr(97)
Out[36]:
'a'
In [41]:
len("Raj")
Out[41]:
3

Aggregate/Collection Data

List

In [42]:
xs = [10,20,30,40]
In [1]:
fs = []
In [3]:
ss = ['apple','orange','banana']
In [44]:
len(xs)
Out[44]:
4
In [45]:
xs[0]
Out[45]:
10
In [46]:
xs[0:2]
Out[46]:
[10, 20]
In [48]:
xs+ss
Out[48]:
[10, 20, 30, 40, 'apple', 'orange', 'banana']
In [49]:
['a','p','p','l','e']
Out[49]:
['a', 'p', 'p', 'l', 'e']
In [50]:
answer = xs[0] + xs[1] + xs[2]
print(sum)
60

Accumulator Pattern

In [54]:
answer = 0
for x in xs:
    answer = answer + x
print(answer)
100
In [56]:
answer = 1
for x in xs:
    answer = answer * x
print(answer)
0
In [4]:
answer = ""
for s in ss:
    answer = answer + s
print(answer)
appleorangebanana
In [58]:
answer = 0
for s in ss:
    answer = answer + len(s)
print(answer)
17

Tuple

In [59]:
ts = (100112222,"Raj",4.0)
ts[0]
Out[59]:
100112222

Dictionary

a collection of key-value pairs

In [60]:
ds = {100: ["apple","orange"], 101: ["apple"] }
es = {"john": [100,20,40], "jamie": [10,20] }
days_in_month = {1: 31, 2:28, 3:31, 12:31}
In [61]:
days_in_month[12]
Out[61]:
31

Functions

In [5]:
def square(x):
    z = x*x
    return z
In [6]:
square(4)
Out[6]:
16
In [7]:
square(5)
Out[7]:
25
In [67]:
ord('h') - ord('a')
Out[67]:
7
In [ ]:
def encode(n,pt):
    ???
    ???
    return answer