Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Thursday, 23 May 2013

Programs to build (Python Turtle)

  1. Change the colour of the pen
  2. Draw a star with 12 points
  3. Draw a square using a for loop
  4. Draw a star using a for loop, fill in star in with colour
  5. Ask a user how big they want their square to be, then draw it
  6. Ask a user how big they want their star to be, then draw it - add this into program number 6
  7. Ask the user what shape they want, how big they want it to beand what colour they want it to be, then draw it
  8. Allow the user to define their own shapes
 

Monday, 22 October 2012

Programs to build 3

Programs to build 3

Hangman
As much as hangman is quite a simple game, when you are learning to program it can be quite challenging to think about where you are going to start, and what you can realistically achieve.
You need to break the game down into sensible chunks, and building the program up bit by bit. You need to decide what programming syntax should be used in order to get the desired outcome.
Here is an example, thought up by year 9's as to the stages of hangman:

Stages of Hangman:
1. The computer thinks up a word
2. The computer tells the user how many letters are in the word
3. The user guesses a letter
4.a. If the letter is in the word, the computer outputs where abouts in the word it goes
4.b. If the letter is not in the word, the computer outputs the correct stage of the "hangman" cycle
5. Stages 4.a. and 4.b. repeat until the word is guessed or the user is "hung"

Stages of Programming a Simplified version of the Hangman game:
1.a. A simple guess the word game. As the programmer you define what the word is, the user gets one guess and are either right or wrong. The whole word is being guessed in one go.
1.b. The game continues until the user has guessed the word correctly.
2. A number of different words are stored in the program, and one is chosen by random. The user has to guess this word.
3. The word is broken down into letters (in the program) and the user has to guess each letter in the word.

Monday, 15 October 2012

Programs to build 2

Programs to build 2

Guess the Number
Write a simple guess the number game, where you decided what the number was, saved it in the program and then the user had to guess it (The original version of the game meant that the game terminated after one guess)
Extension: The game keeps going until the user has guessed the number correctly
Extension 2: The user only gets 5 guesses
You will need: if statement, print, input, int, variables

Interest Calculator
Write a program which works out how much interest you have earnt over a certain number of years.
You have £300, the interest rate is 5% and you are keeping it in the account for 5 years.
The program should tell you how much interest you earn each year, and a total.
Extension: The user can input their own amount, interest rate and number of years
You will need: for loop, print, variables (Extension: input, float)

Guess the Number (v2)
Amend your Guess the Number game so that it runs until the person has guessed the answer correctly. The number they are trying to guess should be chosen at random by the computer.
Extension: The user only gets 5 guesses
You will need: while, break, random

Logging in
Write a program which allows a user to "log on" to your system. Your program should ask the user for their user name and password, and check them against a username and password already stored in the program.
If they type both in correctly, they should get a message which says "Welcome", if they type either one in wrong they should get a message which tells them to try again. They should then be given the option of trying again.
You will need: if statement, boolean expression, variables, input, print

If, For, While, Random, Break, Boolean Expressions

If Statements
An if statement will run the code if a criteria is met.
See here for an example.

When you are checking the values, you can use the following operators:
== - equals to
!= - not equals to
> - greater than
< - less than
>= - greater than or equal to
<= - less than or equal to


For Loops
A for loop will repeat the code inside of it a certain amount of times.
You can define how often the code is run by changing the numbers in the brackets.
for x in range (0, 10):
  print("Hello world")
In the example above x goes up by 1 each time until the whole code has been repeated 9 times.


While...
A while statement is used because you want something to run if a condition is met, or until a condition is no longer met.
num = int(input("Please enter a number: "))
while num != 5:
  print("The number is not 5")
  num = int(input("Please try another number :))
In the example above the user inputs a number. While the number they enter is not 5, the program outputs a message and then asks them to try again. The value in num is then changed to what the user types in the second time and the while statement is run again.
If the program did not ask for the user to input the number again after the output message, the while statement would just output the message "The number is not 5" forever....

You can use the same operators as you can for if in a while statement.

Import Random
Sometimes you want the computer to choose a number at random for you.
You do this by importing the random number generator (a lot like when we imported the turtle this needs to go right at the top).
import random
myNum = random.randint(0, 5)
The code above will randomly pick a number between the values in the brackets, and save whatever number it picks in the variable myNum.


Break
This is how you get a program to stop running.
break
Any code after this will not be run in your program - so be careful where you use it!

Boolean Expressions
Boolean expressions are how the computer checks if a value is true or false. You can also use boolean expressions to check if two or more values are the same or not.
With an if statement we checked one value with symbols, with boolean expressions we check two or more values with 'and' and 'or'.
The example below uses logging onto the school network as an example, although the true and false options stop the same, regardless of the circumstances.

EXAMPLE: Username and password - in order to log onto the school network both your user name and password need to be correct.
Username AND password.
If you type both of them in correctly then the computer sees the answer as being True and so it lets you log on.
If username is correct but password is incorrect, it sees the answer as being False and wont let you log on.
If username is incorrect but password is correct, it sees the answer as being False and wont let you log on.
If username is incorrect and password is incorrect, it sees the answer as being False and wont let you log on.

Username and password - lets pretend that you only need either your username or your password to be correct in order to log on. It doesn't matter if one is wrong so long as one is right.
Username OR password.
If you type both of them in correctly then the computer sees the answer as being True and so it lets you log on.
If username is correct but password is incorrect, it sees the answer as being True and so it lets you log on.
If username is incorrect but password is correct, it sees the answer as beingTrue and so it lets you log on.
If username is incorrect and password is incorrect, it sees the answer as being False and wont let you log on.


How to use boolean expressions in your code...
num1 = int(input("Please input a number: "))
num2 = int(input("Please input a second number: "))
if num1 == 4 and num2 == 6:
  print("Well done you must be psychic!")
if num1 == 4 or num2 == 6:
  print("Half way there!")
The code above asks the user to input two numbers. These are then stored in the variables num1 and num2.
An if statement then checks what they have typed in against some criteria.
On like 3, the if statement uses the "and" boolean operator to check if both numbers are the same as the ones in the program. In order for the program to consider this statement 'True' (and therefore run the code underneath it) both of the number have got to be the same as the ones saved in the program - in that order.
On link 5, the if statement uses the "or" boolean operator to check if either of the numbers are the same as the ones stored in the program. If they are correct with either of them the program will print out the "Half way there" message.

Monday, 8 October 2012

Programs to build

Programs to build

Hello World
Write a program which outputs the words "hello world".
You will need: print

Hello name
Write a program which asks a user for their name, then outputs "Hello _____ " (With ____ being whatever they typed in.
Extension: Ask the user for their first name and surname separatley  but print them out on the same line ("Hello _firstname_ _surname_")
You will need: print, input, variables

Mathematical operators
Write a program which asks a user to input their date of birth. The program then adds together what they input and outputs a number. The program should tell the user that this is their lucky number.
Extension: Adapt the program so that it is not obvious what maths has been done to calculate the lucky number (a bit like a secret code)
You will need: print, input, variables, mathematical operators

Writing lists
Write a program which stores 10 of your favourite things in a list. Using code delete out the 6th item in the list, add another favourite thing to the end of the list and print the list out 5 times. It is a good idea to check that your code is working properly - and we do this by printing out the list every time we change it.
You will need: list, print, delete, append

Using tuples
Write a program which stores a list of numbers in a turple, and a list of numbers in a list. The program should output the fourth number in the list, and the third number in the tuple.
Extension: Do some maths combining numbers from the list and tuple and output the answers.
You will need: list, turple, print

Print, Input, Mathematical Operators, Lists & Turples

User Input
input() - a user has to input something, it can be text or numbers. Usually there is a message in the brackets (the message needs to be in quotes).
int() - integer - this is a whole number. It means that the user cannot input letters.
int(input("Message here: ")) - how it would look if you wanted someone to input an integer!
The code above wouldn't work, because you need to have a variable in which to save the users answer.

Print
Print is where you want the program to output something.
You can output messages, or variables, or a combination of the two.

age = int(input("Please input your age: "))
print("You are ", age, " years old.")

In the example above, the commas separate out the different bits of the code.

Operators (Mathematical and otherwise)
= - this means that you are saving (or setting) something to a value.
x = 4
This means that x is set to 4.
x = input("Please input your name")
This means that x is set to whatever the user types in.
Think carefully; is x a sensible variable name in the example above?

== - this means that you are checking one value against another.
if x == 4:
  print("x equals 4")
The code above means that is the value store in x is 4, print the message.

+ - This adds things together
- - This subtracts
/ - This divides
* - This multiplies

> - This is greater than
< - This is less than

Lists
A list is where you can store a lot of things (attributes) to one variable (Remember, variable means it can change).
To define a list, it needs a name and then all of the attributes go inside square brackets.
my_list = ["bob", "apple", "green"]
The above list has three attributes 1, 2 and 3.
IMPORTANT: Because nothing in life is easy, even though we start counting at 1, the computer starts counting at 0.
Lists are variable, that means you can add to them and delete out attributes.
del my_list[1]
This would delete out the second thing from the list.
my_list.append("4")
This will add the number 4 to the end of the list.

Turples
A turple is like a list, but it cannot be changed - therefore it is constant.
A turple is defined in the same way as a list, except that it has round brackets and no quotes.
my_turple = (1,2,3)

Friday, 5 October 2012

If Statements (Example 2)

Here is another example of an "if statement", implemented with Python.
You need to think carefully about how you can adapt this "if statement" to meet the needs of your program.

shoesize = int(input("Please input your shoe size: "))

def bigfeet():
  print("You have very big feet!")

def smallfeet():
  print("You have small feet!")

if shoesize > 10:
  bigfeet
if shoesize < 4:
  smallfeet

The code above asks a user to input their shoe size. The program has two sections of code stored, one outputs (or prints) the message that they have big feet, the other outputs that they have small feet. Neither of these programs run at the start, they are just defined (that means you have just said what they are made up of).

How the program works
The user is asked to input their shoe size. Python will only accept an integer (whole number). Whatever the user types in (assuming that it is a number) is saved in the variable "shoesize".
The program then checks the number that is stored in the variable "shoesize" against some criteria. If the number stored in shoesize is bigger than 10, run the bit of code "bigfeet"; if the number stored in shoesize is less than 4, run the bit of code "smallfeet".

Wednesday, 3 October 2012

Shapes with User Input (Python)

Python Turtle is the drawing package which comes with Python.
Task: Create a program which allows a user to input a shape, what size they wanted it to be and what colour they wanted it to be.
The program should then draw the shape for them!

You needed to solve this programming problem by yourself using the knowledge you already have in python (using turtle, defining shapes, for loops, variables) as well as figuring out how to add in an "if statement".

What is an "if statement"?
An "if statement" is where the program to checks one thing against another. For example, if the variable shape has the word "star" saved in it, the program needs to run the bit of code that draws a star.

Here is what an "if statement" looks like:
if x == 3:
 print("X is equal to 3")

(The two equals signs means that Python is checking something. One equals sign means that the variable has been assigned that value.)

TASK/HINT: You need to amend your program to add in a number of "if statement" which checks what a user types in against a criteria. If the user has typed in a specific word and it meets the criteria then Python will run a bit of code.

If you go to my Google Docs the Python Turtle help sheet file is uploaded here.
If you go here you can look at Snake Wrangling for Kids (for Windows), or here for Mac. This explains about "if statements".


Monday, 1 October 2012

Python Turtle

Turtle is Python's drawing package. It is a lot like Logo but much more sophisticated.
Spelling, punctuation and spaces all matter!
If you get an error message you need to read it and try to figure out why it doesn't work! Usually the error message will tell you what line your problem is on (Although sometimes this might mean that the code on the line before that is wrong...)

This help sheet was made to get you started with the code.

Importing Turtles
In Python, the first thing you have to do is import the Turtle, otherwise Python doesn't know that you want to draw something.
To do this you write
import turtle
IMPORTANT: This always has to go at the top!


Drawing Shapes
To draw a shape you need to tell Python that you want to move the Turtle (think of the Turtle as being the arrow...). You can go forward (up), backwards (down), left or right but you need to tell Python how far you want the Turtle to move or turn.
turtle.forward(50)
The code above will move the Turtle forward 50 pixels.


For Loops
Programmers are lazy - what is the point in copying and pasting the same bit of code 5 times?
This is where for loops come in.
A for loop is where you tell the program to repeat something a certain number of times.
for x in range (1,5):
  turtle.forward(100)
  turtle.right(90)
The code above will repeat 4 times (you have to add an extra number onto the end). What shape will it draw?


Indentation
Python is very particular about the indents you put.
By indenting a bit of code you are saying that it "belongs" to the code above it. So in the for loop example, the forward and right turn belong to the for loop (Anything that isn't in the for loop needs to be aligned with the for x in range part of the code).
When you indent you should keep consistent. 
It is recommended that you indent by pressing the tab key once, or pressing space twice.
Whichever you decide to do you need to stick with it, or Python might get mardy!


Defining a Shape
This is where you say that a bit of code has a title, and it can be used (or "called upon") many times.
def mystar:
  for x in range(1,13):
    turtle.forward(100)
    turtle.right(130)
The code above will not run unless you tell Python that you want it to run though.
To run the code you type
mystar
This is useful if you want to draw a star many times, you could put the mystar bit of code in a for loop!


Setting Variables and User Input
A variable is a place where data can be saved. As the name suggests a variable can vary, so it might be that the data in it changes throughout the program.
User input is when the user interacts with the program in some way, usually by typing something in.
When the user types something in the program needs somewhere to save what they have typed in, and this is where variables are useful!
size = int(input("Please input the size you want your shape to be: "))
The code above says that the value of size is set to whatever number the user types in.
Size is a variable. The number that the user types in might not always be the same (therefor it varies...). This is where the number is saved.
Int means integer, which means that the program will only accept the user typing in a number.
Input means that the program is expecting the user to type something in.
The message in the quotes "" is just to help the user out, so they know what to do.


Using the variable in your program
In order to use the variable and let people choose how big they want their shape to be, the program needs to pass the number into the code which sets up how long the edges of the shape are.
import turtle


def mystar(size):
  for x in range(1,13):
    turtle.forward(size)
    turtle.right(130)

size = int(input("Please input the size you want your shape to be: "))
mystar(size)

This code has been altered slightly from the examples above.
After we have set up the definition of the star, we need to tell Python that we want to include the variable size when we are drawing the star. In the part of the code which draws the star, the size of the sides has been replaced by the variable size. 
The program runs, and the first thing which happens is that the user is asked to input a size for their shape (remember anything in "def" wont run until we tell Python to run it. If we never tell Python to run it then it will never get used!), then once the user has input their size, the mystar section of code is run, with the variable size being passed into that bit of code.


Introduction to Programming

In your option ICT/Computing lessons you will need to learn how to program.
This means that you need to be able to think logically and apply the knowledge you have in a variety of ways.
I will teach you the Python programming language and you need to apply what you know to solving problems and creating a program.
The answers might not always be obvious, which is why you have to think about what you are going to do before you do it (Planning....).

Example
If in class we learn about a "for loop" then you need to be able to decide when in your programming you might want to use a "for loop" and how you would adapt the code to make it work for the program.

This class will require you to have your brain plugged in, and to be able to solve problems and come up with your own conclusions based on what you already know.
The more you practice the better you will get at it!
 
We are learning Python 3, and you can download it for free at home. Just use the link in the "links" tab (Make sure you download version 3 though, otherwise your code will not work).
 

Helpsheets
Here are some help sheets which will support your learning.