Python programming

Ace your homework & exams now with Quizwiz!

len()

It gets the length of the string that you pass to it then returns that as a number.

variable

A symbol used to represent a quantity that can change.

Functions

They name pieces of code the way variables name strings and numbers. They take arguments the way your scripts take argv. Using 1 and 2 they let you make your own "mini-scripts" or "tiny commands." make a function using def

Print

This cmd prints things on to the screen Must input wither " or ' after the print command or else won't print on screen We put a , (comma) at the end of each print line. This is so print doesn't end the line with a newline character and go to the next line.

raw_input

Used to save an input. Used as: firstName = raw_input ("What is your name: " x = int(raw_input()) which gets the number as a string from raw_input() then converts it to an integer using int(). When you typed raw_input() you were typing the ( and ) characters, which are parenthesis characters. This is similar to when you used them to do a format with extra variables, as in "%s %s" % (x, y). For raw_input you can also put in a prompt to show to a person so he knows what to type. Put a string that you want for the prompt inside the () so that it looks like this: y = raw_input("Name? ") This prompts the user with "Name?" and puts the result into the variable y. This is how you ask someone a question and get the answer. The different has to do with where the user is required to give input. If they give your script inputs on the command line, then you use argv. If you want them to input using the keyboard while the script is running, then use raw_input().

break

def: Stop this loop right now. eg: while True: break

lambda

def: create a short anonymous function eg s = lambda y: y ** y; s(3)

global

def: declare that you want a global variable eg: global x

class

def: define a class eg: class person(object)

def

def: define a function eg: def x(): pass

del

def: delete from dictionary eg: del x[y]

except

def: if an exception do this eg: except ValueError, e: print e

if

def: if condition eg: if: x elif: y else: j

import

def: import a module into this one to use eg: import os

from

def: importing specific part of a module eg: import x from y

is

def: like == to test quality eg: 1 is 1 == true

not

def: logical not eg: not True == False

with

def: with an expression as a variable do eg: with x as y: pass

as

des: Part of the with-as statement eg: with X as Y: pass used to substitute one name with another such as random as rnd

and

des: logical and eg: True and False == False

truncate

empties the file. Watch out if you care about the file.

exists

his returns True if a file exists, based on its name in a string as an argument. It returns False if not

echo

lets you create a text file in cmdline eg echo "lalalalala" > test.txt

Hard coding

means putting some bit of information that should come from the user as a string directly in our source code. That's bad because we want it to load other files later. The solution is to use argv or raw_input to ask the user what file to open instead of "hard coding" the file's name.

open

new command open. Right now, run pydoc open and read the instructions. Notice how like your own scripts and raw_input, it takes a parameter and returns a value you can set to your own variable. You just opened a file. What you get back from open is a file, and it also has commands you can give it.

.seek

the seek function is used to start off from the byte so if file has 30 bytes and you type .seek(9) itll start off from the 9th line"

%r %s %d

they are "formatters." They tell Python to take the variable on the right and put it in to replace the %s, %r, %d with its value Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.

return

to set variables to be a value from a function. we are now doing our own math functions for add, subtract, multiply, and divide. The important thing to notice is the last line where we say return a + b (in add). What this does is the following: Our function is called with two arguments: a and b. We print out what our function is doing, in this case "ADDING." Then we tell Python to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them." Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.

"""

works like a string, but you also can put as many lines of text as you want until you type """ again.

Argument/Parameter

A value or expression passed in a method call.

cat

It's an old command that "con*cat*enates" files together, but mostly it's just an easy way to print a file to the screen. Type man cat to read about it.

argv

argv is short for argument vector and is a variable in the sys module which stores a list of command line arguments passed to a program at run time. This variable holds the arguments you pass to your Python script when you run it.

\

backslash) character encodes difficult-to-type characters into a string. There are various "escape sequences" available for different characters you might want to use: An important escape sequence is to escape a single-quote ' or double-quote ". Imagine you have a string that uses double-quotes and you want to put a double-quote inside the string. If you write "I "understand" joe." then Python will get confused because it will think the " around "understand" actually ends the string. You need a way to tell Python that the " inside the string isn't a real double-quote. \n These two characters put a new line character into the string at that point \t puts a tab when it prints out the text in python \\ Backslash () \' Single-quote (') \" Double-quote (") \a ASCII bell (BEL) \b ASCII backspace (BS) \f ASCII formfeed (FF) \n ASCII linefeed (LF) \N{name} Character named name in the Unicode database (Unicode only) \r ASCII Carriage Return (CR) \t ASCII Horizontal Tab (TAB) \uxxxx Character with 16-bit hex value xxxx (Unicode only) \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only) \v ASCII vertical tab (VT) \ooo Character with octal value ooo \xhh Character with hex value hh forward slash works different than a backwards slash

contiue

def: dont process more of the loop do it again eg: while true: continue

elif

def: else condition eg: if: x; elif: y; else: j

else

def: else condtion eg: if: x; elif: y; else: j

finally

def: exceptions or not' finally do this no matter what eg: finally: pass

return

def: exit the funtion with a retun value eg: def x(): return y

or

def: logical or eg: true or false == True

for

def: loop over a collection of things eg: for x in y: pass

in

def: par of for-loops also a test of x in y eg: for x in y: pass also 1 in [1] == True

yield

def: pause here and return to caller eg: def x(): yield y; x().next()

print

def: print this string eg: print "hello world"

raise

def: raise an exception when things go wrong eg: raise ValueError("no")

exec

def: run as string in python eg: exec 'print "hello"'

pass

def: this block is empty eg: def empty(): pass

try

def: try this block and if exception go to exception eg: try: pass

while

def: while loop eg: while x: pass

python -m pydoc

pulls up the help document for python

+ modifier

so you can do 'w+', 'r+', and 'a+'. This will open the file in both read and write mode, and depending on the character use position the file in different ways.

==

the == (double-equal) tests if two things have the same value.

assert

(v.) To declare or state as truth, maintain or defend, put forward forcefully eg: assert False, "Error!"

close

Closes the file. Like File->Save.. in your editor.

def

First we tell Python we want to make a function using def for "define". On the same line as def we give the function a name. In this case we just called it "print_two" but it could also be "peanuts". It doesn't matter, except that your function should have a short name that says what it does. Then we tell it we want *args (asterisk args) which is a lot like your argv parameter but for functions. This has to go inside () parentheses to work. Then we end this line with a : colon, and start indenting. After the colon all the lines that are indented four spaces will become attached to this name, print_two. Our first indented line is one that unpacks the arguments the same as with your scripts. To demonstrate how it works we print these arguments out, just like we would in a script. To 'run,' 'call,' or 'use' a function all mean the same thing."

%

Modulus - Divides left hand operand by right hand operand and returns remainder eg 100 * 8 % 10 is 2.5 how? 100/8 = 12.5 10 goes into 12.5 once with a remainder 2.5 eg 2 print "Roosters", 100 - 25 * 3 % 4 25 * 3 + 75 4 goes into 75 18 times with a remainder of 3 so the equation turns to be 100 - 3

txt = open(filename)

No, it doesn't. It actually makes something called a "file object." You can think of a file like an old tape drive that you saw on mainframe computers in the 1950s, or even like a DVD player from today. You can move around inside them, and then "read" them, but the DVD player is not the DVD the same way the file object is not the file's contents., opens file assigned to variable 'filename' and assigns file object to variable 'txt'

readline

Reads just one line of a text file.

read

Reads the contents of the file. You can assign the result to a variable.

*args

That tells Python to take all the arguments to the function and then put them in args as a list. It's like argv that you've been using, but for functions. It's not normally used too often unless specifically needed., unpacks an argument list, like argvs for functions (def function(*args), arg1, arg2 = *args

=

The = (single-equal) assigns the value on the right to a variable on the left.

.py

The file format to save python files in

modules

This is how you add features to your script from the Python feature set. Rather than give you all the features at once, Python asks you to say what you plan to use. This keeps your programs small, but it also acts as documentation for other programmers who read your code later ., small program units that you can use together to make a program. Programmers also refer to modules as subroutines, procedures, functions, or methods, import

write('stuff') -

Writes "stuff" to the file.

.

You give a file a command by using the . (dot or period), the name of the command, and parameters. Just like with open and raw_input. The difference is that txt.read() says, "Hey txt! Do your read command with no parameters!"

argument

You know how you type python ex13.py to run the ex13.py file? Well the ex13.py part of the command is called an "argument."

#

a hashtag is used to insert a comment into the python programming without accepting it as code

string

every time you put " (double-quotes) around a piece of text you have been making a string. A string is how you make something that your program might give to a human. You print strings, save strings to files, send strings to web servers, and many other things. A string is usually a bit of text you want to display to someone, or "export" out of the program you are writing. Python knows you want something to be a string when you put either " (double-quotes) or ' (single-quotes) around the text strings may contain the format characters you have discovered so far. You simply put the formatted variables in the string, and then a % (percent) character, followed by the variable. The only catch is that if you want multiple formats in your string to print multiple variables, you need to put them inside ( ) (parenthesis) separated by , (commas).

floating point

having a decimal point within a number In floating point arithmetic, the position of the decimal point does not depend on the relative position of the digits in the numbers (as in fixed point arithmetic), since the two parts of the floating point number determine the absolute value of the number. float(raw_input()) use this in place of int(raw_input()) to get a number with a decimal and more precise equation


Related study sets