Python General Revision Flashcards
Variable
A CONTAINER that stores data/values as a specific name
ie spam = 5
whitespace
seperates statements
whitespace means right space
comments
to make code easier to follow
# for single line comment
“"”for multi line comments”””
boolean
true or false statements
variables can store booleans
ie: a = true
b = false
Python order of operation
maths PEMDAS
python uses PEMDAS system:
Parentheses ( …) = everything in brackets first
Exponents ** = powers (5 ^ 3 is 5x5x5). written as 5 ** 5 in python
Multiplication
Division
Addition, Subtraction
modulo (Mod)
modulo returns the remainder from a division.
ie. 3%2 will return 1. 2 goes into 3 once with 1 remaining (remember the remaider is the bit modulo is interested in)
String
A string is a data type which is written in “quotation marks” ie “ryan”
It can contain numbers, letters and symbols.
Each character in a string is assigned a number (the index) starting with 0.
String method
lets you perform specific tasks for strings ie:
len() = length of string
str() = turns non-string into string ie. str(2) into “2”
. lower() = makes string all lowercase ie. “Ryan” .lower() into “ryan”
. upper() = makes string all uppercase
Dot Notation
this is strings with dot notation in!
ie “Ryan” .upper() or “Ryan”.lower()
but it could be one of many dot .() commands
String Concatenation
This is combining strings with math operators
ie print “life + of + brian” becomes life of brian
Explicit String Conversion
converts non string to string ie:
print “I have” + str(2) + “coconuts!”
will print
I have 2 coconuts!
String Formatting
printing a variable with a string %s goes in the string % goes after string string1 = "Camelot" string2 = "place" print "let's not go to %s tis a silly %s" % (string1, string2)
3 ways to create string
‘Ryan’
“Ryan”
str(2)
- print a string
2. advanced printing
- print “Hello” Hello
- g = “golf”
h = “hotel”
print “%s, %s” % (g, h)golf hotel
datetime
datetime.now
datetime is a type of data (date and time).
datetime.now prints current date and time
from command
import command
from = data location
import = get data
hot commands and placeholders
in printing datetime context
placeholder = %s hot command = % from datetime import datetime now = datetime.now() print '%s/%s/%s %s:%s:%s' % (now.day, now.month, now.year, now.hour, now.minute, now.second) 08/08/2014 13:56:23
Control Flow
Enables code to make decisions
Control Flow: Comparators
equal to == not equal to != less than < greater than > less than or equal to =
Control Flow: Expressions
expressions are values that can have operations like maths, boolean, if, or, and, not, nor, nand, etc.
18 >= 16
extreme expressions and comparators
(10 + 17) == 3 ** 16
Control Flow: Boolean operators
not and or
not is calulated 1st
and is 2nd
or is last
true or false (3 < 4) and (5 >= 5) this() and not that()
Control Flow: Conditional statements
if elif else OR def chess_game_score (answer): if this_might_be_true(): if (answer) > 5: print "this is true" return "true" elif that_might_be_true(): elif (answer) (3 < 4) and (5 >= 5): print "this is really true" return "false" else: else: print "none of the above" return "neither"
.isalpha
checks strings for non letters
what does a comma do in a print statement of variables? eg variable_1 = "hello" variable 2 = "chris" print variable_1, variable_2
creates a space between variable strings
eg it will print this
hello chris
how do you write a variable with a string of placeholders then set the data type or value of those place holders in the print statement?
chris = “ %r %r %r”
print chris % (“25”, “years”, “old”)
25 years old
what does \n do in front of data types in a string?
\n creates a new line between each data type in a string
eg:
variable_1 = “\nchris\ngareth\njason
print variable_1
chris
gareth
jason
what does using “”” instead of “ at the beginning and end of a string allow you to do?
It allows you to print data on continues lines.
print
“"”do this, do that, do nothing.
do something, do everything
dont do anything at all!”””
do this, do that, do nothing.
do something, do everything
dont do anything at all!
what does the raw_input command do?
enables user to input text
enables program to get data and data types from a user
enable program to use this data in program
enable program to print a string of data to user based on that input
what is pydoc?
pydoc is pythons documentation module which allows programmers to acces help files, generate html pages with doc specifics and find appropriate modules for particular jobs
what is a script?
another name for a .py file type
what is an argument?
another name for a file name
what does an argv function do?
the in built function argument variable calls/runs variables assigned to it that relate to file names and types/formats
from sys import argv
script, input_file = argv
so if i now typed ‘python exp20c.py test.txt’ in command line the code above would run both files. specifically it would run the program on the python file exp20c.py (script) and run it on the file test.txt (input_file)
what are modules?
Features you import to make your python program do more.
also called libraries
open
opens file
how to give files commands
put a . after file or variable name
txt = open(filename)
print txt.read
txt is a variable which opens a file. print txt.read tells program to read that files text and print it.
function and method are other names used for?
a command
what is a command
instruction to program to do something with a file
eg open, print, read
read command reads data in a given file and when combined with the print command will print it ( print txt.read)
Reading and writing files
What do close, read, readline, truncate and write commands do?
close = save and close ("c") read = read data from file ("r") readline = read just one line of data from a file truncate = empties file. delete all dat in file write = write data to file
can be added as an extra parametre
eg target = open(filename, “w”)
this mean open file in write mode (as opposed to read mode)
do you need a truncate command when using a write command?
no, write command will overwrite data in file so no need for truncate (erase file contents) command.
what are packages?
directories (folders)
what are modules?
files You know that a module is a Python file with some functions or variables in it. 2. You then import that file. 3. And then you can access the functions or variables in that module with the '.' (dot) operator. In the case of the module the key is an identifier, and the syntax is .key. In the case of the dictionary, the key is a string and the syntax is [key].Other than that, they are nearly the same thing.
mystuff[‘apple’] # get apple from dict mystuff.apple() # get apple from the module mystuff.tangerine # same thing, it’s just a variable
what are modules?
files, arguments A way to think about a module is that it is a specialized dictionary that can store Python code so you can get to it with the '.' operator. You know that a module is a Python file with some functions or variables in it. 2. You then import that file. 3. And then you can access the functions or variables in that module with the '.' (dot) operator. In the case of the module the key is an identifier, and the syntax is .key. In the case of the dictionary, the key is a string and the syntax is [key].Other than that, they are nearly the same thing.
mystuff[‘apple’] # get apple from dict mystuff.apple() # get apple from the module mystuff.tangerine # same thing, it’s just a variable
why is closing files at end of code important?
close command not only closes file but saves it too.
having lots of open file is not good, there is also a limit to amount of open files at same time.
good practice.
files are also known as
modules, arguments
what does close command do?
closes and saves files
output_file.close
what does exists command do?
looks for a specified file and return True statement if it already exists, and False if it doesnt.
what is os.path?
a location on computer containing modules (files) of useful commands to use in programming.
what 3 things do functions do?
- they are commands/methods that call/run sub-routines!!!
- they take arguments the way scripts take argv
- they use both the above to enable you to make ‘mini scripts’ or ‘tiny commands’.
- names a peice ???of the way variable name strings and numbers
what are definitions? def
- a definition is a keyword that assigns a subroutine with a function or command to a variable.
- it must end its first command line with :
- the def variable can have other variables as parameters that it can call/run. def variable_1(variable_2, variable_3):
the subroutine of a def must be indented so the program knows that any code that is indented is part of that subroutine.
def variable_1(variable_2, variable_3):
print variable_2, variable_3.read()
truth tables for NOT, OR, AND, NOR, NAND
NOT: not false = true, not true = false 0=1 1=0
OR: false or false = false 0 or 0 = 0
NOR: false and false = true 0 or 0 = 1
AND:true and true = true 1 and 1 = 1
NAND: true and true = false 1 and 1 = 0
==
!=
equal to 1 == 1 is true 1 == 0 is false
not equal to 1 != 1 is false 1 != 0 is true
a += 1
a -= 1
a *= 1
a /= 1
a = a + 1 a = a - 1 a = a * 1 a = a / 1
if statements and how they work.
if, elif and else
logic decision that create branches that can:
make decisions themselves
make decision themselves and direct to specified areas of program or to sub routines or other branches (if statements)
nests
if statements within if statements
or branches within branches
what are lists?
containers that store data types in an organised manner
data types in lists are assign values starting at 0 (cardinal)
you can then use these values/numbers to index into a list to find specific data.
you can only use number to index
If you need to maintain order. Remember, this is listed order, not sorted order. Lists do not sort for you.
If you need to access the contents randomly by a number. Remember, this is using cardinal numbers starting at 0.
If you need to go through the contents linearly (first to last). Remember, that’s what for-loops are for.
.append
command that adds something to the end
what are lists?
containers that store data types in an organised manner
data types in lists are assign numeric values starting at 0 (cardinal)
you can only use numbers to index into a list to find and retrieve specific data.
The order you put things in list is the number order for retrieval. Remember, this is listed order, not sorted order. Lists do not sort for you.
you can access contents randomly or specifically anywhere in the list by using numbers
use a for-loop to go through the contents linearly (first to last).
while-loop function
loops through list till an assigned criteria is met
while i < 6:
print “not yet”
what are def, for and while?
def, for and while are keywords that call sub routines
floating point method
approximation of a real number that can support a wider range of values
Basically this is using averages to represent a number
ie:
range for a number (difference between smallest and largest number)
median (the middle number in a range [number need to be put in order first])
mode (the number repeated most often in a range)
mean (the average number in a range)
fixed point method
represents a real data type for a number with fixed digits before and after a decimal point
it is an integer (int)
it always have a parameter/factor attached to it most commonly an exponent or power of 10 or 2
20 ** 2
20 ** 10
base 2
a binary numeric value
think computer maths logic
base 10
a decimal numeric value
think human maths logic
hexadecimal or base 16
counting system commonly used in programming using a 16 digit scale:
hex 0123456789 a b c d e f
dec 0123456789101112 13 14 15
written as ‘0x’ in code
ASCII
english language characters
Unicode
universal code
multi language characters
UTF-8 1 byte = standard ASCII 2 bytes = Arabic, Hebrew and most European scripts 3 bytes = BMP 4 bytes = All Unicode characters
concatenation
joining strings together
“snow” “ball” becomes “snowball”
OOP
Object-oriented programming (OOP) is a programming paradigm that represents the concept of “objects” that have data fields (attributes that describe the object) and associated procedures known as methods.
Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs.[1][2] C++, Objective-C, Smalltalk, Delphi, Java, Javascript, C#, Perl, Python, Ruby and PHP are examples of object-oriented programming languages.
instances
??
data type
numbers, text, booleens etc
class
Classes Are Like Mini-Modules
A class is a way to take a grouping of functions and data and place them inside a container so you can access them with the ‘.’ (dot) operator.
A container for objects, functions , data.
class song(object):
def \_\_init\_\_(self, lyrics):
when assigning an object as a parameter of a class, the first parameter variable of __init__ becomes object. the word self is used as good practice, however it is just a variable and can be called anything you want.
objects
Objects Are Like Mini-Imports
If a class is like a “mini-module,” then there has to be a similar concept to import but for classes. That concept is called “instantiate,” which is just a fancy, obnoxious, overly smart way to say “create.” When you instantiate a class, what you get is called an object.
The way you do this is you call the class like it’s a function, like this: thing = MyStuff() thing.apple() print thing.tangerine
Dictionaries
In python called dicts (hashes in other languages). It maps one data type/item (called keys) to another data type/item (called values). (like in a dictionary maps a word to its definition) In the case of the dictionary, the key is a string and the syntax is [key]. In the case of the module the key is an identifier, and the syntax is .key. Other than that, they are nearly the same thing.
Are a type of data structure like lists.
Unlike lists dicts allow you to index/locate data with anything not just numbers.
It associates one thing with another.
{ } brackets.
Dictionaries allow you to add things to them in other parts of your program.
They also allow you to delete things from them.
They can have numbers as parameters in [ ] that are assigned to them as printable.
mystuff[‘apple’] # get apple from dict mystuff.apple() # get apple from the module mystuff.tangerine # same thing, it’s just a variable
cardinal numbers start at 1 or 0?
0
index
the assignment of numeric values to data.
usually used in lists etc where each bit of data in the its has a number assigned to it. this is assigned in the order data is in the list using cardinal numbering system.
delete items from a list
del stuff[1]
delete items from a dict
del stuff[‘city’]
getting things from classes
thing = MyStuff()
thing.apples()
print thing.tangerine
getting things from modules
mystuff.apples()
print mystuff.tangerine
getting things from dicts
mystuff[‘apples’]
(variable1, variable2 )
variables as parameters
([‘apple’, ‘cheese’, biscuit’ ])
lists as parameters
(“hello silly”, “cheese please”)
strings as parameters
(10, 2)
numbers as parameters