Tag: Python

S3 – Python Turtle

This weeks task is to solve the maze. You are not allowed to touch the black lines.

You can use any Python Turtle commands you want including

  • goto(x,y)
  • right(deg)
  • left(deg)
  • forward(length)

Save the image as maze.png and use the boilerplate code below in Thonny to start the task.


# Solve the maze
# Mr Stratton
# 7/6/19

from turtle import *
# Help here https://docs.python.org/3/library/turtle.html
setup(1000,600) # set the window size to 480x360 pixels
bgcolor('yellow') # set BG to yellow
bgpic("maze.png") # BG pic only works with PNG and GIF
title("Mr. Stratton's Maze Tutorial") # Title of window
color("red") # Colour line
# shape("arrow") # Shape of the turtle (“arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”)
turtlesize(3) # size of turtle (easier for some kids to see)
pensize(3) # Set the size of the pen

penup()
goto(-420,220)
pendown()
# vvvvvv Enter your code below here vvvvvv

After you have solved the maze answer these questions:

  1. How many programming steps did you take?
  2. Can you reduce the number of steps?

Save a new copy of the program and edit it to make it more efficient (fewer lines). The number of extra lines that my program needed is below.

Read more

Higher – Rock Paper Scissors – Solution

So when we implemented the code we got something like this

#Mr Stratton

import random

#set up variables
random.seed
object=["Rock","Paper","Scissors"]
playerChoice=""
computerChoice=""
winner=""

#Get players choice
playerChoice=object[int(input("Rock - 1\nPaper - 2\nScissors - 3\n"))-1]

#Get computer choice
computerChoice=object[random.randint(0,2)]

#get winner
if playerChoice=="Rock":
    if computerChoice=="Paper":
        winner="Computer"
    if computerChoice=="Scissors":
        winner="Player"
    if computerChoice==playerChoice:
        winner="Draw"
        
if playerChoice=="Paper":
    if computerChoice=="Scissors":
        winner="Computer"
    if computerChoice=="Rock":
        winner="Player"
    if computerChoice==playerChoice:
        winner="Draw"
        
if playerChoice=="Scissors":
    if computerChoice=="Rock":
        winner="Computer"
    if computerChoice=="Paper":
        winner="Player"
    if computerChoice==playerChoice:
        winner="Draw"
        

    
#display winner
print("\n"*10)
print("Player threw",playerChoice)
print("Computer threw",computerChoice)

if winner=="Player":
    print("Player is the winner")
    
if winner=="Computer":
    print("Computer is the winner")
    
if winner=="Draw":
    print("Its a draw")


However, although it does follow the design from yesterday it isn’t very effcient.
Can you see a way to make it more effient?

#Mr Stratton

import random

#set up variables
object=["Rock","Paper","Scissors"]
playerChoice=""
computerChoice=""
winner="Draw"

#Get players choice
playerChoice=object[int(input("Rock - 1\nPaper - 2\nScissors - 3\n"))-1]

#Get computer choice
computerChoice=object[random.randint(0,2)]

#get winner
if playerChoice=="Rock":
    if computerChoice=="Paper":
        winner="Computer"
    elif computerChoice=="Scissors":
        winner="Player"

        
elif playerChoice=="Paper":
    if computerChoice=="Scissors":
        winner="Computer"
    elif computerChoice=="Rock":
        winner="Player"

        
elif playerChoice=="Scissors":
    if computerChoice=="Rock":
        winner="Computer"
    elif computerChoice=="Paper":
        winner="Player"

        
else:
    print("Error in player choice")
    
#display winner
print("\n"*10)
print("Player threw",playerChoice)
print("Computer threw",computerChoice)
if winner=="Player":
    print("Player is the winner")
elif winner=="Computer":
    print("Computer is the winner")
else:
    print("Its a draw")

Read more

Python – Thonny

I know that some of you have struggled to get Python working at home, so let me introduce you to Thonny.

Thonny is a Python IDE for beginners, it has Python built in so no need for a seperate install. It has a lot of cool features that you may find useful. I am going to demo a few features (the following text is from the Thonny homepage http://thonny.org/ )

No-hassle variables.

Once you’re done with hello-worlds, select View → Variables and see how your programs and shell commands affect Python variables.

Variables table

Simple debugger. Just press Ctrl+F5 instead of F5 and you can run your programs step-by-step, no breakpoints needed. Press F6 for a big step and F7 for a small step. Steps follow program structure, not just code lines.

Stepping through statements

Step through expression evaluation. If you use small steps, then you can even see how Python evaluates your expressions. You can think of this light-blue box as a piece of paper where Python replaces subexpressions with their values, piece-by-piece.

N5 Python – Introduction

add2numbersOur 1st Python program makes use of a number of new constructs and variables.

# – Internal Commentary, anything after the # on the same line is ignored by the translator

= (Assignment) – values are assigned to the variables using an equals sign.

input() –  a string is captured from the keyboard using the input() function

int() – this function changes the datatype of the given variable to an integer (Whole number)

Expression – The expression is the right hand side of the =, this is evaluated and any calculations performed, the results are then assigned to the variable on the left hand side of the equals

print() – This function displays a string. The “,” is used to concatenate strings and add a space between them.

 

N5 & Higher – Input Validation (Python)

Input validation is used in both National 5 and at Higher. It consists of 3 parts.

  1. Get the user to enter a value
  2. While the value is wrong
  3.     Get the user to enter a value

The use of the while construct allows the program to repeatedly ask the user to enter valid data.

1
2
3
4
5
6
7
8
9
age=0

#Input Validation
age=int(input('Please enter your age>'))
while age<0 or age>120: # Check that age is between 0 and 120
    print('Please check your age is between 0 and 120')
    age=int(input('Please enter your age>'))
    
print('Welcome')

This can also be used with strings, can you work out how to modify the code so that it would only take a ‘Yes’ ‘No’ answer?

Python on Raspberry Pi

For a bit of a change the class were programming in Python on a Raspberry Pi.

The program below was used to create a Gold Block in Minecraft.

1
2
3
4
5
6
7
8
from mcpi . minecraft import Minecraft
import mcpi . block as block
mc = Minecraft . create ()
pos = mc. player . getPos ()
x = pos.x
y = pos.y
z = pos.z
mc. setBlock (x, y, z, block . GOLD_BLOCK .id)

Created using http://hilite.me/ and http://www.geocraft.org.uk/

Python – print()

The print() function displays a string to the screen. It can be used like this.

  • print(“hello there”) – displays hello there
  • print(4*4) – displays 16
  • print(“4*4”) – displays 4*4

Note that the last line has quotes around the calculation causing the string to be displayed.

You can use either a single quote ‘ or double quotes ” within the brackets. More on this later.

Python – Input()

Python input() function returns a string to the assigned variable. This can cause us problems when we want to store integers or floats.

We can use the int() function to convert the string to a integer or the float() function to convert it to a floating point. It is better to do this when you get the input or initialise the variable as you may forget later in the program.

InputInt
The first block of code shows Python returning a string. The second block of code uses a int() to return an Integer