Exercise 1: Syntax errors - SOLVED#

In this, and subsequent, noteboooks in this class we’ll walk through a number of different problems. Each of these fail in some way. For many of the early problems, the issue can be solved by inspecting the code. However, for later ones you may need to use PDB to really understand what the code is doing and diagnose the problems. Some of the later problem sets are quite challenging, so just get through as much of this as you can. There are no “summary exercises” this week, just work through as much as you can. Try to get at least as far as exercise 5. Good luck!

Syntax errors#

Syntax errors are the first type of bug you encounter in new code. Luckily these prevent the code from running so you know there’s a problem, you just need to fix it.

Here are some examples of code containing syntax errors. Identify and fix the issues in each of the cells below. In some cases there are errors beyond just the syntax error to resolve!

Exercise 1.1#

counter=0
while counter < 5:
    print ("hello")
    counter = counter + 1
hello
hello
hello
hello
hello

Exercise 1.2#

counter = 4
if counter == 4:
    print ("counter is 4")
counter is 4

Exercise 1.3#

x = 3
y = ((x + 3) * (x + 4))
print (y)
42

Exercise 1.4#

name = input()
print(name)
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Input In [4], in <module>
----> 1 name = input()
      2 print(name)

File /opt/homebrew/Caskroom/miniconda/base/envs/pycbc_test/lib/python3.9/site-packages/ipykernel/kernelbase.py:1190, in Kernel.raw_input(self, prompt)
   1188 if not self._allow_stdin:
   1189     msg = "raw_input was called, but this frontend does not support input requests."
-> 1190     raise StdinNotImplementedError(msg)
   1191 return self._input_request(
   1192     str(prompt),
   1193     self._parent_ident["shell"],
   1194     self.get_parent("shell"),
   1195     password=False,
   1196 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Exercise 1.5#

greeting = "hello" + " world"
print(greeting)
hello world

Exercise 1.6#

def example1_A():
    x = 0
    y = 1
    return x+y

print(example1_A())
1

Exercise 1.7#

import numpy

def example1_B(list_of_vals):
    b = (list_of_vals.sum() + list_of_vals.mean() + numpy.cos(list_of_vals)*(sorted(list_of_vals)))
    return b

a = numpy.random.random(100)
example1_B(a)
array([51.75184617, 51.77588683, 51.78502419, 51.79167299, 51.8254601 ,
       51.84451895, 51.85017647, 51.84081165, 51.84994992, 51.84165148,
       51.88319777, 51.9022958 , 51.84697058, 51.9262402 , 51.92014571,
       51.94367803, 51.88321992, 51.91402844, 51.95590926, 51.96992276,
       51.99461948, 51.94249822, 51.94644996, 51.95663083, 51.99735633,
       52.02454957, 51.96111057, 52.03409513, 52.04555445, 52.05773477,
       52.07375022, 52.00469972, 51.99068419, 52.12441633, 52.10908222,
       52.11113287, 52.13272113, 52.14447188, 52.01383975, 52.15965859,
       52.12386095, 52.15627634, 52.15868902, 52.11755406, 52.09140319,
       52.18449171, 52.1911018 , 52.00457308, 52.08604313, 52.06739403,
       52.11381809, 52.10801914, 52.08435608, 52.10154558, 52.28179104,
       52.17398821, 52.23657308, 52.29597039, 52.24220465, 52.24992919,
       52.23233196, 52.35408047, 52.1545541 , 52.14536218, 52.16908954,
       52.13413546, 52.41375945, 52.2755412 , 52.45152516, 52.42389144,
       52.45476777, 52.31058904, 52.46363036, 52.40888992, 52.25350535,
       52.50115791, 52.45018221, 52.24979596, 52.48451361, 52.30681473,
       52.21364197, 52.38462656, 52.43778105, 52.34866131, 52.56806727,
       52.46887643, 52.51469283, 52.23340675, 52.40702776, 52.60509324,
       52.51704854, 52.28415567, 52.60544582, 52.64413976, 52.5907176 ,
       52.66883737, 52.59436773, 52.64963315, 52.41949642, 52.52061122])

Exercise 1.8#

first = 1
second = 2
third = 3
extra = int(input("What is the extra value? "))

total = first+second+third+extra
print(total)
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Input In [8], in <module>
      2 second = 2
      3 third = 3
----> 4 extra = int(input("What is the extra value? "))
      6 total = first+second+third+extra
      7 print(total)

File /opt/homebrew/Caskroom/miniconda/base/envs/pycbc_test/lib/python3.9/site-packages/ipykernel/kernelbase.py:1190, in Kernel.raw_input(self, prompt)
   1188 if not self._allow_stdin:
   1189     msg = "raw_input was called, but this frontend does not support input requests."
-> 1190     raise StdinNotImplementedError(msg)
   1191 return self._input_request(
   1192     str(prompt),
   1193     self._parent_ident["shell"],
   1194     self.get_parent("shell"),
   1195     password=False,
   1196 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Exercise 1.9#

For this one here, after fixing, ensure it works with both an odd and an even number as input!

x = int(input('Enter a number: '))

if x%2 == 0:
    print('You have entered an even number.')
else:
    print ('You have entered an odd number.')
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Input In [9], in <module>
----> 1 x = int(input('Enter a number: '))
      3 if x%2 == 0:
      4     print('You have entered an even number.')

File /opt/homebrew/Caskroom/miniconda/base/envs/pycbc_test/lib/python3.9/site-packages/ipykernel/kernelbase.py:1190, in Kernel.raw_input(self, prompt)
   1188 if not self._allow_stdin:
   1189     msg = "raw_input was called, but this frontend does not support input requests."
-> 1190     raise StdinNotImplementedError(msg)
   1191 return self._input_request(
   1192     str(prompt),
   1193     self._parent_ident["shell"],
   1194     self.get_parent("shell"),
   1195     password=False,
   1196 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Exercise 1.10#

The following example case is long. It’s an example of coding up a noughts and crosses game. There’s nothing in here that you haven’t seen before, so can you use the error messages, and your knowledge, to fix the broken code? (If you get stuck, don’t spend too much time on this, it’s important to also see later exercises!)

HINT: After resolving the syntax errors, are the input, and output, arguments in the right order??

import numpy

def create_empty_board():
    return numpy.zeros([3,3])
                        

def print_board(board):
    for i in range(3):
        curr_line = ''
        for j in range(3):
            if board[i,j] == -1:
                curr_line += "O"
            elif board[i,j] == 1:
                curr_line += "X"
            elif board[i,j] == 0:
                curr_line += "*"
        print(curr_line)
    print()
    
def place_nought(current_player, board, i, j):
    if current_player == 'crosses':
        print("It's not nought's turn!")
        return current_player, board
    if not board[i,j] == 0:
        print("That square already has a piece on it")
        return current_player, board
    board[i,j] = -1
    current_player = 'crosses'
    check_board_status(board)
    return current_player, board
    
def place_cross(current_player, board, i, j):
    if current_player == 'noughts':
        print("It's not nought's turn!")
        return current_player, board
    if not board[i,j] == 0:
        print("That square already has a piece on it")
        return current_player, board
    board[i,j] = 1
    current_player = 'noughts'
    check_board_status(board)
    return current_player, board
    
def check_board_status(board):
    # Check horizontal and vertical rows
    diag_sum = board[0,0] + board[1,1] + board[2,2]
    diag_sum2 = board[0,2] + board[1,1] + board[2,0]
    for i in range(3):
        if board[i,:].sum() == 3 or board[:,i].sum() == 3 or diag_sum == 3 or diag_sum == 3:
            print("CROSSES WIN")
            print_board(board)
        if board[i,:].sum() == -3 or board[:,i].sum() == -3 or diag_sum == -3 or diag_sum == -3:
            print("NOUGHTS WIN")
            print_board(board)
        
    # Check if any values are 0
    if not (board == 0).any():
        print("GAME IS A DRAW")
        print_board(board)

board = create_empty_board()
current_player = 'noughts'
print_board(board)
current_player, board = place_nought(current_player, board, 0,1)
# This one below should fail, it's not nought's turn!
current_player, board = place_nought(current_player, board, 1,1)
print_board(board)
current_player, board = place_cross(current_player, board, 1,1)
current_player, board = place_nought(current_player, board, 0,0)
current_player, board = place_cross(current_player, board, 2,2)
current_player, board = place_nought(current_player, board, 0,2)
# Nought wins

board = create_empty_board()
current_player = 'noughts'
print_board(board)
current_player, board = place_nought(current_player, board, 1,1)
current_player, board = place_cross(current_player, board, 0,0)
current_player, board = place_nought(current_player, board, 0,2)
current_player, board = place_cross(current_player, board, 2,0)
current_player, board = place_nought(current_player, board, 1,0)
current_player, board = place_cross(current_player, board, 1,2)
current_player, board = place_nought(current_player, board, 0,1)
current_player, board = place_cross(current_player, board, 2,1)
current_player, board = place_nought(current_player, board, 2,2)
# DRAW
***
***
***

It's not nought's turn!
*O*
***
***

NOUGHTS WIN
OOO
*X*
**X

***
***
***

GAME IS A DRAW
XOO
OOX
XXO