0% found this document useful (0 votes)
35 views25 pages

COMP5070 Week 01 Practice

This document contains instructions and exercises for students taking the COMP 5070 Statistical Programming for Data Science course. It provides 5 exercises for students to practice basic Python programming concepts covered in Week 1, including Hello World programs, comparison operators, Boolean logic, and syntax checking. Students are encouraged to attempt the exercises and ask online questions if they get stuck.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views25 pages

COMP5070 Week 01 Practice

This document contains instructions and exercises for students taking the COMP 5070 Statistical Programming for Data Science course. It provides 5 exercises for students to practice basic Python programming concepts covered in Week 1, including Hello World programs, comparison operators, Boolean logic, and syntax checking. Students are encouraged to attempt the exercises and ask online questions if they get stuck.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

COMP 5070



Statistical Programming

for

Data Science

Week  1  
Practice  &  Online  Questions
Week  1  Exercises:  General  Information

The  exercises  that  follow  are  designed  to  complement  the  Week  1  
material.

Got  a  question?

Give  whatever  you  can  a  go  &  if  you  get  stuck,  
pop  online  and  post  a  question  and  we  can  sort  it  out  ☺

2
Exercise  1:  Hello  World
Recall  the  Hello  World  program  from  the  lecture  notes.    For  this  
exercise,  do  the  following:  

1. Enter  and  run  the  hello  world  program  at  the  python  command  line  (i.e.  
at  the  >>>  prompt).    You  can  run  this  program  one  line  at  a  time.  

2. Create  a  script  (e.g.  Hello  World.py)  in  your  Python  editor  that  contains  
this  code,  and  make  sure  you  can  successfully  run  the  script.  

3. Edit  the  Hello  World  script  file  to  prompt  the  user  for  their  name  (and  any  
other  information  you  might  be  interested  in)  and  then  output  to  the  
screen  a  greeting  that  includes  their  name  and  this  other  information.  

3
Exercise  2:  Comparison  Operators
What  is  the  output  of  res  in  each  case?    Assume  x,y  and  z  take  the  
values  as  shown  below:

>>> x = 5
>>> y = 1
>>> z = 5

>>> res = x < y   >>> res = y < x and z < y


>>> res   >>> res

>>> res = x == z   >>> res = y < x or y == z


>>> res
>>> res
4
 Solutions
What  is  the  output  of  res  in  each  case?    Assume  x,y  and  z  take  the  
values  as  shown  below:

>>> x = 5
>>> y = 1
>>> z = 5

>>> res = x < y   >>> res = y < x and z < y


>>> res   >>> res

False False

>>> res = x == z   >>> res = y < x or y == z


>>> res
>>> res
5
True True
Exercise 3: Logic Evaluation
▪ Using  what  you  have  learned  about  Comparison  Operators  and  Boolean  expressions,  complete  
the  following  tables:
a b a  <  b  or  a  +  b  <  10 a b not  a  <  b  or  a  +  b  <  10
1 1 1 1

5 5 5 5

4 3 4 3

7 9 7 9

3 4 3 4

a b a  <  b  and  a  +  b  <  10 a b not(a  <  b  or  a  +  b  <  10)


1 1 1 1

5 5 5 5

4 3 4 3

7 9 7 9

3 4 3 4
 Solutions
a b a  <  b  or  a  +  b  <  10 a b not  a  <  b  or  a  +  b  <  10
1 1 True 1 1 True

5 5 False 5 5 True

4 3 True 4 3 True

7 9 True 7 9 False

3 4 True 3 4 True

a b a  <  b  and  a  +  b  <  10 a b not(a  <  b  or  a  +  b  <  10)


1 1 False 1 1 False

5 5 False 5 5 True

4 3 False 4 3 False

7 9 False 7 9 False

3 4 True 3 4 False
Exercise 4: Boolean Practice
▪ Write compound Boolean conditions to test for the following:

1. An  integer  variable  count  being  in  the  range  0  to  20  inclusive.  

2. An  integer  variable  count  being  outside  of  the  range  0  to  20  inclusive.  

3. Whether  the  three  integer  values  s1,  s2,  s3  are  valid  lengths  for  the  sides  
for  a  triangle.    This  requires  that  all  three  are  greater  than  zero,  and  that  
the  sum  of  any  two  is  greater  than  the  third  value.
Exercise 4: Boolean Practice
4. Assuming s1, s2, s3 are valid lengths for the sides of a triangle (from part
(3)), is the triangle equilateral? That is, are all sides the same length?

5. Assuming s1, s2, s3 are valid lengths for the sides of a triangle (from part
(3)), is the triangle isosceles? That is, are only two sides the same length?

6. Assuming s1, s2, s3 are valid lengths for the three sides of a triangle (from
part (3)), is the triangle scalene? That is, are all sides of different lengths?

Note: there are at least two different general approaches to writing this last
statement - see if you can figure out two different ways to do this!
 Solutions
▪ Question 3: Write compound Boolean conditions to test for the
following (refer to question 1 if you need help):

a) An integer variable count being in the range 0 to 20 inclusive.

0 <= count <= 20  

b) An integer variable count being outside of the range 0 to 20 inclusive.

not(0 <= count <= 20)  

c) Three integer values s1, s2, s3 are valid lengths for the sides for a triangle –
this requires that all three be greater than zero, and that the sum of any two
be greater than the third.

(s1 > 0 and s2 > 0 and s3 > 0 and s1+s2 > s3 and s1+s3 > s2 and s2+s3 > s1)
 Solutions
d) With s1, s2, s3 valid lengths for the sides of a triangle (see question (c)
above), is the triangle equilateral (all side the same length)?

s1 == s2 and s1 == s3

e) With s1, s2, s3 valid lengths for the sides of a triangle (see question (c)
above), is the triangle isosceles (two sides the same length)?

s1 == s2 or s1 == s3 or s2 == s3  

f) With s1, s2, s3 valid lengths for the three sides of a triangle (see question
(c) above), is the triangle scalene (all sides of different lengths)?

Either:  
not ( s1 == s2 or s1 == s3 or s2 == s3)  
s1 != s2 and s1 != s3 and s2 != s3
Exercise 5: Syntax checking
▪ Find any syntax errors in the following:

Program A Program B  
if a < b : if a + b > 3 :  
print('a is larger than b')  
if b < 5 :
else: print(b)

elif a > 2

print('b is larger than a')
print(a)

b -= a
 else:

a += 1 print(a + b)  
print('a=', a, 'b=', b) else

print(a - b)  
print(a, b)

▪ Rewrite the code to make them run correctly


 Solutions
▪ Find any syntax errors in the following:
A. Only syntax error is in the second to last
if a < b : line where the indentation is wrong –
print('a is larger than b') Python wants consistent indentation in a
suite. Note that the fact that the strings
else:
are saying the wrong thing is not a syntax
print('b is larger than a') error, but a semantic error.
b -= a

a += 1
print('a=', a, 'b=', b)
B.
if a + b > 3 : On line 4 there is a missing ‘:’ at end of the
if b < 5 : elif clause. The else clause of the nested if
print(b)
 statement has the wrong indentation. The
elif a > 2
 final else clause (of the outer if statement)
print(a)
 is missing a ‘:’. The fact that the final suite
else:
 has a different indentation to the first suite
print(a + b) does not matter as far as syntax is
else
 concerned, but is bad programming
print(a - b) practice.
print(a, b)
 Solutions
▪ Solution:
A.
if a < b:
print('a is larger than b')
else:
print('b is larger than a')
b -= a
a += 1
print('a=', a, 'b=', b)
B.
if a + b > 3:
if b < 5:
print(b)
elif a > 2:

print(a)
else:

print(a + b)
else:
print(a - b)
print(a, b)
Exercise  6:  Random  Number  Generation
▪ (a):  In  a  script,  write  code  to  generate  a  random  number  between  1  –  10.    
Display  the  random  number  to  the  screen  as  follows:  

  The random number is: 7  

▪ Hint:  you  will  need  to  import  one  module  to  generate  a  random  integer.  

▪ (b):    Modify  your  program  so  that  it  first  asks  (prompts)  the  user  to  guess  
the  random  number  and  prints  the  guess  to  the  screen.      

▪ After  the  user’s  guess  has  been  printed,  the  randomly  generated  number  
between  1-­‐10  is  displayed  to  the  screen.
15
 Solutions
import random

# Generate the random number


number = random.randint(1, 10)

guess = int(input('Please enter your guess: '))


print('You guessed:',guess)

print('The random number is',number)

16
Exercise  7:  if-else statement  
▪ Recall  the  random  number  generator  program.    Write  code  to:  

Generate  a  random  number  between  1  –  10  and  then  ask  (prompt)  


the  user  to  guess  the  random  number.    Display  the  user’s  guess  to  the  
screen  and  the  random  number  to  the  screen,  using  the  phrases  
shown  below.      
     
    You guessed: <user’s guess>  
The random number is: <random number>

If  the  user  guesses  correctly,  display  the  congratulations  message  


below,  otherwise  display  the  commiserations  message.  
   

    Well done – you guessed it!

Too bad – better luck next time! 17


 Solutions
import random

# Generate the random number


number = random.randint(1, 10)

guess = int(input('Please enter your guess: '))


print('You guessed:',guess)

print('The random number is',number)

if guess == number:
print('Well done - you guessed it!')
else:
print('Too bad - better luck next time!')
18
Exercise  8:  if-elif-else statement
▪ Generate  a  random  number  between  1  –  10  and  then  ask  (prompt)  the  user  to  
guess  the  random  number.    Display  the  user’s  guess  to  the  screen  and  the  
random  number  to  the  screen,  using  the  phrases  shown  below.      
     
    You guessed: <user’s guess>
The random number is: <random number>

▪ If  the  user  guesses  correctly,  display:  


   
    Well done – you guessed it!

If  the  user  guesses  lower  than  the  random  number,  display:  Too low!

If  the  user  guess  higher  than  the  random  number,  display:  Too high!
19
 Solutions
import random

# Generate the random number


number = random.randint(1, 10)

guess = int(input('Please enter your guess: '))


print('You guessed:', guess)

print 'The random number is',number

if guess < number:


print('Too low')
elif guess > number:
print('Too high')
elif guess == number:
print('Well done - you guessed it!')
else:
print('Too bad - better luck next time!')
20
Exercises  9a  and  b:  ternary  expressions
▪ (a)  Write  a  piece  of  code  that  prompts  a  user  for  two  numbers.    Using  a  ternary  
expression,  if  the  first  number  is  larger,  output  this  value  and  the  statement  that  
this  is  the  larger  number.    Else,  output  the  second  number  followed  with  a  
statement  that  this  number  is  the  larger  of  the  two.      

▪ E.g.  the  output  can  look  something  like  that  below  (assuming  the  user  input  the  
values  10  and  5):  
   
10 is larger!

▪ (b)  Write  a  piece  of  code  that  prompts  the  user  for  their  name.    Using  a  ternary  
expression,  if  the  name  entered  is  the  same  as  your  own  name,  output  the  
statement  “Same  as  me!”.    Otherwise,  output  the  statement  “Not  the  same  as  
my  name!”  or  some  other  cheeky  message!      
▪ Hint:  you  can  use  the  operator  ==  to  compare  strings.  
21
 Solutions
▪ Program  (a)  

num1 = int(input('Please enter your first number: '))


num2 = int(input('Please enter your second number: '))

print('The numbers you entered are: ',num1,' and ',num2)


print(num1,' is larger') if num1 > 2 else print(num2,
'is larger')

▪ Program  (b)  

name = input('Please enter your first name: ')


print("The same as me!") if name == "Belinda" else
print("Not as good as my name!")  

22
Two-­‐up!
A  simplified  game  of  Two-­‐up    (http://en.wikipedia.org/wiki/Two-­‐up)  

General  game  play  :      A  person  is  selected  as  the  Spinner.  The  Spinner  tosses  two  
coins  in  the  air  until  they  win  or  lose.  
▪ Two  heads  means  the  Spinner  wins.    

▪ Two  tails  means  the  Spinner  loses.    

▪ Odds  (One  coin  lands  with  the  'head'  side  up,  and  the  other  lands  with  the  

'tails'  side  up)  means  the  Spinner  throws  again.    

For  this  exercise  you  are  being  asked  to  write  a  simplified  Two-­‐Up  simulator  
(see  the  next  page  for  more  information).
Two-­‐up!
Write  a  program  which  simulates  the  toss  of  two  coins.  

If  the  two  coins  land  heads  up,  display ‘Spinner Wins! Two heads!’.
If  the  two  coins  land  tails  up,  display  ‘Spinner Loses! Two tails!’.
Otherwise,  display  ‘Throw again!’.    

Your  output  should  be  presented  as:    

Coin 1: Heads   Hint:    use  the  random.randint()


Coin 2: Heads   function  to  simulate  a  coin  toss  (e.g.    0  
=  tails,  1  =  heads).      See  slide  46  for  
Spinner wins! Two heads!   more  information  about  the  random  
module.

Thanks for playing!


 Solutions
import random

# Generate random toss - tails = 0, heads = 1


coin1 = random.randint(0,1)
coin2 = random.randint(0,1)

if coin1 == 0:
print("Coin 1: Tails")
elif coin1 == 1:
print("Coin 1: Heads")

if coin2 == 0:
print("Coin 2: Tails\n")
elif coin2 == 1:
print("Coin 2: Heads\n")

if coin1 == 1 and coin2 == 1:


print("Spinner wins! Two heads!")
elif coin1 == 0 and coin2 == 0:
print("Spinner loses! Two tails!")
else:
print("Throw again!”)
print("\nThanks for playing!")

You might also like