More results...

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

Python Syntax

python-logo
This page summarises the syntax of the Python language. When using Python always remember two key rules:

  • Rule #1: Python is white-space dependent; code blocks are indented using spaces.
  • Rule #2: Python language is case sensitive. It matters for variables, functions and any keyword in general.
Input / OutputSelection (IF Statements)Iteration (Loops)ListsSubroutinesFile HandlingInput Validation

Annotations

# Single Line Comment

"""
Multi-line comment
by 101Computing.net
"""

Variables & Assignment Operator

myInteger = 1
myFloat = 3.14
myString = "Hello World"
myList = ["John","James","Laura"]

Input

# Text Input
playerName = input("What's your name?")

# Number/Integer Input
playerAge = int(input("How old are you?"))

# Number/Decimal Input
cost = float(input("How much does it cost?"))

Output

print("Hello World")

print("Hello " + playerName)

print("You are " + str(playerAge) + " years old.")

Casting

str(100)	# To convert a value to a string

int("100")	# To convert from a string to an integer

float("3.14")	# To convert from a string to a float

score = 5
print("Your score = " + str(score))

String Manipulation

# String Concatenation
playerName = "John"
myString = "Hello " + playerName + "!"

score = 5
print("Your score = " + str(score))


# Changing the case of a string
myString = "Hello World"
print(myString.upper())   # to print HELLO WORLD
print(myString.lower())   # to print hello world


# Extracting Characters of a String
myString = "Hello World"

print(myString[0])	# "H"
print(myString[0:5])	# "Hello"
print(myString[-5:])	# "World"


# Finding out the length of a string
print(len(myString))	# 11


# Splitting a string into a list of values
names = "John;James;Laura"
data = names.split(";") 
print(data[0]) # This would print: John

Random Library

#Import the random library
import random

#Generate a random number between 1 and 100
randomNumber = random.randint(1,100)

#Pick a value in a list at random
names = ["John","James","Luke"]
randomName = random.choice(names)

Arithmetic Operators

x = a + b	# Add
x = a – b	# Take away
x = a / b	# Divide
x = a * b	# Multiply
x = a ** 2	# to the power of
x = a // b    	# Quotient DIV
x = a % b   	# Remainder MOD

x += 1 # Increment x by 1
x -= 1 # Decrement x by 1
x *= 2 # Multiply x by 2
x /= 2 # Divide x by 2

Rounding a Number

pi = 3.14159
pi2 = round(pi,2)

print("Pi rounded to two decimal places: " + str(pi2))   # 3.14

IF Statements / Selection


Warning: Use the 4 spaces rule!!! (Indentation)

if numberOfLives == 0:
    print("Game Over!")


if number == 7:
    print("Seven")
else:
    print("Not seven!")


if number < 0:
    print("Negative Number")
elif number == 0:
    print("Zero")
else:
    print("Positive Number")


if number == 7:
    print("Seven")
elif number == 8:
    print("Eight")
elif number == 9:
    print("Nine")
else:
    print("Not seven, eight or nine")

Comparison Operators


The main comparison operators are:

Comparison Operator Meaning Example
== is equal to 4==4
!= is different from 4!=7
< is lower than 3<5
> is greater than 9>2
<= is lower or equal to 3<=5
5<=5
>= is greater or equal to 9>=2
5>=5

Comparison operators are used to check if a condition is true or false.

Boolean operators such as AND, OR and NOT can also be used to check multiple conditions at the same time.

e.g.

if timer>0 and numberOfLives>0:
    print("Carry on playing!")
else:
    print("Game Over")

Loops / Iteration


Warning: Use the 4 spaces rule!!! (Indentation)

for i in range(1,11):   # Using a range
    print i


for i in range(0,101,5):   # Using a step - e.g. count in 5
    print i

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
#Iterate through all the values of a list
for i in range(0,len(daysOfTheWeek)):
    print(daysOfTheWeek[i])

#Iterate through all the values of a list - Alternative method
for day in daysOfTheWeek :
    print(day)


string = "Hello World"
for character in string:  # Using a string
    print(character)


i=0
while i<=100:
    print i
    i = i + 1

# To exit from a loop at any time:
    break

Lists

days = ["Mon","Tue","Wed","Thu","Fri","Sat"]

days.append("Sun")

print(days[0]) 	 # "Mon"
print(days[1]) 	 # "Tue"
print(days[2]) 	 # "Wed"
…
print(days[6]) 	 # "Sun"

#Finding out the number of items in a list (length of a list)
print(len(days)) # 7

#Iterate through all the values of a list
for i in range(0,len(days)):
    print(days[i])

#Iterate through all the values of a list - Alternative method
for value in days:
    print(value)

Procedures


Warning: Use the 4 spaces rule!!! (Indentation)

def displayBanner(message) :
    print("---------------")
    print(message)
    print("---------------")

displayBanner("Hello World!")

Functions


Warning: Use the 4 spaces rule!!! (Indentation)

def add(x, y) :
    sum = x + y
    return sum

total = add(1,3)
print(total)  # this would display 4

File Handling – (Over)Writing a text file

file = open("myTextFile.txt","w")

file.write("Hello World\n");
  
file.close()

Be careful, when using the write command, you are overwriting the content of your file. If instead of overwriting the content of your file you want to append (write at the end of the file) check the next tab: “Append to a text file”.

File Handling – Appending data to a text file

file = open("myTextFile.txt","a")

file.write("Hello World\n");
  
file.close()

File Handling – Reading a text file line by line

file = open("myTextFile.txt","r")

for line in file:
    print(line)
  
file.close()

File Handling – Reading a CSV file line by line


CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a divider symbol such as a comma “,”, a semi-colon “;” or a pipe “|”.

In this case when reading a line of the text file you can use the split() method to then access each field one by one.

file = open("myTextFile.txt","r")

for line in file:
    data = line.split(";")
    print(data[0] + " - " + data[1] + " - " + data[2])
  
file.close()

File Handling – Reading a text file using a list

file = open("myTextFile.txt","r")

lines = file.readlines()

file.close()

for line in lines:
  print(line)

Input Validation: Presence Check

name = input("Enter your name:")

if name=="":
    print("Empty name!")
else:
    print("Thank you!")

Input Validation: Type Check – Integer?

number = input("Type a number:")

if number.isdigit():
    print("This is a number")
else:
    print("This is not a whole number")

Input Validation: Range Check

number = int(input("Type a number between 1 and 5:"))

if number>=1 and number<=5:
    print("Valid number")
else:
    print("Invalid number")

Input Validation: Lookup Check

drive = input("Can you drive?").lower()

if drive in ["yes","no"]:
    print("Valid answer")
else:
    print("Invalid answer")

Input Validation: Character Check

email = input("Type your e-mail address:")

if "@" in email:
    print("Valid e-mail address")
else:
    print("Invalid e-mail address")

Input Validation: Length Check

password = input("Type a password:")

if len(password)>=8:
    print("Valid password")
else:
    print("Invalid password")

Try Again! Using a While Loop:

name = input("Enter your name:")

while name=="":
    print("You must enter your name! Please try again!")
    name = input("Enter your name:")

print("Welcome " +  name)

You can investigate more advance approaches to implement validation subroutines on this blog post.

Othello Game

othello-gridOthello (a.k.a. Reversi) is a strategy board game for two players, played on an 8×8 board. There are sixty-four identical game pieces called discs which are white on one side and black on the other. Players take turns placing discs on the board with their assigned color facing up. During a play, any discs of the opponent’s color that are in a straight line and bounded by the disc just placed and another disk of the current player’s color are turned over to the current player’s color.

The object of the game is to have the majority of disks turned to display your color when the last playable empty square is filled.

Read more about the rules of the Othello game: https://en.wikipedia.org/wiki/Reversi.

Othello Challenge


In this challenge you will use HTML, CSS, and JavaScript to complete this game of Othello for two players.

You will first need to reverse-engineer the code provided. The code so far is used to:

  • Display the 8×8 grid using HTML and CSS.
  • Add a disc on the grid when the user clicks on a cell of the grid using the selectCell()
    function in JavaScript.
  • Refresh the grid on the screen using the refreshGrid() function in JavaScript.

The code provided uses a variable called grid, use to store a two-dimensional array (8×8) of integer values. Within this array, a 0 represents an empty place, a 1 represents a white disc and a 2 represents a black disc.

Your Task


Your task consists of:

  • Amend the selectCell() function in JavaScript in order to:
    • Check if user is allowed to place a disc on the selected cell.
    • Reverse any discs of the opponent’s color that are in a straight line and bounded by the disc just placed and another disk of the current player’s color.
    • Count the number of white and black discs and display the score on the page.
    • Check if the grid is full.
  • Add code to the resetGrid() JavaScript function to start a new game with an empty grid.

HTML, CSS and JavaScript Code

See the Pen OthelloChallenge by 101 Computing (@101Computing) on CodePen.

Tagged with: , ,

Moroccan Mosaic

ZelligeMoroccan mosaic, aka Zellige (الزليج‎‎), is a form of Islamic art and one of the main characteristics of Moroccan architecture. It consists of geometrically patterned mosaics, used to ornament walls, ceilings, fountains, floors, pools and tables. Each mosaic is a tilework made from individually chiseled geometric tiles set into a plaster base.

You can google examples of Zellige using this link.

In this challenge, we will investigate how to create our own mosaic using various geometric patterns. We will use Python Turtle to draw a regular polygon (e.g. pentagon, hexagon, etc.) and repeat and rotate this shape several times to create a circular pattern/mosaic.

Mosaic Code: Using one polygon shape:


Amend the code below by changing the value of the three parameters used by the drawMosaic() function. View the impacts of these changes on your final mosaic.

python-turtle-mosaics-1

Mosaic Code: Combining two polygon shapes:


The code below combines two different types of regular polygons to create a more complex pattern:

python-turtle-mosaics-2

unlock-access

Solution...

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

2D Shapes using Python Turtle

In this challenge we will use Python Turtle to draw regular polygons including:

  • An equilateral triangle
  • A square
  • A pentagon
  • An hexagon
  • etc.

Did you know?


In Euclidean geometry, a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Regular polygons may be convex or star.

Convex Regular Polygons


Looking at the following three polygons, we can work out a formula to calculate the external angle of a convex regular polygon based on its number of sides.
exterior-angle-triangle

exterior-angle-square

exterior-angle-pentagon

Exterior Angle = 360 / number of sides

Python Code


Based on this formula we have implanted a function called drawPolygon() which takes one parameter called numberOfSides. This function will draw the corresponding convex regular polygon on screen.

Star Regular Polygons


star-polygons
Your challenge consists of coding a similar function, called drawStar(), used to draw star regular polygons on the screen. This function will take two parameters called numberOfSides and multiplier.

This time we will use a different formula to calculate the exterior angle:

Exterior Angle = multiplier * (360 / number of sides)

You can test your code with the following parameter values:

Star # Number of Sides Multiplier
#1 5 2
#2 8 3
#3 9 4
#4 10 3
#5 12 5
Tagged with:

Print Command Quiz

The first instruction you will most likely learn when using Python is the print() instruction. It is used to display/output a message on screen.

print("Hello World")

Using Variables
The print command can be used to output the content of a variable:

username="admin"
print("You are logged as:")
print(username)

Using String Concatenation
You can join multiple strings together (string concatenation using +) to print them on a single line:

username="admin"
print("You are logged as:" + username)

Casting numbers (e.g integers) into string and vice-versa:
You can convert (cast) a number (e.g integer) into a string using the str() function or convert/cast a string into an integer using the int() function:

score=10
print("Your score:" + str(score))

Take the Quiz! (open full screen)


How Old is Your Cat?

catIn this challenge we are going to create a cat’s age convertor find out how old a cat is in “human years”. This is very useful to understand more about cats and the care they need and to find out at what stage of life a cat is.
To convert the age of a cat in human years you have to do the following:

  • Year 1 counts for 15 Human Years
  • Year 2 counts for 9 Human Years
  • Thereafter each year counts for 4 Human Years

For example:

  • A 1 year old cat is 15 Human Years old,
  • A 2 years old cat is 15 + 9 = 24 Human Years old,
  • A 3 years old cat is 15 + 9 + 4 = 28 Human Years old,
  • A 4 years old cat is 15 + 9 + 4 + 4 = 32 Human Years old,
  • A 5 years old cat is 15 + 9 + 4 + 4 + 4= 36 Human Years old,
  • A 10 years old cat is 15 + 9 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 = 56 Human Years old.

You can check the full cat’s age conversion chart at the bottom of this post.

Your Challenge

Complete the following code to ask the user to input the age of a cat in years and return the equivalent in human years.

Extension #1

Amend your code so that it also works for cats under 1 year old. In this case you will have to ask for the cat’s age in months and use the conversion chart below (At the bottom of this post) to return the cat’s age in human years.

Extension #2

The stages of life of a cat are as follows:

  • Kitten – from birth to 6 months,
  • Junior – from 7 months to 2 years,
  • Prime – from 3 years to 6 years,
  • Mature – from 7 years to 10 years,
  • Senior – from 11 years to 14 years,
  • Geriatic – from 15 years above.

Extend your code to tell the end-user what stage of life their cat’s age is corresponding to.

Extension #3

Create another program where the user enters their age in human years and the program tells the user how old they would be if they were a cat!

Cat’s age conversion chart:

Life Stage Cat years Human years
Kitten2 months9 to 10 months
3 months2 to 3 years
4 months5 to 6 years
5 months8 to 9 years
6 months10 years
Junior8 months13 years
1 year15 years
2 years24 years
Prime3 years28 years
4 years32 years
5 years36 years
6 years40 years
Mature7 years44 years
8 years48 years
9 years52 years
10 years56 years
Senior11 years60 years
12 years64 years
13 years68 years
14 years72 years
Geriatric15 years76 years
16 years80 years
17 years84 years
18 years88 years
19 years92 years
20 years96 years
21 years and above100 years
unlock-access

Solution...

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

How many sweets in the jar?

how-many-sweets-in-the-jar“Guess how many sweets are in the jar” is a fundraising game. A large see-through jar is filled with a carefully counted number of sweets. People then try to guess how many sweets are in the jar. Each contestant has to donate a small amount of money to have a go. Guesses are recorded (name + guess). At the end of the game, the nearest guesser wins the content of the jar.

In this challenge we are using a Python script to record the names and guesses (number of sweets) of each contestant. We record this information in a list of lists called guesses.

Your challenge is to complete this code from line 63 to scan through all the guesses from this list and find out who has the nearest guess!

unlock-access

Solution...

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

Pascal Triangle

Pascal-triangle-animationIn mathematics, one of the most interesting number patterns is Pascal’s Triangle. It is named after Blaise Pascal (1623 – 1662), a famous French Mathematician and Philosopher.

To build a Pascal Triangle we start with a “1” at the top. We then place numbers below each number in a triangular pattern: Each number is the result of adding the two numbers directly above it. (See animation)

For this challenge we will use a Python script to output a Pascal Triangle after a fixed number of iterations (rows): e.g.

Pascal-Triangle

To do so we will use the following programming concepts:

  • Iteration: Each iteration will output one line of the triangle
  • List: We will use a list to store all the values appearing on one row
  • String Manipulation: We will use string manipulation techniques to format the output printed on screen (e.g. Our Pascal Triangle should appear centered on screen)

Python Code


We have started the code for you. You will need to complete this code form line 20.

unlock-access

Solution...

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

Infinite Quarter Series

The infinite quarter series is a series where each term is a quarter of the previous one:
infinite-quarter-series

We can visually represent this series by dividing a canvas (or price of paper) into 4 quadrants and colouring in one quadrant (bottom left). Then we repeat this process by dividing the top right quadrant into 4 and so on.

infinite-quarter-series-visual-representation-square

By doing so infinitely we will colour in a third of the initial canvas. This is because this infinite series converges to the value of 1/3.

Visual Demonstration using Python Turtle


Your Challenge


It is possible to visually represent this series using a triangle instead of a square.
Your task is to adapt the above Python script to represent this series using a triangle.
infinite-quarter-series-using-triangles

Help?


Check our flowchart to solve this challenge.
unlock-access

Solution...

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

Estimating Pi using Buffon’s Needle

Painting by François-Hubert Drouais - Musée Buffon à Montbard, France

Painting by François-Hubert Drouais – Musée Buffon à Montbard, France

A few hundred years ago people enjoyed betting on coins tossed on to a wooden floor … would they cross a line or not?

A French mathematician called Georges-Louis Leclerc, Comte de Buffon (1707-1788) started thinking about this and worked out the probability.

This probability is called “Buffon’s Needle” in his honor.

Buffon then used the results from his experiment with a needle to estimate the value of π (Pi). He worked out this formula:

π ≈ 2LN / CW

Where

  • L is the length of the needle
  • N is the total number of needles
  • C is the total number of needles crossing a line
  • W is the line spacing (Width of the wooden boards on the floor)

We have decided to simulate this experiment using a Python script (using Python Turtle).

Task 1


Run the above script and count how many needles (out of 50) are crossing a line. Apply Buffon’s formula to estimate the value of Pi using:
π ≈ 2LN / CW

  • L is the length of the needle (L = 30 pixels
  • N is the total number of needles (N = 50 needles)
  • C is the total number of needles crossing a line
  • W is the line spacing (Width of the wooden boards on the floor W = 40 pixels)

needle

Task 2


Adapt this Python script to automatically detect if a needle is crossing a line.

Your Python script should then count how many needles are crossing a line and use this to estimate a value of Pi.

unlock-access

Solution...

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