More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
◑ Python IDE Dashboard

For Sale

for-sale

Learning Objectives


In this challenge we are learning how to use variables to store the characteristics of your house. Some of our variables will be used to store text (string) such as the street name of your house. Some variables will be used to store numbers, either whole numbers (integers) or numbers with a decimal place (reals/floats). For instance we could use a variable called numberOfBedrooms.

Once we have stored all the characteristics of our house we will use the print command in Python to print a full description of our house.

Using variables


Look at the example below to see how text (string) and numbers (integers or reals) are stored using variables.

streetName = "Turing Street"
typeOfHouse = "detached"
numberOfBedrooms = 3
price = 99999.99

Have you noticed the use of “speech marks” when storing a string?

Step #1


Use the trinket below to store the street name, town, type of house (terraced, semi-detached, detached, flat). Don’t forget the use of “speech marks”.

Step #2


Now save the number of bedrooms, number of reception rooms, number of floors and selling price of your house, using numerical values. You will not need to use speech marks.

Step #3

We will now use the print command to display a description of our house on screen.

We will combine statements such as “My house is located on ” and variables (such as streetname) to create a clear description of our house. To do this we will use the + operator.

Tip:


When combining two strings or a statement and a string variable we use the + operator. For instance:

print("A lovely " + typeOfHouse + " located on " + streetName + ".")

When combining a string or a statement with a numerical variable (integer or real) we have to cast (convert) this number into a string using the str() function. For instance:

print("This house consists of " + str(numberOfBedrooms) + " bedrooms.")

houses

Your Challenge


Complete your code to create a complete description of your house. For instance:

For sale: A superb semi-detached house located on Turing Street, London. This house contains 3 bedrooms and 2 reception rooms and is organised across 2 floors. It is for sale at ÂŁ1,000,000.

Extension:


Can you think of additional characteristics to describe your house? For instance number of bathrooms, etc.

Create more variables to store these new characteristics and complete your description of your house.

Challenge #2


Using if statements we can tell the computer whether to execute some lines of codes or not. Let’s create a few more variables to store whether or not your house has:

  • A front garden,
  • A back garden,
  • A swimming pool,
  • A garage,
  • etc.

Then, using if statements, we will decide whether or not to add information to our description.

For instance:

frontGarden = True
if frontGarden == True:
    print ("This house also benefits from a lovely front garden.")

Complete your code adding extra characteristics to your house and displaying a message when relevant using if statements.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

My superhero

superhero

Learning Objectives


In this challenge we are learning how to use variables to store the properties of a superhero. Some of our variables will be used to store text (string) such as the name of our super hero. Some variables will be used to store numbers, either whole numbers (integers) or numbers with a decimal place (reals/floats).

Once we have stored all our properties of our superhero we will use the print command in Python to print a full description of our superhero.

Using variables


Look at the example below to see how text (string) and numbers (integers or reals) are stored using variables.

name = "Baymax"
strength = 9
height = 1.85

Have you noticed the use of “speech marks” when storing a string?

Step #1


Use the trinket below to store the name, location, gender, name of the enemy, super powers of your superhero. Dont forget the use of “speech marks”.

name = "..."
location = "..."
gender = "..."
enemy = "..."
powers = "..., ..., ..."

Step #2


Now save the speed, age and strength of your superhero using numerical values. You will not need to use speech marks.

speed = 
strength = 
age = 

Step #3

We will now use the print command to display a description of our superhero on screen.

We will combine statements such as “My superhero is called ” and variables (such as name) to create a clear description of our superhero. To do this we will use the + operator.

Tip:


When combining two strings or a statement and a string variable we use the + operator. For instance:

print("Hello, my name is " + name + " and I live in " + location + ".")

When combining a string or a statement with a numerical variable (integer or real) we have to cast (convert) this number into a string using the str() function. For instance:

print("My strength score is " + str(strength) + " out of 10.")

Your Challenge


Complete your code to create a complete description of your superhero. For instance:

My name is Batman and I live in Gotham City. I am male and my enemy is The Joker.

Extension:


Can you think of additional properties to describe your superhero? For instance the colours of their costume, their height, their weight, etc.

Create more variables to store these new properties and complete your description of your superhero.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

12-hour clock

clock

Did You Know?


The 12-hour clock is a time convention in which the 24 hours of the day are divided into two periods: a.m. (from the Latin ante meridiem, meaning “before midday”) and p.m. (post meridiem, “after midday”). Each period consists of 12 hours numbered: 12 (acting as zero), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 11. The 24 hour/day cycle starts at 12 midnight (often indicated as 12 a.m.), runs through 12 noon (often indicated as 12 p.m.), and continues to the midnight at the end of the day.

24-hour to 12-hour clock convertor


Your challenge consists of writing a computer program that asks the end-user to enter a time in the 24-hour format (e.g. 18:36). The program will convert this time in the 12-hour format (e.g. 6:36 PM).

Solution


Extension


Amend this code to validate the user entry and make sure they enter a time between 00:00 and 23:59 and to display an error message if not.
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

Minecraft Trampoline

trampolineIn this post we will use Python 2 and Minecraft to create a virtual trampoline for Minecraft. We will first build the trampoline using Minecraft blocks (in Python). Then we will write a routine to make the main player bounce up and down on the trampoline.

Step 1: Let’s connect to the Minecraft World via our Python script


For this challenge we are using a Raspberry Pi with Minecraft and Python 2 pre-installed.

from mcpi import minecraft, block
import time 

mc = minecraft.Minecraft.create()

msg = "Hello Minecraft World from 101 Computing"
mc.postToChat(msg)

Now try this, just to make sure it works! You should see a message appearing on your minecraft screen. If you are not sure how to do this you may want to check our first minecraft + python tutorial.

(x,y,z) coordinates?

minecraft-xyz-coordinatesBefore getting started you need to understand how the (x,y,z) coordinates are used to retrieve the position of the player in the minecraft world or to add blocks at the right position. As you can see on the picture to the left, it is slightly confusing as the vertical axis is not the z axis but the y axis.

Step 2: Building the trampoline


Our trampoline will be quite basic. It will consists of 4 posts (made of stone blocks) and a 6 by 6 bouncing area made of wood (ouch!).

Before we can build this trampoline we are going to find the position of the player so we can build this trampoline next to our main player (in fact just 5 blocks away on the x axis)

So let’s see how this all works:

from mcpi import minecraft, block
import time 

mc = minecraft.Minecraft.create()
msg = "Hello Minecraft World from 101 Computing"
mc.postToChat(msg)

def buildTrampoline(x , y, z, width):
    time.sleep(1)
    mc.setBlock(x, y, z, block.STONE)
    mc.setBlock(x, y, z+width, block.STONE)
    mc.setBlock(x + width, y, pos.z, block.STONE)
    mc.setBlock(x+width, y, z+width, block.STONE)
    mc.setBlocks(x, y+1, z, x + width, y+1, z + width, block.WOOD)


#Let's get the player's coordinates
pos=mc.player.getPos()

#We will build the trampoline 5 blocks away from the player
trampoline_xPos = pos.x + 5
trampoline_yPos = pos.y
trampoline_zPos = pos.z
trampoline_width = 6

buildTrampoline(trampoline_xPos,trampoline_yPos,trampoline_zPos,trampoline_width)

trampoline2

Step 3: Make it Bounce!


Let’s first create a new routine to make the player bounce up in the sky using a for loop.

def bounce():
    x, y, z = mc.player.getPos()
    for i in range(1,21):
        time.sleep(0.01)
        mc.player.setPos(x,y+i,z)

We don’t have to worry about getting the player to go down as it will do so automatically (there is gravity in the minecraft world!).

Then we will use an infinite loop to constantly check on the player’s position. If the player is on the trampoline then we will call our bounce() procedure.

while True:
    x, y, z = mc.player.getPos()
    if (x>=trampoline_xPos and x<=(trampoline_xPos+trampoline_width)) and (z>=trampoline_zPos and z<=(trampoline_zPos+trampoline_width)):
          block_beneath = mc.getBlock(x, y-1, z)
          if block_beneath==17: #17 is wood
            bounce()

Complete script:

from mcpi import minecraft, block
import time

def buildTrampoline(x , y, z, width):
    time.sleep(1)
    mc.setBlock(x, y, z, block.STONE)
    mc.setBlock(x, y, z+width, block.STONE)
    mc.setBlock(x + width, y, pos.z, block.STONE)
    mc.setBlock(x+width, y, z+width, block.STONE)
    mc.setBlocks(x, y+1, z, x + width, y+1, z + width, block.WOOD)

def bounce():
    x, y, z = mc.player.getPos()
    for i in range(1,21):
        time.sleep(0.01)
        mc.player.setPos(x,y+i,z)

mc = minecraft.Minecraft.create()

msg = "Hello Minecraft World from 101 Computing"
mc.postToChat(msg)

#Let's get the player's coordinates
pos=mc.player.getPos()

#We will build the trampoline 5 blocks away from the player
trampoline_xPos = pos.x + 5
trampoline_yPos = pos.y
trampoline_zPos = pos.z
trampoline_width = 6

buildTrampoline(trampoline_xPos,trampoline_yPos,trampoline_zPos,trampoline_width)

mc.postToChat("Climb on the trampoline next to you to start bouncing.")

while True:
    x, y, z = mc.player.getPos()
    if (x>=trampoline_xPos and x<=(trampoline_xPos+trampoline_width)) and (z>=trampoline_zPos and z<=(trampoline_zPos+trampoline_width)):
          block_beneath = mc.getBlock(x, y-1, z)
          if block_beneath==17: #17 is wood
            bounce()

Your Challenge


Use the above script to make your trampoline.

Once you have it working adapt this script to create an escalator. The escalator should be built using a Python script. As the soon as the main player goes on the escalator they should automatically move up the stairs, one step at a time.

Tagged with: , ,

Avatar Generator

avatars4In this challenge we will use Python Turtle to create avatars. (An avatar is an icon representing a particular person in a computer game, Internet forum, etc.)

Try the code below. This code is using a few computing concepts such as:

  • A list to store the different colour codes,
  • (x,y) coordinates to position the turtle on the screen.



List?


In Python, a list is used to save a collection of values. For instance, to save all the different days of the week we could declare a variable called “daysOfTheWeek” and assign a list as follows:

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

Based on this what do you think len(daysOfTheWeek) would return?
What’s about daysOfTheWeek[0]?
Or daysOfTheWeek[3] ?

In our avatar generator code we use three lists to store all the different colours for the skin, the hair and the eyes:

skinColors = ["#FCD09D","#FAC47A", "#DBA965", "#CC9D5E","#A3855B","#806645","#665135"]
eyeColors = ["#489CF0","#15A315", "#8C3303"]
hairColors = ["#000000","#8C3303","#F5D907","#580000","#E31E00","#636363","#FFFFFF"]

By using the random library we can access a random value of a list.

import random #Only use this instruction once at the very beginning of your code

hairColors = ["#000000","#8C3303","#F5D907","#580000","#E31E00","#636363","#FFFFFF"]
hairColorIndex = random.randint(0,6)

print(hairColors[hairColorIndex])



(x,y) coordinates using turtle


quadrant-coordinates
On this trinket widget the turtle screen is 400 pixels wide. So:

  • the top left corner coordinates are (-200,200)
  • the top right corner coordinates are (200,200)
  • the bottom left corner coordinates are (-200,-200)
  • the bottom right corner coordinates are (200,-200)
  • the centre of the screen coordinates are (0,0)



Look at the canvas below to understand how (x,y) coordinates work:


Avatar Generator




Your Challenge


Start customising the above script to add a random colour for the background. You can select colour codes using www.colorpicker.com.

Then add a T-shirt to your avatar, using random colours too.

Customise your avatar further by adding a beauty spot, different colours of lipstick, a mustache, a beard etc.

Tagged with: , , ,

Le Tour de France

cyclist

Learning Objectives


By completing this challenge we are learning how to open and extract data from a text file, reading the file line by line. We will then use our program to make some calculations such as calculating the total distance of the race over 21 stages.

The Race


Le Tour de France is a cycling race that takes place over 21 stages (23 days in total, including two rest days). The text file below contains a list of the 21 stages as follows (based on the 2015 route):

Stage Number;Distance in km;Starting from;Arriving at
TextFileletour.txt

The Code


Your Challenge


Adapt this code to answer the following questions:

  • What stage is the longest stage (in distance)?
  • What stage is the shortest stage (in distance)?
  • What is the average distance per stage?
  • What is the total distance of the race in miles?
  • Between stage 16 and stage 17, once in Gap, cyclists have a rest day. How many kilometres have they been cycling for? How many kilometres are left till the end of the race?
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

Rainbow Challenge

rainbowIn this challenge we are going to use our coding skills to create some nice colour patterns. We will first look at the code given to create a rainbow effect to understand how it works. We will then adapt this script to create three other colour patterns.

Rainbow Effect


Try the code above. This code is using a few computing concetps such as:

  • A list to store the different colour codes,
  • Iteration using a for loop to loop through each colour in the list,
  • (x,y) coordinates to position the turtle on the screen.

List?


In Python, a list is used to save a collection of values. For instance, to save all the different days of the week we could declare a variable called “daysOfTheWeek” and assign a list as follows:

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

Based on this what do you think len(daysOfTheWeek) would return?
What’s about daysOfTheWeek[0]?
Or daysOfTheWeek[3] ?

Looping through a list


It is possible to access each value of a list one at a time using a for loop. Look at the following code to print the seven days of the week.

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

for day in daysOfTheWeek:
    print(day)

In our rainbow code we use a list to store all the different colours of the rainbow as follows:

rainbowColors = ["#FF0000","#FFA600","#FFFF00", "#62FF00", "#1E56FC","#4800FF","#CC00FF","#69C5FF"]

(x,y) coordinates using turtle


quadrant-coordinates
On this trinket widget the turtle screen is 400 pixels wide. So:

  • the top left corner coordinates are (-200,200)
  • the top right corner coordinates are (200,200)
  • the bottom left corner coordinates are (-200,-200)
  • the bottom right corner coordinates are (200,-200)
  • the centre of the screen coordinates are (0,0)

Look at the canvas below to understand how (x,y) coordinates work:

Colour Pattern #1


Use and adapt the script above to recreate this colour pattern. The colour codes are given to you in the colour palette below.
color-pattern-1

Colour Hex RGB
#0099e6 (0,153,230)
#43e0ef (67,224,239)
#c3e970 (195,233,112)
#ffa9c2 (255,169,194)
#d297d9 (210,151,217)

Colour Pattern #2


Use and adapt your script to recreate this colour pattern. The colour codes are given to you in the colour palette below.
color-pattern-2

Colour Hex RGB
#ff0000 (255,0,0)
#d61a1a (214,26,26)
#a50000 (165,0,0)
#ddb200 (221,178,0)
#e7e497 (231,228,151)

Colour Pattern #3: Using a Random pattern


Use and adapt your script to recreate this colour pattern. The colour codes are given to you in the colour palette below.

However there is no colour pattern here. Each circle uses a random colour from the colour palette.

Check the code below used to randomly pick a colour from:

import random #Only use this statement once, at the top of your Python program.

rainbowColors = ["#FF0000","#FFA600","#FFFF00", "#62FF00", "#1E56FC","#4800FF","#CC00FF","#69C5FF"]
randomColor = random.choice(rainbowColors)

color-pattern-3

Colour Hex RGB
#ECECEC (236,236,236)
#2198d5 (33,152,213)
#0f8975 (15,137,117)
#0f6089 (15,96,137)
#000000 (0,0,0)

Tagged with: , , ,

Turtle Maze Challenge

maze
Your challenge is to guide the turtle through the maze. To do so you will need to use the following instructions:

  • myPen.forward(100) to move forward by 100 pixels,
  • myPen.right(90) to turn right by 90 degrees,
  • myPen.left(90) to turn left by 90 degrees.

Complete the code


Using a for loop


Note that, as you progress through the maze you may also decide to use a for loop to repeat a set of instructions several times.
For instance:

for i in range(0,3):
   myPen.forward(100)
   myPen.left(90)

Video Tutorial:



unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

Pygame: How to control your sprite?

arrowKeysThis tutorial is the third tutorial in a series of five Pygame tutorials:

For this third tutorial we will complete the code from the previous tutorial:

Remember the aim is to create a car racing game. In the first tutorial we looked at how to create the background for our game (The road). In the second tutorial we added our first sprite called playerCar which is an instance of the Car class.

In this third tutorial we will add methods to our Car class to move the car to the left, right, forward, and backward.

We will then add event handlers to the main program loop to respond to keystroke events. When the player uses the arrow keys on the keyboard we will call our methods to move the playerCar on the screen.

Step 1: Adding Methods to the Car class.


Open the file car.py and add the lines 26 to 30 as follows:

import pygame
WHITE = (255, 255, 255)

class Car(pygame.sprite.Sprite):
    #This class represents a car. It derives from the "Sprite" class in Pygame.
    
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()
        
        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
 
        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])
        
        # Instead we could load a proper pciture of a car...
        # self.image = pygame.image.load("car.png").convert_alpha()
 
        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()

    def moveRight(self, pixels):
        self.rect.x += pixels

    def moveLeft(self, pixels):
        self.rect.x -= pixels

As you can see we have added two procedures to our class. In OOP (Object Orientated Programming) we call these procedures: methods. A method is a procedure or function associated to a class. Let’s look at the moveRight() method.

def moveRight(self, pixels):
   self.rect.x += pixels

The moveRight() method takes two arguments. The first one is implicit and is called self. It refers to the current object. The second one is called pixels and refers to the number of pixels we will use to move the car.

The body of our method only contains one line: self.rect.x += pixels
It is basically adding pixels to the current x coordinate of the object.

Step 2: Responding to keystroke events


arrowKeysLet’s look at the code for our main program. You may remember that in the first tutorial we talked about the main program loop. The first section of this loop is to respond to events such as user interactions when the user uses the mouse or the keyboard.

So let’s add two event handlers, one moving left and one for moving right using the left and right arrow keys of the keyboard. Each event handler will call the relevant method from the Car class. Check the code below with the new event handlers from line 37 to 45.

import pygame, random
#Let's import the Car Class
from car import Car
pygame.init()

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
        
SCREENWIDTH=400
SCREENHEIGHT=500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

playerCar = Car(RED, 20, 30)
playerCar.rect.x = 200
playerCar.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(playerCar)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            carryOn=False
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_x: #Pressing the x Key will quit the game
               carryOn=False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        playerCar.moveLeft(5)
    if keys[pygame.K_RIGHT]:
        playerCar.moveRight(5)
        
    #Game Logic
    all_sprites_list.update()

    #Drawing on Screen
    screen.fill(GREEN)
    #Draw The Road
    pygame.draw.rect(screen, GREY, [40,0, 200,300])
    #Draw Line painting on the road
    pygame.draw.line(screen, WHITE, [140,0],[140,300],5)
        
    #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
    all_sprites_list.draw(screen)

    #Refresh Screen
    pygame.display.flip()

    #Number of frames per secong e.g. 60
    clock.tick(60)

pygame.quit() 

All done… Save your files and try your code. You should now be able to control your car using the arrow keys!

Tagged with: , , ,

Captain Redbeard’s Treasure

pirateWe need your coding skills to locate the treasure of Captain Redbeard. The legend holds that Redbeard was a great pirate who sailed the Caribbean Sea, fiercely attacking any vessels from the British Navy he would encounter.

Redbeard was killed in battle with the British Navy in 1743. Legend holds that he received 20 stab wounds and five gunshot wounds before finally succumbing.

But the legend also tells us that he buried his treasure before his final battle on Paradise Island, in the Caribbean waters. On his ship the British Navy found a treasure map with a set of instructions that they have not been able to decode yet.

Will you be able to help them locate Captain Redbeard treasure?

Map of Paradise Island:


treasure-map

Captain Redbeard’s Instructions:

START
GOTO E7
POINT North

FOR step FROM 1 to 4
    MOVE FORWARD BY 1
END FOR

POINT West

REPEAT
    MOVE FORWARD BY 1
UNTIL FoundKey == True

TURN 180 Degrees

WHILE StillOnMap == True
    MOVE FORWARD BY 1
    IF FoundSpider == TRUE THEN
           CRUSH spider
           EXIT WHILE LOOP
    END IF
END WHILE 	

POINT South
MOVE FORWARD BY 2
DIG FOR TREASURE

Can you tell where Captain Redbeard’s treasure has been buried for all these years?

Tagged with:
Privacy Overview

This website will store some information about your preferences on your own computer inside a tiny file called a cookie. A cookie is a small piece of data that a website asks your browser to store on your computer or mobile device. The cookie allows the website to remember your actions or preferences over time.

You can delete all cookies that are already on your computer, and you can set most browsers to prevent them from being placed. However, if you do this, you may have to manually adjust some preferences every time you visit a site, and some services and functionalities may not work.

Most browsers support cookies, but you can set your browser to decline them and can delete them whenever you like. You can find instructions here for how you can do that on various browsers.

This website uses cookies to:

  1. Identify you as a returning user and to count your visits in traffic statistics analysis
  2. Remember your custom display preferences (such as light/dark theme option)
  3. Provide other usability features, including tracking whether you have already given your consent to cookies

Enabling cookies is not strictly necessary for the website to work but it will provide you with a better browsing experience.

The cookie-related information is not used to identify you personally and is not used for any purpose other than those described here.

There may also be other types of cookies created after you have visited this website. This site uses Google Analytics, a popular web analytics service that uses cookies to help to analyse how users use the site. The information generated by the cookie about your use of this website (including your IP address) will be transmitted to and stored by Google on servers in the United States. Google will use this information for the purpose of evaluating your use of other website, compiling reports on website activity, and providing other services relating to website activity and internet usage. Google may also transfer this information to third parties where required to do so by law, or where such third parties process the information on Google’s behalf. Google undertakes not to associate your IP address with any other data held by Google.