Difference between revisions of "Python"
Rafahsolis (talk | contribs) |
Rafahsolis (talk | contribs) |
||
| Line 84: | Line 84: | ||
==== Tuple ==== | ==== Tuple ==== | ||
==== Dictionary ==== | ==== Dictionary ==== | ||
| − | Key - Value pairs, | + | Key - Value pairs. They are called diferent in diferent languages:<br /> |
| + | dictionary[key] = value <br /> | ||
| + | |||
| + | * Perl → Associative arrays | ||
| + | * Java → Properties, Map or HashMap | ||
| + | * C# → Property bag | ||
| + | <br /> | ||
| + | Declarationn and assigment:<br /> | ||
| + | There are two posible ways to declare them: | ||
| + | * purse = dict() | ||
| + | * puse = {} | ||
| + | <source lang="python"> | ||
| + | purse = dict() | ||
| + | purse['money'] = 12 | ||
| + | purse['candy'] = 3 | ||
| + | |||
| + | print purse['money'] | ||
| + | </source> | ||
| + | purse = {'money': 12, 'candy' = 3}<br /> | ||
| + | |||
| + | '''get() method:'''<br /> | ||
| + | If you try to retrieve a value for a key that doesn't exist you would get a traceback error.<br /> | ||
| + | To avoid this you should use the get() method, that returns the default value if the key doesn't exist: | ||
| + | purse.get(name, default_value) | ||
| + | '''Other methods and functions'''<br /> | ||
| + | * list(purse) → Returns a list of keys. | ||
| + | * dict.keys() → Returns a list of keys. | ||
| + | * dict.values() → Returns a list of values. | ||
| + | * dict.items → Returns a list of tuples ( [(key, value), (key, value)...] ) | ||
| + | ''' Word count using files and dictionarys'''<br /> | ||
<source lang="python"> | <source lang="python"> | ||
| + | counts = dict() | ||
| + | file_path = raw_input('Enter file name: ') | ||
| + | file_handle = open(file_path, 'r') | ||
| + | text = file_handle.read() | ||
| + | words = text.split() | ||
| + | |||
| + | for word in words: | ||
| + | counts[word] = counts.get(word, 0) + 1 | ||
| + | |||
| + | bigCount = None | ||
| + | bigWord = None | ||
| + | for word, count in counts.items(): | ||
| + | if bigCount is None or count > bigCount: | ||
| + | bigWord = word | ||
| + | bigCount = count | ||
| + | print 'Most frequent word: ', bigWord, '\nFrequency: ', bigCount' | ||
</source> | </source> | ||
Revision as of 08:58, 6 April 2015
Indentation
Python is an indented language, so the code indentation matters. A good practice is to indent with 4 spaces (if you mix spaces and tabs the code won't work.
Operators
Arithmetic
+ Addition - Substraction * Multiplication / Division ** Power % Reminder // Floor division (Reminder is removed)
Comparison
== Equal != Not equal > Greater >= Greater or equal < Smaller <= Smaller or equal <> Similar to !=
Assignment
= Simple assignment += Add and as -= Substract and assignment *= Multiply and assignment /= Divide and assignment %= Modulus and assignment **= Exponent and assignment //= Floor Divisionn and assignment
Bitwise operators
They perform operations on binary terms. a= 8 → 100; b= 9 → 101; a & b → 100
$ Binary AND | Binary OR ^ Binary XOR ~ Binary complement << Binary left shift >> Binary right shift
Logic
and or not
Membership operators
in
not in
Variables
Numbers
String
String assingment:
MyString = 'Hello World' OR MyString = "Hello World"
Strings can be subset sliced:
MyString = "Hello world"
MyString[0:4]
Hel
in operator: to check if a substring is contained in a string
String library:
str.lower()
str.upper()
str.capitalize() → Uppercases 1st char
str.center(width[, fillchar])
str.startswith(preffix[, start[, end]])
str.endswith(suffix[, start[, end]])
str.find(substring[, start[, end]])
str.lstrip([chars])
str.rstrip([chars])
str.strip([chars])
str.replace(old, new[, count])
len(MyString) → returns the lenght of a string
Collections
List
Tuple
Dictionary
Key - Value pairs. They are called diferent in diferent languages:
dictionary[key] = value
- Perl → Associative arrays
- Java → Properties, Map or HashMap
- C# → Property bag
Declarationn and assigment:
There are two posible ways to declare them:
- purse = dict()
- puse = {}
purse = dict()
purse['money'] = 12
purse['candy'] = 3
print purse['money']
purse = {'money': 12, 'candy' = 3}
get() method:
If you try to retrieve a value for a key that doesn't exist you would get a traceback error.
To avoid this you should use the get() method, that returns the default value if the key doesn't exist:
purse.get(name, default_value)
Other methods and functions
- list(purse) → Returns a list of keys.
- dict.keys() → Returns a list of keys.
- dict.values() → Returns a list of values.
- dict.items → Returns a list of tuples ( [(key, value), (key, value)...] )
Word count using files and dictionarys
counts = dict()
file_path = raw_input('Enter file name: ')
file_handle = open(file_path, 'r')
text = file_handle.read()
words = text.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigCount = None
bigWord = None
for word, count in counts.items():
if bigCount is None or count > bigCount:
bigWord = word
bigCount = count
print 'Most frequent word: ', bigWord, '\nFrequency: ', bigCount'
Conditional
if/elif/else
if a < 10:
print "Less than 10"
elif a >= 10 and a < 20:
print "a greater or equal to 10 and less than 20"
else:
print "a greater or equal to 20"
try/except/finally
try:
file = open("test.txt")
except:
print "Could not open file"
finally:
print "This part will be executed at the end whether the open fails or not"
Loops
For
NumberList = [1, 3, 7, 12, 24]
for number in NumberList:
print number
Another way:
for i in range(0, len(NumberList)-1):
print NumberList[i]
while
CtrlNum = 7
while CtrllNum > 3:
print CtrlNum
CtrlNum -= 1
Functions
All arguments in Python are passed by reference, if you change a variable value inside a function it will be changed at the calling function.
def MyFunction(formal_arg, optional_arg = None, *variable_lenght_args):
print formal_arg
if optional_arg:
print optional_arg
for arg in variable_lenght_args:
print arg