Logicalwebhost Cheatsheet

Linux & Open Source Cheatsheets & Howto's

Skip to: Content | Sidebar | Footer

Python basics

13 January, 2011 (16:23) | python | By: unclecameron

Examples run at the command line after typing “python” then getting the >>> prompt

lists

make a list and then do stuff with the data in it
[codesyntax lang=”python”]
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count(‘x’)
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
[/codesyntax]

loops

list filtering
[codesyntax lang=”python”]
>>> li = [“a”, “mpilgrim”, “foo”, “b”, “c”, “b”, “d”, “d”]
>>> [elem for elem in li if len(elem) > 1]
[‘mpilgrim’, ‘foo’]
>>> [elem for elem in li if elem != “b”]
[‘a’, ‘mpilgrim’, ‘foo’, ‘c’, ‘d’, ‘d’]
>>> [elem for elem in li if li.count(elem) == 1] 3
count lets you know how many times occurs in a list
[‘a’, ‘mpilgrim’, ‘foo’, ‘c’]
[/codesyntax]

functions

you define a thing that you can use later just by referencing it, not retyping it so:
[codesyntax lang=”python”]
>>> def a(b): –> a is the name you’ll use later to reference it, b is the thing that holds the logic you define next
>>> return b*2 –> says you want whatever b is to be multiplied by 2
>>> …
>>> a(3) –> inserts 3 in the logic of your “a” function and then runs the “a” function on it, so should give you:
6
[/codesyntax]

read a file

[codesyntax lang=”python”]
>>>f = open(“/folder/file.txt”, ‘w’) –> opens file for writing
>>>f.read() –> prints out the whole file
>>>f.write(‘whoopeee’)
>>>f.close() –> closes the file
[/codesyntax]

classes

A class is a re-usabe “template” that has some functions in it you can use later as a recipe for applying to data you send to it.
[codesyntax lang=”python”]
>>>>>> class ExampleClass: # creates a class called ExampleClass for use later
… def __init__(self, some_message): # __init__ means the first one, you have to create a 1st one somewhere,
# ignore self (but use it), is where your data gets held during transfer
… self.message = some_message # tells what to do with that you transfer
… print “New ExampleClass instance created, with message:” –> generic dialog output
… print self.message –> print the output of message

>>> first_instance = ExampleClass(“message1”)
New ExampleClass instance created, with message:
message1
>>> second_instance = ExampleClass(“message2”)
New ExampleClass instance created, with message:
message2
[/codesyntax]

Write a comment

You need to login to post comments!