SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
Code Cards
For KS3, GCSE and IGCSE
Python 3
print() ................ 1
input() ................ 2
"strings" .............. 3
mathematical operators.. 4
comparison operators.... 4
while loops ............ 5
for loops .............. 6
range() ................ 6
if elif else ........... 7
functions .............. 8
random module .......... 8
turtle ................. 9 & 10
tkinter basics ......... 11
tkinter widgets ........ 12
using images ........... 13
importing modules ...... 14
tuples ................. 15
lists .................. 16
dictionaries ........... 17
string manipulation .... 18
reading text files ...... 19
writing to text files ... 19
classes ................ 20

objects ................ 21
Index
© 2015 by Chris Roffey. Except where otherwise noted, Coding Club Code Cards, is
licensed under the Creative Commons Attribution-ShareAlike 4.0 International License:
http://creativecommons.org/licenses/by-sa/4.0
© in the characters derived from Python Basics. Cambridge University Press 2012
print()
1
The print()function is very flexible:
>>> print("Hello World")
Hello World
>>> print("Hello World, " * 3)
Hello World, Hello World, Hello World,
>>> print("Hello Worldn" * 3)
Hello World
Hello World
Hello World
>>> text = "Hello"
>>> name = "Mia"
>>> print(text, name)
Hello Mia
>>> print(text, "your name is", name)
Hello your name is Mia
>>> print(text, "your name is", name, ".")
Hello your name is Mia .
>>> print(text, " your name is ", name, ".", sep="")
Hello your name is Mia.
>>> print(text, name, sep=",")
Hello,Mia
>>> name = input("What is your name? ")
What is your name? Daniel
>>> print(name)
Daniel
>>> my_name = "Mia"
>>> message = "My name is " + my_name
>>> message = message + ". What is your name? "
>>> user_name = input(message)
My name is Mia. What is your name? Daniel
>>> print(user_name)
Daniel
user_age = int(input("Enter your age: "))
# exit nicely
input("nnPress RETURN to finish.")
The input() function is not quite as flexible.
It can only accept a single string:
We can work around this though:
Ask the user for an integer:
The input()function can be used to end a program nicely
by providing this as the last line of code. Instead of suddenly
ending, this waits for the user to end the program:
input()
2
>>> my_string = "One ring to"
>>> my_string
'One ring to'
>>> my_string = my_string + " rule them all"
>>> my_string
'One ring to rule them all'
>>> my_string = my_string * 2
>>> my_string
'One ring to rule them allOne ring to rule them all'
>>> my_string = ""Hi Mia," said Daniel."
>>> print(my_string)
"Hi Mia," said Daniel.
>>> my_string = '"Hi Mia," said Daniel.'
>>> print(my_string)
"Hi Mia," said Daniel.
"strings"
Strings can be added to and multiplied:
Some escape sequences:
Escape sequence What it does
n creates a line return in a string
t creates a tab style indent in a string
 allows a backslash to appear in string
" allows a speech mark to appear in a string
Single or double quotes? You choose – but be consistent:
3
>>> 4*5
20
if a > b:
# do something
Python understands maths. This can be used
in scripts or directly in interactive mode:
Here are some of the more useful operators:
Operator Name Example Answer
* multiply 2*3 6
/ divide (normal) 20/8 2.5
// divide (integer) 20//8 2
% modulus (remainder) 20%8 4
+ add 2+3 5
- subtract 7-3 4
** exponent (raise to) 4**2 16
comparison operators
Comparison operators are most often used in if statements:
Operator Name Operator Name
== equal to < less than
!= not equal to >= greater or equal to
> greater than <= less or equal to
mathematical operators
4
>>> n = 0
>>> while n < 3:
print(n)
n = n+1
0
1
2
>>>
while True:
# code that runs until game is over goes here
if [game over test] == True:
break
While loops continue looping through a block
of code while a test is true:
Sometimes you might make a mistake in your code and the while
loop never becomes false. This is an infinite loop and can be
stopped by pressing CTRL-C
Other times you may want to intentionally create an infinite loop
that only stops when something happens, for example in a game.
This can be achieved by creating a while loop that is True and
using the break key word to allow your program to escape from
the loop when you are ready:
while loops
5
>>> colours = ("Red", "Orange", "Yellow")
>>> for colour in colours:
print(colour, end=" ")
Red Orange Yellow
The for loop is most useful for looping through
items in a container data-type e.g.
for loops
6
>>> for i in range(6):
print(i, end=" ")
0 1 2 3 4 5
>>> for i in range(2,6):
print(i, end=" ")
2 3 4 5
>>> for i in range(2,6,2):
print(i, end=" ")
2 4
range()
The range function takes three integer arguments:
range([start], [up to but not including], [steps])
starts from zero if omitted required only used with both other arguments
>>> colours = ("Red", "Orange", "Yellow")
>>> for i in range(1,2):
print(i, colours[i])
1 Orange
Putting it all together:
>>> my_number = 7
>>> if my_number > 5:
print("My number is big.")
My number is big.
>>> my_number = 2
>>> if my_number > 5:
print("My number is big.")
else:
print("My number is small.")
My number is small.
>>> my_number = 7
>>> if my_number < 5:
print("My number is small.")
elif my_number < 10:
print("My number is medium sized.")
elif my_number < 100:
print("My number is big.")
else:
print("My number is huge.")
My number is medium sized.
These control statements are used with logical
operators to provide control in programs:
if elif else
7
if
else
elif
print("This is my number:", number)
an argument another argument
def add_two_numbers(a,b):
print(a + b)
function name parameters
add_two_numbers(3,4)
7
arguments
# bind up arrow to the move_up() function:
window.bind("<Up>", move_up)
import random
dice_number = random.randint(1,6)
Python has some built in functions:
To make your own functions use the def key word:
Calling the function:
Parameter and argument are often used interchangeably. Strictly
speaking, parameters are used in the function definition. When we
call a function we pass it arguments.
Calling a function from the keyboard in tkinker (Card 11):
To use the random function, first import the random module:
functions
8
random numbers:
import turtle as t
t.forward(50)
First import the turtle module.
To avoid confusion between turtle commands
and your own function names, it is often a good idea
to import the turtle module and call its commands like this:
Some great turtle commands:
Command Arguments Example
forward() or fd() distance (pixels) forward(50)
back() or bk() distance (pixels) back(50)
right() or rt() angle (degrees) right(90)
left() or lt() angle (degrees) left(90)
home() none required
(turtle to start)
penup() none required
pendown() none required
speed() 10 = fast, 1 = slow,
6 = normal
0 = fast as possible
speed(6)
pensize() line width (pixels) pensize(10)
pencolor() common colours pencolor("red")
shape() arrow, turtle, circle,
square, triangle,
classic
shape("turtle")
turtle
9
Some more turtle commands:
Command Arguments Example
circle() radius (in pixels)
extent - angle of circle
to draw
steps - number of
lines used to make
the circle (can make
polygons)
# Draw pentagon
circle(50,steps=5)
fillcolor() common colours fillcolor("violet")
begin_fill() none required
(creates a start point
to fill a shape)
end_fill() none required
(creates a stop point
when filling a shape)
hideturtle() none required
showturtle() none required
color() common colours
(turtle colour)
color("brown")
setposition() x and y coords from
the origin (pixels)
setposition(50,60)
done() none required
(tells Python to stop
waiting for turtle
commannds)
see also: https://docs.python.org/3.4/library/turtle.html
turtle continued
10
The tkinter package provides a simple windowing
toolkit for your Python programs.
To create a simple, empty window:
Laying out widgets:
Using the grid layout manager some sophisticated layouts can be
achieved. Using grid() the window can be split into columns and
rows starting from top left (row=0, column=0).
from tkinter import *
# Create a window and add a title:
window = Tk()
window.title("My application")
# Other code goes here
# Start the infinite loop which watches for changes:
window.mainloop()
from tkinter import *
window = Tk()
def bye():
my_label.config(text="Bye bye")
my_label = Label(window, text="Hello World")
my_label.grid(row=0, column=0)
my_button = Button(window, text="Start", command=bye)
my_button.grid(row=1, column=0)
window.mainloop()
tkinter basics
11
On card 11 there was a button and a label.
Here are some other useful widgets that can be
added after window = Tk()
Add a canvas:
Add a text entry box with a label:
Add a frame:
A recipe to add a drop-down menu:
my_canvas = Canvas(bg="green", height=50, width=100)
my_canvas.grid(row=0, column=0)
Label(window, text="Name:").grid(row=0, column=0)
my_text_box = Entry(window, width=10)
my_text_box.grid(row=0, column=1)
frame1 = Frame(window,height=20,width=50,bg="green")
frame1.grid(row=0, column=0)
frame2 = Frame(window,height=20,width=50,bg="red")
frame2.grid(row=1, column=1)
options = (1,2,3)
var = IntVar()
var.set("choose:")
my_dropdown = OptionMenu(window, var, *options)
dropdown.grid()
tkinter widgets
12
cat = PhotoImage(file="images/cat.gif")
my_button = Button(window, image=cat)
from tkinter import *
window=Tk()
# build a canvas:
canvas = Canvas(window, bg="beige", height=100,
width=100)
canvas.grid(row=0,column=0)
# add an image:
cat = PhotoImage(file="images/cat.gif")
canvas.create_image(20, 40, image=cat, anchor=NW)
window.mainloop()
First, images need to be loaded into memory:
Images can be added to buttons (see card 11):
Images can be added to a tkinter canvas (see card 12):
canvas origin (0,0)
image's NW anchor point (20,40)
using images
13
from tkinter import *
Label(window, text="Name:")
import turtle
turtle.forward(50)
import turtle as t
t.forward(50)
Modules are files or groups of files outside of
your own script.
Importing a big group of modules the easy way:
Your code can now call the methods and functions directly from
the tkinter module without identifying where the code is from:
Never do this more than once in your code as you can start to
confuse where the functions and methods come from.
Importing a module and keeping track of where the functions
are coming from:
More typing is required but it is clear which code belongs
with which module:
The best of both worlds:
It is still clear where the functions come from but less typing is
needed:
importing modules
14
>>> my_tuple = ("Mon", "Tue", "Wed", "Thu", "Fri")
>>> my_tuple
('Mon', 'Tue', 'Wed', 'Thu', 'Fri')
>>> len(my_tuple)
5
>>> my_tuple[0]
'Mon'
>>> my_tuple[2]
'Wed'
>>> my_tuple.index("Thu")
3
Tuples are the simplest and most memory
efficient container data-type available in Python.
They are used to store a group of elements
that will not change:
Tuples are created with round brackets:
Find the length of a tuple (how many items it contains)
The elements are indexed from 0:
Locate an element in a tuple:
tuples
15
>>> my_list = ["Mon", "Tue", "Wed", "Thu", "Fri"]
>>> my_list
['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
>>> len(my_list)
5
>>> my_list[2]
'Wed'
>>> my_list.index("Thu")
3
>>> weekend = ["Sat", "Sun"]
>>> week = my_list + weekend
>>> week
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
>>> my_list.append(3)
>>> my_list
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 3]
>>> del my_list[5]
>>> my_list[3] = "January"
>>> my_list
['Mon', 'Tue', 'Wed', 'January', 'Fri']
Lists can do everything a tuple can do and more.
They are used to store a group of elements that
can change:
Lists are created with square brackets:
Lists can be combined:
Lists can be added to:
Elements can also be deleted and replaced in a list:
lists
16
>>> my_dict = {1:"b", 2:"a", 3:"r"}
>>> my_dict
{1: 'b', 2: 'a', 3: 'r'}
>>> my_other_dict = {"red":2, "green":5, "blue":3}
>>> my_other_dict
{'green': 5, 'blue': 3, 'red': 2}
>>> my_dict[5] = "t"
>>> my_dict
{1: 'b', 2: 'a', 3: 'r', 5:'t'}
>>> my_dict[5] = "g"
>>> del my_dict[3]
>>> my_dict
{1: 'b', 2: 'a', 5:'g'}
>>> len(my_dict)
3
>>> keys_list = list(my_dict.keys())
>>> keys_list
[1, 2, 5]
>>> values_list = list(my_dict.values())
>>> values_list
['b','a','g']
Dictionaries are another container data-type
but here we define the key. It is best to think of
dictionaries as unordered key:value pairs:
Dictionaries are created with curly brackets:
Adding, replacing, deleting items and finding the number of
elements in a dictionary is similar to lists:
Extracting keys and values into their own lists:
dictionaries
17
>>> string1 = ("Hello")
>>> string2 = ("World")
>>> string3 = string1 + " " + string2
>>> string3
'Hello World'
>>> len(string3)
11
>>> "e" in string3
True
>>> string3.find("l") #Only finds first instance
2
>>> string3.count("l")
3
>>> string3[1]
'e'
>>> string3.replace("e", "a")
'Hallo World'
>>> string4 = string3.upper()
>>> string5 = string3.lower()
>>> print(string3, string4, string5)
Hallo World HALLO WORLD hallo world
Strings can be treated like a container data-type:
Concatenation (adding strings):
Find the number of letters:
Find and replace letters:
Convert to uppercase or lowercase:
string manipulation
18
my_file = open("my_doc.txt", "r", encoding="utf-8")
my_list = list(my_file)
word_count=0
for line in my_file:
words = line.split()
for word in words:
word_count = word_count+1
print(word_count)
my_string = open("my_document.txt").read()
my_file.close()
my_file = open("hi.txt", "w", encoding="utf-8")
my_file.write("Ça van")
my_file.write("André")
my_file.close()
Store a reference to a file in a variable:
(This assumes the text file is in the same folder as the script.)
Store every line of text from your file in a list:
Loop through this file a line or word at a time:
Read a text file and store its contents in a string variable:
When finished, close the file to save system resources:
This will create a new text file called hi.txt
needed for non-ASCII characters
reading text files
19
writing to text files
class Cat:
# constructor:
def __init__(self, name):
self.name = name
# methods:
def speak(self):
print(self.name, "says: 'Meow'")
def drink(self):
print(self.name, "drinks some milk")
print(self.name, "takes a napn")
Classes are like factories. Many objects can be
built from then when they are sent orders.
Classes have to be built carefully:
Class name
Cat Cat class plan
Attributes
name
Methods
speak Python code for the Cat class
drink
classes
20
# Create two instances of a cat
romeo = Cat("Romeo")
juliet = Cat("Juliet")
# Play with Romeo
romeo.speak()
romeo.drink()
# Play with Juliet
juliet.speak()
juliet.drink()
Romeo says: 'Meow'
Romeo drinks some milk
Romeo takes a nap
Juliet says: 'Meow'
Juliet drinks some milk
Juliet takes a nap
(See card 20 for the corresponding Cat class)
From one class it is easy to create many different objects :
Objects can call all the methods from their creator class:
Here is the output from playing with the cats:
objects
21
Code Cards:
The Coding Club series for KS3:
Code Cards provide indexed, quick reminders and recipes for
the Python 3 code required at KS3, GCSE and IGCSE.
Keep them in your school jacket pocket (but remember to leave
them behind during exams!)
Red cards cover material found in Coding Club Level 1 books.
Blue cards cover material found in Coding Club Level 2 books.
Green cards cover Level 3 topics, usually not required at GCSE.
These cards are available in a variety of formats.
Visit www.codingclub.co.uk/codecards for further details.
Available from:
http://education.cambridge.org or Amazon.

Weitere ähnliche Inhalte

Was ist angesagt?

Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
Csphtp1 16
Csphtp1 16Csphtp1 16
Csphtp1 16HUST
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2Abdul Haseeb
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17OdessaFrontend
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08HUST
 
Python programming workshop session 4
Python programming workshop session 4Python programming workshop session 4
Python programming workshop session 4Abdul Haseeb
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES Aditya Shah
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09HUST
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202Mahmoud Samir Fayed
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 

Was ist angesagt? (20)

Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Csphtp1 16
Csphtp1 16Csphtp1 16
Csphtp1 16
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
 
Computer Programming- Lecture 10
Computer Programming- Lecture 10Computer Programming- Lecture 10
Computer Programming- Lecture 10
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
 
Computer Programming- Lecture 3
Computer Programming- Lecture 3Computer Programming- Lecture 3
Computer Programming- Lecture 3
 
Python programming workshop session 4
Python programming workshop session 4Python programming workshop session 4
Python programming workshop session 4
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 
.net progrmming part2
.net progrmming part2.net progrmming part2
.net progrmming part2
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 

Andere mochten auch

Python programming lab2
Python programming lab2Python programming lab2
Python programming lab2profbnk
 
Introduction to Graphics
Introduction to GraphicsIntroduction to Graphics
Introduction to Graphicsprimeteacher32
 
OSCON 2008: Porting to Python 3.0
OSCON 2008: Porting to Python 3.0OSCON 2008: Porting to Python 3.0
OSCON 2008: Porting to Python 3.0guest4d09
 
Python 3000
Python 3000Python 3000
Python 3000Bob Chao
 
PyTrening 2.0 # 15 Okienka GUI
PyTrening 2.0 # 15 Okienka GUIPyTrening 2.0 # 15 Okienka GUI
PyTrening 2.0 # 15 Okienka GUIMoniaJ
 
Python programming lab1
Python programming lab1Python programming lab1
Python programming lab1profbnk
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming LanguageYLTO
 
Python twitterとtkinterのことはじめ
Python twitterとtkinterのことはじめPython twitterとtkinterのことはじめ
Python twitterとtkinterのことはじめYukitaka Uchikoshi
 
10 more-things-you-can-do-with-python
10 more-things-you-can-do-with-python10 more-things-you-can-do-with-python
10 more-things-you-can-do-with-pythonDaniel Greenfeld
 
Tkinter Does Not Suck
Tkinter Does Not SuckTkinter Does Not Suck
Tkinter Does Not SuckRichard Jones
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd roundYouhei Sakurai
 
Chapter 11 Presentation
Chapter 11 PresentationChapter 11 Presentation
Chapter 11 PresentationAmy McMullin
 
Chapter 12 Presentation
Chapter 12 PresentationChapter 12 Presentation
Chapter 12 PresentationAmy McMullin
 

Andere mochten auch (20)

Python programming lab2
Python programming lab2Python programming lab2
Python programming lab2
 
Introduction to Graphics
Introduction to GraphicsIntroduction to Graphics
Introduction to Graphics
 
Apache Web Server Setup 3
Apache Web Server Setup 3Apache Web Server Setup 3
Apache Web Server Setup 3
 
OSCON 2008: Porting to Python 3.0
OSCON 2008: Porting to Python 3.0OSCON 2008: Porting to Python 3.0
OSCON 2008: Porting to Python 3.0
 
Python 3000
Python 3000Python 3000
Python 3000
 
Securing Apache Web Servers
Securing Apache Web ServersSecuring Apache Web Servers
Securing Apache Web Servers
 
PyTrening 2.0 # 15 Okienka GUI
PyTrening 2.0 # 15 Okienka GUIPyTrening 2.0 # 15 Okienka GUI
PyTrening 2.0 # 15 Okienka GUI
 
Python programming lab1
Python programming lab1Python programming lab1
Python programming lab1
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming Language
 
Python and you
Python and youPython and you
Python and you
 
Apache Web Server Setup 2
Apache Web Server Setup 2Apache Web Server Setup 2
Apache Web Server Setup 2
 
Python twitterとtkinterのことはじめ
Python twitterとtkinterのことはじめPython twitterとtkinterのことはじめ
Python twitterとtkinterのことはじめ
 
10 more-things-you-can-do-with-python
10 more-things-you-can-do-with-python10 more-things-you-can-do-with-python
10 more-things-you-can-do-with-python
 
An introduction-to-tkinter
An introduction-to-tkinterAn introduction-to-tkinter
An introduction-to-tkinter
 
Tkinter Does Not Suck
Tkinter Does Not SuckTkinter Does Not Suck
Tkinter Does Not Suck
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd round
 
Chapter 11 Presentation
Chapter 11 PresentationChapter 11 Presentation
Chapter 11 Presentation
 
Chapter 12 Presentation
Chapter 12 PresentationChapter 12 Presentation
Chapter 12 Presentation
 
20 cool things python
20 cool things python20 cool things python
20 cool things python
 

Ähnlich wie Cc code cards

Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schoolsDan Bowen
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
python lab programs.pdf
python lab programs.pdfpython lab programs.pdf
python lab programs.pdfCBJWorld
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Modify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfModify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfmallik3000
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88Mahmoud Samir Fayed
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)ExcellenceAcadmy
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)ExcellenceAcadmy
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
 

Ähnlich wie Cc code cards (20)

Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
python lab programs.pdf
python lab programs.pdfpython lab programs.pdf
python lab programs.pdf
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
Python basics
Python basicsPython basics
Python basics
 
Python ppt
Python pptPython ppt
Python ppt
 
Python programing
Python programingPython programing
Python programing
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Modify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfModify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdf
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 

Cc code cards

  • 1. Code Cards For KS3, GCSE and IGCSE Python 3
  • 2. print() ................ 1 input() ................ 2 "strings" .............. 3 mathematical operators.. 4 comparison operators.... 4 while loops ............ 5 for loops .............. 6 range() ................ 6 if elif else ........... 7 functions .............. 8 random module .......... 8 turtle ................. 9 & 10 tkinter basics ......... 11 tkinter widgets ........ 12 using images ........... 13 importing modules ...... 14 tuples ................. 15 lists .................. 16 dictionaries ........... 17 string manipulation .... 18 reading text files ...... 19 writing to text files ... 19 classes ................ 20 
objects ................ 21 Index © 2015 by Chris Roffey. Except where otherwise noted, Coding Club Code Cards, is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License: http://creativecommons.org/licenses/by-sa/4.0 © in the characters derived from Python Basics. Cambridge University Press 2012
  • 3. print() 1 The print()function is very flexible: >>> print("Hello World") Hello World >>> print("Hello World, " * 3) Hello World, Hello World, Hello World, >>> print("Hello Worldn" * 3) Hello World Hello World Hello World >>> text = "Hello" >>> name = "Mia" >>> print(text, name) Hello Mia >>> print(text, "your name is", name) Hello your name is Mia >>> print(text, "your name is", name, ".") Hello your name is Mia . >>> print(text, " your name is ", name, ".", sep="") Hello your name is Mia. >>> print(text, name, sep=",") Hello,Mia
  • 4. >>> name = input("What is your name? ") What is your name? Daniel >>> print(name) Daniel >>> my_name = "Mia" >>> message = "My name is " + my_name >>> message = message + ". What is your name? " >>> user_name = input(message) My name is Mia. What is your name? Daniel >>> print(user_name) Daniel user_age = int(input("Enter your age: ")) # exit nicely input("nnPress RETURN to finish.") The input() function is not quite as flexible. It can only accept a single string: We can work around this though: Ask the user for an integer: The input()function can be used to end a program nicely by providing this as the last line of code. Instead of suddenly ending, this waits for the user to end the program: input() 2
  • 5. >>> my_string = "One ring to" >>> my_string 'One ring to' >>> my_string = my_string + " rule them all" >>> my_string 'One ring to rule them all' >>> my_string = my_string * 2 >>> my_string 'One ring to rule them allOne ring to rule them all' >>> my_string = ""Hi Mia," said Daniel." >>> print(my_string) "Hi Mia," said Daniel. >>> my_string = '"Hi Mia," said Daniel.' >>> print(my_string) "Hi Mia," said Daniel. "strings" Strings can be added to and multiplied: Some escape sequences: Escape sequence What it does n creates a line return in a string t creates a tab style indent in a string allows a backslash to appear in string " allows a speech mark to appear in a string Single or double quotes? You choose – but be consistent: 3
  • 6. >>> 4*5 20 if a > b: # do something Python understands maths. This can be used in scripts or directly in interactive mode: Here are some of the more useful operators: Operator Name Example Answer * multiply 2*3 6 / divide (normal) 20/8 2.5 // divide (integer) 20//8 2 % modulus (remainder) 20%8 4 + add 2+3 5 - subtract 7-3 4 ** exponent (raise to) 4**2 16 comparison operators Comparison operators are most often used in if statements: Operator Name Operator Name == equal to < less than != not equal to >= greater or equal to > greater than <= less or equal to mathematical operators 4
  • 7. >>> n = 0 >>> while n < 3: print(n) n = n+1 0 1 2 >>> while True: # code that runs until game is over goes here if [game over test] == True: break While loops continue looping through a block of code while a test is true: Sometimes you might make a mistake in your code and the while loop never becomes false. This is an infinite loop and can be stopped by pressing CTRL-C Other times you may want to intentionally create an infinite loop that only stops when something happens, for example in a game. This can be achieved by creating a while loop that is True and using the break key word to allow your program to escape from the loop when you are ready: while loops 5
  • 8. >>> colours = ("Red", "Orange", "Yellow") >>> for colour in colours: print(colour, end=" ") Red Orange Yellow The for loop is most useful for looping through items in a container data-type e.g. for loops 6 >>> for i in range(6): print(i, end=" ") 0 1 2 3 4 5 >>> for i in range(2,6): print(i, end=" ") 2 3 4 5 >>> for i in range(2,6,2): print(i, end=" ") 2 4 range() The range function takes three integer arguments: range([start], [up to but not including], [steps]) starts from zero if omitted required only used with both other arguments >>> colours = ("Red", "Orange", "Yellow") >>> for i in range(1,2): print(i, colours[i]) 1 Orange Putting it all together:
  • 9. >>> my_number = 7 >>> if my_number > 5: print("My number is big.") My number is big. >>> my_number = 2 >>> if my_number > 5: print("My number is big.") else: print("My number is small.") My number is small. >>> my_number = 7 >>> if my_number < 5: print("My number is small.") elif my_number < 10: print("My number is medium sized.") elif my_number < 100: print("My number is big.") else: print("My number is huge.") My number is medium sized. These control statements are used with logical operators to provide control in programs: if elif else 7 if else elif
  • 10. print("This is my number:", number) an argument another argument def add_two_numbers(a,b): print(a + b) function name parameters add_two_numbers(3,4) 7 arguments # bind up arrow to the move_up() function: window.bind("<Up>", move_up) import random dice_number = random.randint(1,6) Python has some built in functions: To make your own functions use the def key word: Calling the function: Parameter and argument are often used interchangeably. Strictly speaking, parameters are used in the function definition. When we call a function we pass it arguments. Calling a function from the keyboard in tkinker (Card 11): To use the random function, first import the random module: functions 8 random numbers:
  • 11. import turtle as t t.forward(50) First import the turtle module. To avoid confusion between turtle commands and your own function names, it is often a good idea to import the turtle module and call its commands like this: Some great turtle commands: Command Arguments Example forward() or fd() distance (pixels) forward(50) back() or bk() distance (pixels) back(50) right() or rt() angle (degrees) right(90) left() or lt() angle (degrees) left(90) home() none required (turtle to start) penup() none required pendown() none required speed() 10 = fast, 1 = slow, 6 = normal 0 = fast as possible speed(6) pensize() line width (pixels) pensize(10) pencolor() common colours pencolor("red") shape() arrow, turtle, circle, square, triangle, classic shape("turtle") turtle 9
  • 12. Some more turtle commands: Command Arguments Example circle() radius (in pixels) extent - angle of circle to draw steps - number of lines used to make the circle (can make polygons) # Draw pentagon circle(50,steps=5) fillcolor() common colours fillcolor("violet") begin_fill() none required (creates a start point to fill a shape) end_fill() none required (creates a stop point when filling a shape) hideturtle() none required showturtle() none required color() common colours (turtle colour) color("brown") setposition() x and y coords from the origin (pixels) setposition(50,60) done() none required (tells Python to stop waiting for turtle commannds) see also: https://docs.python.org/3.4/library/turtle.html turtle continued 10
  • 13. The tkinter package provides a simple windowing toolkit for your Python programs. To create a simple, empty window: Laying out widgets: Using the grid layout manager some sophisticated layouts can be achieved. Using grid() the window can be split into columns and rows starting from top left (row=0, column=0). from tkinter import * # Create a window and add a title: window = Tk() window.title("My application") # Other code goes here # Start the infinite loop which watches for changes: window.mainloop() from tkinter import * window = Tk() def bye(): my_label.config(text="Bye bye") my_label = Label(window, text="Hello World") my_label.grid(row=0, column=0) my_button = Button(window, text="Start", command=bye) my_button.grid(row=1, column=0) window.mainloop() tkinter basics 11
  • 14. On card 11 there was a button and a label. Here are some other useful widgets that can be added after window = Tk() Add a canvas: Add a text entry box with a label: Add a frame: A recipe to add a drop-down menu: my_canvas = Canvas(bg="green", height=50, width=100) my_canvas.grid(row=0, column=0) Label(window, text="Name:").grid(row=0, column=0) my_text_box = Entry(window, width=10) my_text_box.grid(row=0, column=1) frame1 = Frame(window,height=20,width=50,bg="green") frame1.grid(row=0, column=0) frame2 = Frame(window,height=20,width=50,bg="red") frame2.grid(row=1, column=1) options = (1,2,3) var = IntVar() var.set("choose:") my_dropdown = OptionMenu(window, var, *options) dropdown.grid() tkinter widgets 12
  • 15. cat = PhotoImage(file="images/cat.gif") my_button = Button(window, image=cat) from tkinter import * window=Tk() # build a canvas: canvas = Canvas(window, bg="beige", height=100, width=100) canvas.grid(row=0,column=0) # add an image: cat = PhotoImage(file="images/cat.gif") canvas.create_image(20, 40, image=cat, anchor=NW) window.mainloop() First, images need to be loaded into memory: Images can be added to buttons (see card 11): Images can be added to a tkinter canvas (see card 12): canvas origin (0,0) image's NW anchor point (20,40) using images 13
  • 16. from tkinter import * Label(window, text="Name:") import turtle turtle.forward(50) import turtle as t t.forward(50) Modules are files or groups of files outside of your own script. Importing a big group of modules the easy way: Your code can now call the methods and functions directly from the tkinter module without identifying where the code is from: Never do this more than once in your code as you can start to confuse where the functions and methods come from. Importing a module and keeping track of where the functions are coming from: More typing is required but it is clear which code belongs with which module: The best of both worlds: It is still clear where the functions come from but less typing is needed: importing modules 14
  • 17. >>> my_tuple = ("Mon", "Tue", "Wed", "Thu", "Fri") >>> my_tuple ('Mon', 'Tue', 'Wed', 'Thu', 'Fri') >>> len(my_tuple) 5 >>> my_tuple[0] 'Mon' >>> my_tuple[2] 'Wed' >>> my_tuple.index("Thu") 3 Tuples are the simplest and most memory efficient container data-type available in Python. They are used to store a group of elements that will not change: Tuples are created with round brackets: Find the length of a tuple (how many items it contains) The elements are indexed from 0: Locate an element in a tuple: tuples 15
  • 18. >>> my_list = ["Mon", "Tue", "Wed", "Thu", "Fri"] >>> my_list ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] >>> len(my_list) 5 >>> my_list[2] 'Wed' >>> my_list.index("Thu") 3 >>> weekend = ["Sat", "Sun"] >>> week = my_list + weekend >>> week ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] >>> my_list.append(3) >>> my_list ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 3] >>> del my_list[5] >>> my_list[3] = "January" >>> my_list ['Mon', 'Tue', 'Wed', 'January', 'Fri'] Lists can do everything a tuple can do and more. They are used to store a group of elements that can change: Lists are created with square brackets: Lists can be combined: Lists can be added to: Elements can also be deleted and replaced in a list: lists 16
  • 19. >>> my_dict = {1:"b", 2:"a", 3:"r"} >>> my_dict {1: 'b', 2: 'a', 3: 'r'} >>> my_other_dict = {"red":2, "green":5, "blue":3} >>> my_other_dict {'green': 5, 'blue': 3, 'red': 2} >>> my_dict[5] = "t" >>> my_dict {1: 'b', 2: 'a', 3: 'r', 5:'t'} >>> my_dict[5] = "g" >>> del my_dict[3] >>> my_dict {1: 'b', 2: 'a', 5:'g'} >>> len(my_dict) 3 >>> keys_list = list(my_dict.keys()) >>> keys_list [1, 2, 5] >>> values_list = list(my_dict.values()) >>> values_list ['b','a','g'] Dictionaries are another container data-type but here we define the key. It is best to think of dictionaries as unordered key:value pairs: Dictionaries are created with curly brackets: Adding, replacing, deleting items and finding the number of elements in a dictionary is similar to lists: Extracting keys and values into their own lists: dictionaries 17
  • 20. >>> string1 = ("Hello") >>> string2 = ("World") >>> string3 = string1 + " " + string2 >>> string3 'Hello World' >>> len(string3) 11 >>> "e" in string3 True >>> string3.find("l") #Only finds first instance 2 >>> string3.count("l") 3 >>> string3[1] 'e' >>> string3.replace("e", "a") 'Hallo World' >>> string4 = string3.upper() >>> string5 = string3.lower() >>> print(string3, string4, string5) Hallo World HALLO WORLD hallo world Strings can be treated like a container data-type: Concatenation (adding strings): Find the number of letters: Find and replace letters: Convert to uppercase or lowercase: string manipulation 18
  • 21. my_file = open("my_doc.txt", "r", encoding="utf-8") my_list = list(my_file) word_count=0 for line in my_file: words = line.split() for word in words: word_count = word_count+1 print(word_count) my_string = open("my_document.txt").read() my_file.close() my_file = open("hi.txt", "w", encoding="utf-8") my_file.write("Ça van") my_file.write("André") my_file.close() Store a reference to a file in a variable: (This assumes the text file is in the same folder as the script.) Store every line of text from your file in a list: Loop through this file a line or word at a time: Read a text file and store its contents in a string variable: When finished, close the file to save system resources: This will create a new text file called hi.txt needed for non-ASCII characters reading text files 19 writing to text files
  • 22. class Cat: # constructor: def __init__(self, name): self.name = name # methods: def speak(self): print(self.name, "says: 'Meow'") def drink(self): print(self.name, "drinks some milk") print(self.name, "takes a napn") Classes are like factories. Many objects can be built from then when they are sent orders. Classes have to be built carefully: Class name Cat Cat class plan Attributes name Methods speak Python code for the Cat class drink classes 20
  • 23. # Create two instances of a cat romeo = Cat("Romeo") juliet = Cat("Juliet") # Play with Romeo romeo.speak() romeo.drink() # Play with Juliet juliet.speak() juliet.drink() Romeo says: 'Meow' Romeo drinks some milk Romeo takes a nap Juliet says: 'Meow' Juliet drinks some milk Juliet takes a nap (See card 20 for the corresponding Cat class) From one class it is easy to create many different objects : Objects can call all the methods from their creator class: Here is the output from playing with the cats: objects 21
  • 24. Code Cards: The Coding Club series for KS3: Code Cards provide indexed, quick reminders and recipes for the Python 3 code required at KS3, GCSE and IGCSE. Keep them in your school jacket pocket (but remember to leave them behind during exams!) Red cards cover material found in Coding Club Level 1 books. Blue cards cover material found in Coding Club Level 2 books. Green cards cover Level 3 topics, usually not required at GCSE. These cards are available in a variety of formats. Visit www.codingclub.co.uk/codecards for further details. Available from: http://education.cambridge.org or Amazon.