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

Python Reserved Words

The document provides a quick reference to Python syntax including numeric operators, string functions, input/output, loops, modules, classes, and file processing. It includes the syntax for common statements like print, assignment, if/else, and for/while loops as well as built-in functions for math, strings, sequences, and type conversions. Various Python concepts are covered at a high level such as modules, classes, docstrings, and list methods.

Uploaded by

tariq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
237 views

Python Reserved Words

The document provides a quick reference to Python syntax including numeric operators, string functions, input/output, loops, modules, classes, and file processing. It includes the syntax for common statements like print, assignment, if/else, and for/while loops as well as built-in functions for math, strings, sequences, and type conversions. Various Python concepts are covered at a high level such as modules, classes, docstrings, and list methods.

Uploaded by

tariq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Quick Reference Card Numeric Operators String Library Functions

Loosely adopted from John Zelle’s “Python Operator Operation Name Meaning
Programming: An Introduction to Computer + addition capitalize(s) Copy of s with only the
Science”, Franklin, Beedle, 1994. - subtraction 1st character uppercase
* multiplication capwords(s) Copy of s with first
/ division character of each word
Python Reserved Words ** exponentiation uppercase
and del for is raise % integer remainder (modulus) center(s,w) Center s in a field of
assert elif from lambda return abs() absolute value width w
break else global not try count(s,sub) Count the number of
class except if or while times sub occurs in s
continue exec import pass yield Math Library Functions find(s,sub) Find first position
def finally in print Name Returns where sub occurs in s
pi an approximation of pi join(list) Concatenate list of
e an approximation of e strings in one string
print Statement sin(x) sine of x radians ljust(s,w) Left-justify s in a
print <expr> cos(x) cosine of x radians field of width w
print <expr>, <expr>, ..., <expr> tan(x) tangent of x radians lower(s) Copy of s in lowercase
print <expr>, <expr>, ..., <expr>, asin(x) inverse of sine x radians lstrip(s) Copy of s with leading
acos(x) inverse of cosine x radians whitespace removed
Assignment Statement atan(x) inverse of tangent x radians replace(s,old,new) Replace all occurences
<variable> = <expr> log(x) natural log of x of substring old in s
<variable1>, <variable2>, ..., <variableN> degrees(x) converts x radians to degrees with substring new
= <expr1>, <expr2>, ..., <exprN> radians(x) converts x degrees to radians rfind(s,sub) Like find, but returns
log10(x) base 10 log of x the rightmost position
exp(x) exponential of x rjust(s,sub) Right-justify s in a
Input (numeric) ceil(x) smallest integer >= x field of width w
<variable> = input(<prompt>) floor(x) largest integer <= x rstrip(s) Copy of s with trailing
<variable1>, <variable2>, ..., <variableN> sqrt(x) square root of x whitepace removed
= input(<prompt>) split(s,c) Split s into a list of
Common Built-in Functions substrings delimited by
Input (string) Name Returns optional character c
<variable> = raw_input(<prompt>) range(n) list of ints from 0 to n-1 (defaults is space)
range(m,n) list of ints from m to n-1 upper(s) Copy of s in uppercase
Definite Loop (iteration) range(m,n,p) list of ints from m to n-1
for <variable> in <sequence>: counting by p Type Conversion Functions
<body> type(x) Python data type of x Name Returns
int(x) the value of x converted to an float(<expr>) expr as a floating point
while Loop int; x numeric or string value
float(x) the value of x converted to a int(<expr>) expr as an integer
while <condition>:
float; x numeric or string long(<expr>) expr as a long integer value
<body>
round(x) nearest whole value of x str(<expr>) a string representation of
break Statement expr
while True: Sequence Ops (strings and lists) eval(<string>) the numeric value of expr,
... Operator Returns evaluated as an expression
if <condition>: break <seq>+<seq> concatenation of sequences ord(c) ASCII code for character c
... <seq>*n sequence concatenated with chr(i) character corresponding to
itself n times integer ASCII code i
Module Import <seq>[n] item at n (indexing):
import <module_name> n >= 0, 0-based from left Boolean Expressions
from <module_name> import n < 0, 1-based from right Literals: True, False
<name1>, <name2>, ... len(<seq>) number of items in sequence Operators: and, or, not
from <module_name> import * <seq>[m:n] slice from m to n-1; m, n
default to 0, len(<seq>) Preventing Execution on Import
if __name__ == “__main__”:
main()
-1- -2- -3-
String Formatting Relational Operators Class Definition
Symbol Meaning class <class-name>:
Expression syntax <method-definition>
<template-string> % (<value>, ...) < Less than ...
> Greater than • method-definition is a function with a
Specifier syntax
<= Less than or equal to special 1st parameter, self, that
%<width>.<precision><type-char>
refers to the object to which the
• width and precision are optional >= Greater than or equal to
method is being applied
• 0 width => use whatever space needed == Equal to • The constructor method is __init__
• width with leading 0 => pad as needed != Not equal to
with 0 (space is default) Note: These operators return a docStrings
• negative width means left-justify bool value (True or False) A string at the beginning of a module,
(right-justify is default) class, function, or method can be used for
• type-char: i (int), f (float), s if Statement documentation. docStrings are carried along
(string) at runtime and are used for interactive help
if <condition>:
<body> and the PyDoc utility.

File Processing if <condition>: List Methods


Opening and Closing Files <body1> Method Meaning
<filevar> = open(<name>,<mode>) –or- else:
<list>.append(x) add x to end of list
<filevar> = file(<name>,<mode>) <body2>
<list>.sort() sort the list
• mode is ‘r’ead, ‘w’rite, or ‘a’ppend if <condition-1>: <list>.reverse() reverse the list
• add + for updating <body-1> <list>.index(x) return index of first
<filevar>.close() elif <condition-2>: occurrence of x
<body-2> <list>.insert(i,x) insert x into list at i
Reading a File ... <list>.count(x) return count of number
<filevar>.read() else: #optional in elif of x’s in the list
<filevar>.readline() <default-body>
<filevar>.readlines() <list>.remove(x) delete 1st occurrence of
for <variable> in <filevar>: x in the list
<body> Exception Handling <list>.pop(i) delete the ith element
try: and return its value
Writing a File <statements>
<filevar>.write(<string>) except <ExceptionType>, <variable>:
<handler1> ASCII Table (decimal)
except <ExceptionType>, <variable>: 32 SP 48 0 64 @ 80 P 96 ` 112 p
Object Constructor <handler2> 33 ! 49 1 65 A 81 Q 97 a 113 q
<class-name>(<param>, ...) ... 34 “ 50 2 66 B 82 R 98 b 114 r
except:
35 # 51 3 67 C 83 S 99 c 115 s
<default handler>
Object Method Call 36 $ 52 4 68 D 84 T 100 d 116 t
<object>.<method_name>(<param>, ...) Note: <variable> is optional; if present, is 37 % 53 5 69 E 85 U 101 e 117 u
assigned the actual exception object that 38 & 54 6 70 F 86 V 102 f 118 v
Function Definition was raised. 39 ‘ 55 7 71 G 87 W 103 g 119 w
def <name>(<formal-param>, ...) 40 ( 56 8 72 H 88 X 104 h 120 x
Preventing Execution on Import
41 ) 57 9 73 I 89 Y 105 i 121 y
if __name__ == “__main__”:
Function Call main() 42 * 58 : 74 J 90 Z 105 j 122 z
<name>(<formal-param>, ...) 43 + 59 ; 75 K 91 [ 107 k 123 {
Random Library 44 , 60 < 76 L 92 \ 108 l 124 |
Return Statement random() returns a uniformly distributed 45 - 61 = 77 M 93 ] 109 m 125 }
return <expr>, ... pseudorandom value in the range [0,1) 46 . 62 > 78 N 94 ^ 110 n 126 ~
randrange(<params>) returns a uniformly
47 / 63 ? 79 O 95 _ 111 o 127 DEL
Simple Conditions distributed pseudorandom value from
‘\0’ = 0, ‘\t’ = 9, ‘\n’ = 10
<expr> <relational-operator> <expr> range(<params>)

-4- -5- -6-

You might also like