0% found this document useful (0 votes)
2 views

Python 2

The document provides a comprehensive overview of Python 2.7 keywords, built-in functions, and operators, along with examples for each. It serves as a cheat sheet for essential programming concepts in Python, including control flow, function definitions, and data manipulation. Additionally, it highlights selected functions from the Python standard library and basic arithmetic operators.

Uploaded by

derekcuevas0909
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python 2

The document provides a comprehensive overview of Python 2.7 keywords, built-in functions, and operators, along with examples for each. It serves as a cheat sheet for essential programming concepts in Python, including control flow, function definitions, and data manipulation. Additionally, it highlights selected functions from the Python standard library and basic arithmetic operators.

Uploaded by

derekcuevas0909
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Python 2.

7 Keyword Subset and Examples


https://www.dummies.com/programming/python/python-2-7-keyword-subset-and-examples/

RELATED BOOK
Python For Kids For Dummies
Add to Cart

By Brendan Scott

Part of Python For Kids For Dummies Cheat Sheet

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

Page 1 of 12
Keywor Summary Example
d

and Logical operator to test whether two things are <conditional expression> and
both True. <conditional expression>
x>2 and x<10

as Assign a file object to a variable. Used with with. with open(<name of file>,<file mode>)
Let your code refer to a module under a different name as <object name>:
(also called an alias). Used with import. 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… “”

Page 2 of 12
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 for <dummy variable name> in
(or other iterable). <sequence>:
for i in range(10):

from Import specific functions from a module without from <module name> import <name of
importing the whole module. function or object>
from random import randint

global Make a variable global in scope. (If a variable is defined global x


in the main section, you can change its value within a
function.)

if Create a condition. If the condition is True, the if <conditional expression>:


associated code block is executed. Otherwise, <code block>
any elif commands are processed. If there are none, or [elif <conditional expression>:
none are satisfied, execute the else block if there is one. <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

Page 3 of 12
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 1 in range(10)


elements of an object.

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 lamda <dummy variables>:
function needs to be passed as an argument to another <expression using dummy variables>
function. times = lambda x, y: x*y
command=lambda x:
self.draw_line(self.control_points)

not Logical negation, used to negate a logical condition. 10 not in range(10)


Don’t use for testing greater than, less than, or equal.

or Logical operator to test whether at least one of two <conditional expression> or


things is True. <conditional expression>
x<2 or x>10

pass Placeholder keyword. Does nothing but stop Python for i in range (10):

Page 4 of 12
complaining that a code block is empty. pass

print Output text to a terminal. print(“Hello World!“)

return Return from the execution of a function. If a value is return <value or expression>
specified, return that value, otherwise return None. return x+2

while Execute a code block while the associated condition while <conditional expression>:
is True. 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 ok_to_continue = False


assigned. 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 x = None


to initialise a variable which will be changed later.
Page 5 of 12
Returned by functions which do not explicitly return a
value.

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__“, if __name__==“__main__“:


_ the code is being used in an import.

dir List attributes of an item. dir(<object name>)

enumerat Iterate through a sequence and number each item. enumerate(‘Hello‘)


e

exit Exit Python (Command Line) interpreter. exit()

float Convert a number into a decimal, usually so that 1/float(2)


division works properly.

getattr Get an attribute of an object by a name. Useful for getattr(<name of object>, <name of
introspection. attribute>)

help Get Python docstring on object. help(<name of object>)

Page 6 of 12
help(getattr)

id Show the location in the computer’s RAM where an id(<name of object>)


object is stored. 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. from future import print_function
Need to import from the future to use it (srsly!) print (‘Hello World!‘)

Page 7 of 12
range Gives numbers between the lower and upper limits range(10)
specified (including the lower, but excluding the upper range(5,10)
limit). A step may be specified. range(1,10,2)

raw_input Get some text as a string from the user, with an optional prompt = ‘What is your guess? ‘
prompt. players_guess = raw_input(prompt)

str Convert an object (usually a number) into a string str(0)


(usually for printing).

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 os.path.exists(<path to file>)


and file paths.

pickle, Save and load objects pickle.load(<file object to load from>), pickle.dump(<object to
cPickle to/from a file. dump>, <file object to save to>)

Page 8 of 12
random Various functions random.choice(<sequence to choose from>), random.randint(<lower
relating to random limit>, <upper limit>), random.shuffle(<name of list to shuffle>)
numbers.

String Stuff relating to strings. string.printable

sys Various functions related sys.exit()


to your computer system.

Time Time-related functions. time.time()

Tkinter User interface widgets Tkinter.ALL


and associated constants. 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>,
Page 9 of 12
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. Add: >>> 1+1


Join two strings together. 2
Join: >>> ‘a‘+‘b‘
‘ab‘

– Minus Subtract a number from another. >>> 1-1


Can’t use for strings. 0

* Times Multiply two numbers. Multiply: >>> 2*2


Make copies of a string. 4
Copy: >>> ‘a‘*2

Page 10 of 12
‘aa‘

/ Divide Divide one number by another. 1/2 # integer division:


Can’t use for strings. Answer will be
rounded down.
1/2.0 # decimal
division
1/float(2) # decimal
division

% Remainder Give the remainder when dividing the left number by >>> 10%3
(Modulo) the right number. 1
Formatting operator for strings.

** Power x**y means raise x to the power of y. >>> 3**2


Can’t use for strings. 9

= Assignment Assign the value on the right to the variable on the >>> a = 1
left.

== Equality Is the left side equal to the right side? Is True if so; >>> 1 == 1
is False otherwise. True
>>> ‘a’ == ‘a’
True

!= Not equal Is the left side not equal to the right side? Is True if >>> 1 != 1
so; is False otherwise. False
>>> 1 != 2
True
>>> ‘a’ != ‘a’
Page 11 of 12
True

> Greater than Is the left side greater than the right side? >>> 2 > 1
>= means greater than or equal to True

< Less than Is the left side less than the right side? >>> 1 < 2
<= means less than or equal to True

& (or And Are both left and right True? >>> True & True
and) Typically used for complex conditions where you True
want to do something if everything is True: >>> True and False
while im_hungry and you_have_food: False
>>> True & (1 == 2)
False

| (or or) Or Is either left or right True? >>> True | False


Typically used for complex conditions where you True
want at least one thing to be True: >>> True or False
while im_bored or youre_bored: True
>>> False | False
False
>>> (1 == 1) | False
True

Page 12 of 12

You might also like