wk0.1 A curious case of conditionals

Intro to git and github

Feedback form: https://docs.google.com/forms/d/1A0rjsJUUBlQTXOpHN0wGglDEG4Mte5DorovPTS_cbsI/viewform?usp=send_form

Read these:

A few challenges

Complete reverse_string and primes challenges in challenge folder.

Reviewing some ideas from yesterday

# Example from yesterday def t(num): if 10 <= num < 15: print("hot") elif num > 15: print("hotter") else: print("cold") # What does this function do? for i in range(4): for j in range(10): if j % 3 == 0: continue if j > 7 and j % 2 == 0: break else: print('i equals', i) print('j equals', j) print('------------')

In [3]:
#a = [1,2,3]
#b = a
#b is a
#b == a
#b = a[:]

In [4]:
#b == a
#b = a[:]

In [55]:
4 is 2**2


Out[55]:
True

Try evaluating each of the lines below in your python REPL. What's going on?

a = [1, 2, 3]
b = a
b is a
b == a
b = a[:]
b is a
b == a

If you have a hypothesis about the difference between is and ==, devise some tests you could try out to disprove your hypothesis. Implement them. Were you correct?

  • in and not in

In [63]:
# a in range(10)

assert a == 1
30 in range(10)


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-63-5814fa79f306> in <module>()
      1 # a in range(10)
      2 
----> 3 assert a == 1
      4 30 in range(10)

AssertionError: 
  • and, or

In [83]:
x = False
y = 0

x/y and x


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-83-4bd792ffccf8> in <module>()
      2 y = 0
      3 
----> 4 x/y and x

ZeroDivisionError: division by zero
  • comparison priority

    not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C.

  • Short circuit operators


In [9]:
#1000 == 10**3


Out[9]:
True

In [10]:
#1000 is 10**3


Out[10]:
False

In [12]:
#4 is 2**2
#python stores small values,  whereas with 10**3 it has to calculate


Out[12]:
True

In [20]:
#a = [1,2,3]
#c =[1,2,3]
#b =a
#a is c


Out[20]:
False

In [21]:
#a[:] is not b


Out[21]:
True

In [32]:
#for x in range(10):
#    print (x)


0
1
2
3
4
5
6
7
8
9

In [33]:
#10 <= x and x < 20


Out[33]:
False

In [36]:
#x = 1.5
#if x < 10 and x > 0:
#    print ("x is between ten and zero")


x is between ten and zero

In [37]:
#x = 'a'
#if x == 'a' or x =='b':
#    print('x is a or b')


x is a or b

In [41]:
#'a' or 'b'


Out[41]:
'a'

In [42]:
2 or 3


Out[42]:
2

In [43]:
'''x = True
y = True

not (x and y)'''


Out[43]:
False

In [46]:
'''x = False
y = 0
x and x/y
#and requires both to be true so the error of the division by zero is superceded by the falsity of the first condition''''


Out[46]:
False

More string and list practice

  • Add elements from a list L to the end of another list at least three different ways.

In [90]:
a = [1, 2, 3]
L = [4, 5, 6]

a[len(a):]


Out[90]:
[]
  • Insert elements into a list at least two different ways.

In [96]:
a[:4] + ['b'] + a[4:]


Out[96]:
['a', 6, 6, 1, 'b', 'a', 2, 3]
  • Insert an element into a string (this might take more than one step...).

In [105]:
str1 = "hello"
str1 = list(str1)
str1.insert(3, 'demo')
str1 = ''.join(str1)
str1

# str1 = "Hello world"
# str1 = str1[:3] + 'llllll' + str1[4:]
# str1


Out[105]:
'heldemolo'
  • Remove an item from a list by value.

In [110]:
lst  = [1 , 2, 3, 4]
lst.remove(3)
lst


Out[110]:
[1, 2, 4]
  • Remove an item from a list by index.

In [114]:
lst.pop(0)
lst


Out[114]:
[4]
  • Remove all items from a list two different ways.

In [121]:
lst = [1, 2, 3, 4]

lst.clear()
lst


Out[121]:
[]
  • Return the index in the list of the first item whose value is x.

In [123]:
lst = [1, 2, 2, 3, 4]
lst.index(2)


Out[123]:
1
  • Return the number of times x appears in the list.

In [126]:
lst.count(1)


Out[126]:
1
  • Capitalize the first element in a string

In [143]:
lst = [1, 2, 3]
lst.append(5)

lst


Out[143]:
[1, 2, 3, 5]

In [146]:
str1 ='abc'
b = list(str1).append(5)
b


Out[146]:
['a', 'b', 'c', 5]
  • Capitalize all elements in a string

In [166]:
def %(duh):
    """ Append 5 to the end of the list"""
    return duh + '5'


  File "<ipython-input-166-ebe37b1dcb76>", line 1
    def %(duh):
        ^
SyntaxError: invalid syntax

In [ ]:
def area(xadsf787adf, asdfjljk4):
    return xadsf787adf*asdfjljk4

In [164]:
foo = 7
bar = 10
area(foo, bar)


Out[164]:
70

In [152]:
str1 = 'asdf'
#string_changer(str1)


Out[152]:
'asdf5'
  • Strip leading, trailing, and all whitespace (ex. leading: ' asdf ' --> 'asdf ', trailing:' asdf ' --> ' asdf', all:' asdf ' --> 'asdf').

In [188]:
def namer(n, a):
    print('My name is {name} and my age is {age}'.format(age=a, name=n))
    
namer('Richie', 8)


My name is Richie and my age is 8

In [ ]:
str1.split()
  • Split a sentence into a list of words (no whitespace), how would you split on comma or semi-colon?

  • Read up on how to format strings


In [119]:
#0.
a = ['x',2,3]
b = [4,5,6]
f = a.pop()
b.append(f)
g = a.pop()
b.append(g)
h = a.pop()
b.append(h)
b


w = [1,2,3]
w.insert(3,4)
w


Out[119]:
[1, 2, 3, 4]

In [125]:
'Hello my name is Nick'.split()


Out[125]:
['Hello', 'my', 'name', 'is', 'Nick']

In [ ]:


In [97]:
a.index('x')


Out[97]:
0

In [99]:
a.count('x')


Out[99]:
1

In [103]:
'hello'.capitalize()


Out[103]:
'Hello'

In [106]:
'hello'.upper()


Out[106]:
'HELLO'

In [130]:
a = [1,2,3]
L = [4,5,6]
a.extend(L)
a


Out[130]:
[1, 2, 3, 4, 5, 6]

In [133]:
a=[1,2,3]
L = [4,5,6]
a + L


Out[133]:
[1, 2, 3, 4, 5, 6]

In [138]:
a = [1,2,3]
L = [4,5,6]
for x in a:
    L.append(x)
print (L)


[4, 5, 6, 1, 2, 3]

In [141]:
a = [1,2,3]
a.append(4)
a


Out[141]:
[1, 2, 3, 4]

In [143]:
a.insert(4,5)
a


Out[143]:
[1, 2, 3, 4, 5, 5]

In [149]:
#insert element into a string
str1 = 'hello'
str1 = list(str1)
str1.insert(3,'b')
str1 = ''.join(str1)
str1

str1 = 'hello world'
str1 = str1[:3] + 'llll' + str1[4:]
str1


Out[149]:
'helllllo world'

In [150]:
#remove an item by value
lst = [1,2,3]
lst.remove(3)
lst


Out[150]:
[1, 2]

In [151]:
#remove an item by index
lst.pop(0)
lst


Out[151]:
[2]

In [153]:
# remove all items from a list two different ways
lst = [1,2,3,4]
del lst[:]
lst

lst = [1,2,3,4]
lst.clear()
lst


Out[153]:
[]

In [ ]:
#Return the index in the list of the first item whose value is x

In [155]:
str1 = 'abc'
b = list(str1).append(5)
b
#immutable always outputs something, mutable does not

In [156]:
def string_changer(duh):
    return duh + '5'

In [157]:
str1 = 'asdf'
string_changer(str1)


Out[157]:
'asdf5'

In [158]:
def area(w,h):
    return w*h

In [159]:
area(3,4)


Out[159]:
12

In [161]:
#strip leading, trailing and all whitespace

#lstrip,rstrip,strip

str1 = '          absad          '
str1.strip()


Out[161]:
'asd   sad'

In [168]:
str1 = '   asd  fw'
b = str1.split()
''.join(b)


Out[168]:
'asdfw'

In [171]:
def namer(name):
    print ('My name is {}'.format(name))

namer('Joe')


My name is Joe

In [172]:
def namer(n):
    print ('My name is {name}'.format(name=n))

namer('Joe')


My name is Joe

In [ ]:
#Split a sentence 

str1.split(sep=None)

In [176]:

Intro to pins assignment

  • Intro to try/except and error handling
    • Syntax errors vs. exceptions

In [7]:
10 * (1/0)


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-7-9ce172bd90a7> in <module>()
----> 1 10 * (1/0)

ZeroDivisionError: division by zero

In [6]:
4 + spam*3


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-6b1dfe582d2e> in <module>()
----> 1 4 + spam*3

NameError: name 'spam' is not defined

In [ ]:
'2' + 2

Handing exceptions


In [ ]:
while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")

In [5]:
b == a
b = a[:]

In [ ]:


In [ ]: