JamCoders

💾 Download

JamCoders Day 1 Lecture 2

Boaz Barak

Operations (integral types)

In [ ]:
# Python things can be combined using arithmetic operators
1 + 1
Out[ ]:
2
In [ ]:
# The result of arithmetic operations can be assigned to variables
x = 10. - 5.3
y=5
z=x+y
z
Out[ ]:
9.7
In [ ]:
# The result of an arithmetic operation WILL NOT CHANGE the variable contents
x*2
Out[ ]:
9.4
In [ ]:
# as you can see here
x
Out[ ]:
4.7
In [ ]:
# To change the value of a variable, we assign to it a new value
x = x * 2
x
Out[ ]:
18.8
In [ ]:
# An example of floating point division
4.3 / 2.0
Out[ ]:
2.15
In [ ]:
# An example of division of integers
16 / 6
Out[ ]:
2.6666666666666665
In [ ]:
# Integer division
16 // 6
Out[ ]:
2
In [ ]:
# An example of "modulus" or "mod" or "finding the remainder"
4 % 3
Out[ ]:
1
In [ ]:
# What is the answer?
8 % 3
Out[ ]:
2
In [ ]:
# How about now?
10 % 4
In [ ]:
# How about now?
10 % 2
Out[ ]:
0
In [ ]:
# And now?
143 % 5
In [ ]:
x = 1
x = x + 1
x
In [ ]:
x = 1
x += 1 # This is equivalent to "x = x + 1"
x
In [ ]:
x = 10
x -= 5
x
In [ ]:
x = 60
x *= 50
x
Out[ ]:
3000
In [ ]:
x = 100
x /= 10
x
type(x)
In [1]:
x = 100
x //= 10
x
Out[1]:
10

Difference between = and ==

x = 5: Assign the value 5 to the variable x

x==5: Is True if x equals to 5 already and is False otherwise

In [ ]:
x = 5
In [ ]:
x == 5
In [ ]:
x == 7
In [ ]:
x = 7
In [ ]:
x == 7
In [ ]:
7 == x
In [ ]:
7 = x
In [ ]:
# Order of operations matters!
# *, /, % happen first, in the order they appear
1 + 3 * 20 % 7

Operations (boolean types)

In [ ]:
# Booleans can be combined using logical ands
# The result of logical and is True if and only if both sides are True
True and False

#Is True==True and False==True?
In [ ]:
# Booleans can be combined using logical ors
# The result of logical or is True if either side is True
True or False

#is True==True or False==True?
In [ ]:
# You can put operations that result in booleans and combine them
(1 == 1) and (2 == 2)
In [ ]:
# Logical negation changes True to False
not True
In [ ]:
# and False to True
not False
In [ ]:
not (1 == 1)

Operations (string, list)

In [ ]:
# Adding strings is called "concatenation"
'Hello' ' '+ 'world!'
In [ ]:
# Aside: can you have a 1-element list?
len([27])
In [ ]:
# Aside: can you have a 0-element list?
len([])
In [ ]:
# Adding list is also called "concatenation"
[0] + [1]
In [ ]:
x = [0]
y = [1]
x + y

Errors

In [ ]:
# Errors occur when something you do that isn't allowed
# Remember: True is supposed to be capitalized!
true
In [ ]:
# Variables must be assigned before being used
print(boaz)
In [ ]:
# Once you assign a variable you can use it
boaz = 7
print(boaz)
In [ ]:
# Dividing by 0 is undefined and thus an error in Python
1 / 0

Issues to watch out for

Different types of parenthesis (,) .. [,] ... {,}

In [ ]:
L = [1,2,3] # list
L[1]
Out[ ]:
2
In [ ]:
(2+3)*4 , 2+3*4
Out[ ]:
(20, 14)
In [ ]:
print("hello")
hello
In [ ]: