Python For Kids For Dummies
Book image
Explore Book Buy On Amazon
Python coding helps you with things you do every day, like math homework. Python programming can also help with things like making web pages: Thank goodness for widgets and keywords!

Python 2.7 keyword subset and examples

Programming is an important skill. Python will serve you well for years to come. The tables here give you the core words, built-ins, standard library functions, and operators that you’ll use most when you’re coding with Python.

Python Core Words
Keyword Summary Example
and Logical operator to test whether two things are both True. <conditional expression> and
<conditional expression>
x>2 and x<10
as Assign a file object to a variable. Used with with.
Let your code refer to a module under a different name (also called an alias). Used with import.
with open(<name of file>,<file mode>) as <object name>:
import cPickle as pickle
break Stop execution of a loop. for i in range(10):
    if i%2 ==0:
        break
class Define a custom object. class <name of class>(object):
    “”Your docstring“”
class MyClass(object):
    “”A cool function.””
continue Skip balance of loop and begin a new iteration. for i in range(10):
    if i%2 ==0:
        continue
def Define a function. def <name of function>(<argument list>):
    “”Your docstring“”
def my_function():
    “”This does… “”
elif Add conditional test to an if clause. See if.
else Add an alternative code block. See if.
for Create a loop which iterates through elements of a list (or other iterable). for <dummy variable name> in <sequence>:
for i in range(10):
from Import specific functions from a module without importing the whole module. from <module name> import <name of function or object>
from random import randint
global Make a variable global in scope. (If a variable is defined in the main section, you can change its value within a function.) global x
if Create a condition. If the condition is True, the associated code block is executed. Otherwise, any elif commands are processed. If there are none, or none are satisfied, execute the else block if there is one. if <conditional expression>:
   <code block>
[elif <conditional expression>:
    <code block>, …]
[else:
    <code block>]
if x == 1:
    print(“x is 1”)
elif x == 2:
    print(“x is 2”)
elif x > 3:
    print(“x is greater than 3”)
else
    print(“x is not greater than 3, nor is it 1 one or 2”)
import Use code defined in another file without retyping it. import <name of module>
import random
in Used to test whether a given value is one of the elements of an object. 1 in range(10)
is Used to test whether names reference the same object. x = None
x is None # faster than
x == None
lambda Shorthand function definition. Usually used where a function needs to be passed as an argument to another function. lamda <dummy variables>:
<expression using dummy variables>
times = lambda x, y: x*y
command=lambda x: self.draw_line(self.control_points)
not Logical negation, used to negate a logical condition. Don’t use for testing greater than, less than, or equal. 10 not in range(10)
or Logical operator to test whether at least one of two things is True. <conditional expression> or
<conditional expression>
x<2 or x>10
pass Placeholder keyword. Does nothing but stop Python complaining that a code block is empty. for i in range (10):
    pass
print Output text to a terminal. print(Hello World!)
return Return from the execution of a function. If a value is specified, return that value, otherwise return None. return <value or expression>
return x+2
while Execute a code block while the associated condition is True. while <conditional expression>:
while True:
    pass
with Get Python to manage a resource (like a file) for you. with open(<name of file>,<file mode>) as <object name>:

Extend Python’s core functionality with these built-ins.

Python Built-ins
Built-in Notes Example
False Value, returned by a logical operation or directly assigned. ok_to_continue = False
age = 16
old_enough = age >=21
(evaluates comparison age>=21
and assigns the result to old_enough)
None Value used when representing the absence of a value or to initialise a variable which will be changed later. Returned by functions which do not explicitly return a value. x = None
True Value, returned by a logical operation. ok_to_continue = True
age = 16
old_enough = age >=21
(evaluates comparison age>=21
and assigns the result to old_enough)
__name__ Constant, shows module name. If it’s not __main__, the code is being used in an import. if __name__==__main__:
dir List attributes of an item. dir(<object name>)
enumerate Iterate through a sequence and number each item. enumerate(Hello)
exit Exit Python (Command Line) interpreter. exit()
float Convert a number into a decimal, usually so that division works properly. 1/float(2)
getattr Get an attribute of an object by a name. Useful for introspection. getattr(<name of object>, <name of attribute>)
help Get Python docstring on object. help(<name of object>)
help(getattr)
id Show the location in the computer’s RAM where an object is stored. id(<name of object>)
id(help)
int Convert a string into an integer number. int(0)
len Get the number of elements in a sequence. len([0,1])
object A base on which other classes can inherit from. class CustomObject(object):
open Open a file on disk, return a file object. open(<path to file>, <mode>)
open(‘mydatafile.txt’, ‘r’) # read
(opens a file to read data from)
open(‘mydatafile.txt’, ‘w’) # write
(creates a new file to write to, destroys any existing file with the same name)
open(‘mydatafile.txt’, ‘a’) # append
(adds to an existing file if any, or creates
a new one if none existing already)
print Reimplementation of print keyword, but as a function.
Need to import from the future to use it (srsly!)
from future import print_function
print (‘Hello World!)
range Gives numbers between the lower and upper limits specified (including the lower, but excluding the upper limit). A step may be specified. range(10)
range(5,10)
range(1,10,2)
raw_input Get some text as a string from the user, with an optional prompt. prompt = What is your guess?
players_guess = raw_input(prompt)
str Convert an object (usually a number) into a string (usually for printing). str(0)
type Give the type of the specified object. type(0)
type(
0)
type([])
type({})
type(())

Use the work that others have already done. Try these modules from the Python standard library.

Selected Functions from the Standard Library
Module What It Does Sample Functions/Objects
os.path Functions relating to files and file paths. os.path.exists(<path to file>)
pickle, cPickle Save and load objects to/from a file. pickle.load(<file object to load from>), pickle.dump(<object to dump>, <file object to save to>)
random Various functions relating to random numbers. random.choice(<sequence to choose from>), random.randint(<lower limit>, <upper limit>), random.shuffle(<name of list to shuffle>)
String Stuff relating to strings. string.printable
sys Various functions related to your computer system. sys.exit()
Time Time-related functions. time.time()
Tkinter User interface widgets and associated constants. Tkinter.ALL
Tkinter.BOTH
Tkinter.CENTER
Tkinter.END
Tkinter.HORIZONTAL
Tkinter.LEFT
Tkinter.NW
Tkinter.RIGHT
Tkinter.TOP
Tkinter.Y
Tkinter.Button(<parent widget>,
text=<button text>)
Tkinter.Canvas(<parent widget>,
    width=<width>, height=<height>)
Tkinter.Checkbutton(<parent widget>,
    text=<checkbutton text>)
Tkinter.Entry(<parent widget>,
    width=<number of characters wide>),
Tkinter.Frame(<parent widget>)
Tkinter.IntVar()
Tkinter.Label(<parent widget>,
    text = <label text>)
Tkinter.mainloop()
Tkinter.Menu(<parent widget>)
Tkinter.OptionMenu(<parent widget>,
    None, None)
Tkinter.Scale(<parent widget>,
    from_=<lower limit>,
    to=<upper limit>)
Tkinter.Scrollbar(<parent widget>)
Tkinter.StringVar()
Tkinter.Tk()

Add, subtract, divide, multiply, and more using these operators.

Python Operators
Operator Name Effect Examples
+ Plus Add two numbers.
Join two strings together.
Add: >>> 1+1
2
Join: >>> a+b
ab
Minus Subtract a number from another.
Can’t use for strings.
>>> 1-1
0
* Times Multiply two numbers.
Make copies of a string.
Multiply: >>> 2*2
4
Copy: >>> a*2
aa
/ Divide Divide one number by another.
Can’t use for strings.
1/2 # integer division:
Answer will be rounded down.
1/2.0 # decimal division
1/float(2) # decimal division
% Remainder (Modulo) Give the remainder when dividing the left number by the right number.
Formatting operator for strings.
>>> 10%3
1
** Power x**y means raise x to the power of y.
Can’t use for strings.
>>> 3**2
9
= Assignment Assign the value on the right to the variable on the left. >>> a = 1
== Equality Is the left side equal to the right side? Is True if so; is False otherwise. >>> 1 == 1
True
>>> ‘a’ == ‘a’
True
!= Not equal Is the left side not equal to the right side? Is True if so; is False otherwise. >>> 1 != 1
False
>>> 1 != 2
True
>>> ‘a’ != ‘a’
True
> Greater than Is the left side greater than the right side?
>= means greater than or equal to
>>> 2 > 1
True
< Less than Is the left side less than the right side?
<= means less than or equal to
>>> 1 < 2
True
& (or and) And Are both left and right True?
Typically used for complex conditions where you want to do something if everything is True:
while im_hungry and you_have_food:
>>> True & True
True
>>> True and False
False   
>>> True & (1 == 2)
False
| (or or) Or Is either left or right True?
Typically used for complex conditions where you want at least one thing to be True:
while im_bored or youre_bored:
>>> True | False
True
>>> True or False
True
>>> False | False
False
>>> (1 == 1) | False
True

Use Python to help with your math homework

Python can do fractions so you can check your homework answers. Use the fractions module, and its Fraction object, specifying the numerator and denominator. To get one-half, type fractions.Fraction(1, 2). For four-fifths, type fractions.Fraction(4, 5):

>>> import fractions
>>> one_half = fractions.Fraction(1, 2)
>>> one_fifth = fractions.Fraction(1, 5)

Fractions can do normal fraction calculations (including multiplication and division) for you:

>>> one_half+one_fifth
Fraction(7, 10)
>>> one_half-one_fifth
Fraction(3, 10)
>>> one_half*one_fifth
Fraction(1, 10)
>>> one_half/one_fifth
Fraction(5, 2)

Using Tkinter widgets in Python

Tkinter in Python comes with a lot of good widgets. Widgets are standard graphical user interface (GUI) elements, like different kinds of buttons and menus. Most of the Tkinter widgets are given here.

Label Widget

image0.jpg

A Label widget shows text to the user. You can update the widget programmatically to, for example, provide a readout or status bar.

import Tkinter
parent_widget = Tkinter.Tk()
label_widget = Tkinter.Label(parent_widget, text="A Label")
label_widget.pack()
Tkinter.mainloop()

Button Widget

image1.jpg

A Button can be on and off. When a user clicks it, the button emits an event. Images can be displayed on buttons.

import Tkinter
parent_widget = Tkinter.Tk()
button_widget = Tkinter.Button(parent_widget,
    text="A Button")
button_widget.pack()
Tkinter.mainloop()

Entry Widget

image2.jpg

An Entry widget gets text input from the user.

import Tkinter
parent_widget = Tkinter.Tk()
entry_widget = Tkinter.Entry(parent_widget)
entry_widget.insert(0, "Type your text here")
entry_widget.pack()
Tkinter.mainloop()

Radiobutton Widget

image3.jpg

A Radiobutton lets you put buttons together, so that only one of them can be clicked. If one button is on and the user clicks another, the first is set to off. Use Tkinter variables (mainly Tkinter.IntVar and Tkinter.StringVar) to access its state.

import Tkinter
parent_widget = Tkinter.Tk()
v = Tkinter.IntVar()
v.set(1) # need to use v.set and v.get to
# set and get the value of this variable
radiobutton_widget1 = Tkinter.Radiobutton(parent_widget,
                                   text="Radiobutton 1",
                                   variable=v, value=1)
radiobutton_widget2 = Tkinter.Radiobutton(parent_widget,
                                   text="Radiobutton 2",
                                   variable=v, value=2)
radiobutton_widget1.pack()
radiobutton_widget2.pack()
Tkinter.mainloop()

Radiobutton Widget (Alternate)

image4.jpg

You can display a Radiobutton without the dot indicator. In that case it displays its state by being sunken or raised.

import Tkinter
parent_widget = Tkinter.Tk()
v = Tkinter.IntVar()
v.set(1)
radiobutton_widget1 = Tkinter.Radiobutton(parent_widget,
                                   text="Radiobutton 1",
                                   variable=v, value=1,
                                   indicatoron=False)
radiobutton_widget2 = Tkinter.Radiobutton(parent_widget,
                                   text="Radiobutton 2",
                                   variable=v, value=2,
                                   indicatoron=False)
radiobutton_widget1.pack()
radiobutton_widget2.pack()
Tkinter.mainloop()

Checkbutton Widget

image5.jpg

A Checkbutton records on/off or true/false status. Like a Radiobutton, a Checkbutton widget can be displayed without its check mark, and you need to use a Tkinter variable to access its state.

import Tkinter
parent_widget = Tkinter.Tk()
checkbutton_widget = Tkinter.Checkbutton(parent_widget,
                                    text="Checkbutton")
checkbutton_widget.select()
checkbutton_widget.pack()
Tkinter.mainloop()

Scale Widget: Horizontal

image6.jpg

Use a Scale widget when you want a slider that goes from one value to another. You can set the start and end values, as well as the step. For example, you can have a slider that has only the even values between 2 and 100. Access its current value by its get method; set its current value by its set method.

import Tkinter
parent_widget = Tkinter.Tk()
scale_widget = Tkinter.Scale(parent_widget, from_=0, to=100,
                             orient=Tkinter.HORIZONTAL)
scale_widget.set(25)
scale_widget.pack()
Tkinter.mainloop()

Scale Widget: Vertical

image7.jpg

A Scale widget can be vertical (up and down).

import Tkinter
parent_widget = Tkinter.Tk()
scale_widget = Tkinter.Scale(parent_widget, from_=0, to=100,
                             orient=Tkinter.VERTICAL)
scale_widget.set(25)
scale_widget.pack()
Tkinter.mainloop()

Text Widget

image8.jpg

Use a Text widget to show large areas of text. The Text widget lets the user edit and search.

import Tkinter
parent_widget = Tkinter.Tk()
text_widget = Tkinter.Text(parent_widget,
                           width=20, height=3)
text_widget.insert(Tkinter.END,
    "Text Widgetn20 characters widen3 lines high")
text_widget.pack()
Tkinter.mainloop()

LabelFrame Widget

image9.jpg

The LabelFrame acts as a parent widget for other widgets, displaying them with a title and an outline. LabelFrame has to have a child widget before you can see it.

import Tkinter
parent_widget = Tkinter.Tk()
labelframe_widget = Tkinter.LabelFrame(parent_widget,
                                   text="LabelFrame")
label_widget=Tkinter.Label(labelframe_widget,
       text="Child widget of the LabelFrame")
labelframe_widget.pack(padx=10, pady=10)
label_widget.pack()
Tkinter.mainloop()

Canvas Widget

image10.jpg

You use a Canvas widget to draw on. It supports different drawing methods.

import Tkinter
parent_widget = Tkinter.Tk()
canvas_widget = Tkinter.Canvas(parent_widget
                               bg="blue",
                               width=100,
                               height= 50)
canvas_widget.pack()
Tkinter.mainloop()

Listbox Widget

image11.jpg

Listbox lets the user choose from one set of options or displays a list of items.

import Tkinter
parent_widget = Tkinter.Tk()
listbox_entries = ["Entry 1", "Entry 2",
                   "Entry 3", "Entry 4"]
listbox_widget = Tkinter.Listbox(parent_widget)
for entry in listbox_entries:
    listbox_widget.insert(Tkinter.END, entry)
listbox_widget.pack()
Tkinter.mainloop()

Menu Widget

image12.jpg

The Menu widget can create a menu bar. Creating menus can be hard, especially if you want drop-down menus. To do that, you use a separate Menu widget for each drop-down menu you’re creating.

import Tkinter
parent_widget = Tkinter.Tk()
def menu_callback():
    print("I'm in the menu callback!")
def submenu_callback():
    print("I'm in the submenu callback!")
menu_widget = Tkinter.Menu(parent_widget)
submenu_widget = Tkinter.Menu(menu_widget, tearoff=False)
submenu_widget.add_command(label="Submenu Item1",
                           command=submenu_callback)
submenu_widget.add_command(label="Submenu Item2",
                           command=submenu_callback)
menu_widget.add_cascade(label="Item1", menu=submenu_widget)
menu_widget.add_command(label="Item2",
                        command=menu_callback)
menu_widget.add_command(label="Item3",
                        command=menu_callback)
parent_widget.config(menu=menu_widget)
Tkinter.mainloop()

OptionMenu Widget

image13.jpg

The OptionMenu widget lets the user choose from a list of options. To use the OptionMenu the right way, you’ll probably need to bind it to a separate callback that updates other information based on the user’s selection. Get the currently selected value with its get method.

import Tkinter
parent_widget = Tkinter.Tk()
control_variable = Tkinter.StringVar(parent_widget)
OPTION_TUPLE = ("Option 1", "Option 2", "Option 3") 
optionmenu_widget = Tkinter.OptionMenu(parent_widget,
                     control_variable, *OPTION_TUPLE)
optionmenu_widget.pack()
Tkinter.mainloop()

About This Article

This article is from the book:

About the book author:

Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.

This article can be found in the category: