Python: Difference between revisions
Jump to navigation
Jump to search
Line 138: | Line 138: | ||
m['1'] = 'Banana'] | m['1'] = 'Banana'] | ||
print(m['1']) // Banana | print(m['1']) // Banana | ||
</syntaxhighlight> | |||
= Modularity = | |||
== Functions == | |||
These are created as below | |||
<syntaxhighlight lang="python"> | |||
def foo(arg1, arg2) | |||
return arg1 * arg2 | |||
</syntaxhighlight> | |||
== Importing defs == | |||
Best to be selective | |||
<syntaxhighlight lang="python"> | |||
from words import (fetch_words, print_words) | |||
// could be BAD BAD!! | |||
from words import * | |||
</syntaxhighlight> | |||
== Passing arguments == | |||
<syntaxhighlight lang="python"> | |||
import sys | |||
if __name__ == '__main__': | |||
main(sys.argv[1]) | |||
</syntaxhighlight> | |||
== Passing arguments == | |||
<syntaxhighlight lang="python"> | |||
def fetch_words(url): | |||
"""Fetch a list of words from a URL. | |||
Args: | |||
url: The URL of UTF-8 text document. | |||
Return: | |||
A list of strings containing the words from | |||
the document. | |||
""" | |||
story = urlopen(url) | |||
story_words = [] | |||
for line in story: | |||
line_words = line.decode('utf8').split() | |||
for word in line_words: | |||
story_words.append(word) | |||
story.close() | |||
return story_words | |||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 05:56, 15 July 2020
Intro
Python 2 and 3 differences
print "fred" // OK Python 2
print("fred") // Not OK Python 2
Whitespace
Uses full colon and four spaces instead of brackets e.g.
for i in range(5):
x = i * 10
print(x)
Rules
- Prefer four spaces
- Never mix spaces and tabs
- Be consistent on consecutive lines
- Only deviate to improve readability
Help
help(object) gives help. e.g. for the module math
help(math)
Scalar Types, Operators and Control
Types
- int (42)
- float (4.2)
- NoneType (None)
- bool ( True, False) 0 = False !=0 = True
Operators
- == value equality
- != value inequality
- < less-than
- > greater-than
- <= less-than or equal
- >= greater-than or equal
Control
if statementes
if True:
print("Its true")
h = 42
if h > 50:
print("Greater than 50")
elif h < 20:
print("Less than 20")
else:
print("Other")
while loops
while c != 0:
print(c)
c -= 1 // c = c-1
print("Its true")
while True:
response = input()
if int(response) % 7 == 0:
break
for loops
cities = ["London", "Paris", "Berlin"]
for city in cities:
print(city)
Collections and Iterations
str
Double and single quotes are supported. Strings are immutable. Multiline
"""This is
a multiline
string"""
m = "This string\nspans multiple\nlines"
Raw Strings like c# @
path = r'C:\users\merlin\Documents'
bytes
These work like strings, well ascii strings as and can be created like below
b'some bytpes'
print(b[0]) // 115
decoding to bytes
norsk = "some norsk characters"
data = norsk.encode('utf8')
norwegian = data.decode('utf8')
lists
List are a sequence of lists
m = [1,14,5]
// Can be different types
m = ['apple', 7, false]
// Add are mutable
b = []
b.append(1.666)
b.append(1.4444)
print(b) // [1.666, 1.4444]
// Constructor
print(list("characters")) // ['c','h','a','r','a','c','t','e','r','s']
Dict
Dict are value pairs
m = {'1': 'Apple', '2': 'Orange'}
print(m['1']) // Apple
// Replaces
m['1'] = 'Banana']
print(m['1']) // Banana
Modularity
Functions
These are created as below
def foo(arg1, arg2)
return arg1 * arg2
Importing defs
Best to be selective
from words import (fetch_words, print_words)
// could be BAD BAD!!
from words import *
Passing arguments
import sys
if __name__ == '__main__':
main(sys.argv[1])
Passing arguments
def fetch_words(url):
"""Fetch a list of words from a URL.
Args:
url: The URL of UTF-8 text document.
Return:
A list of strings containing the words from
the document.
"""
story = urlopen(url)
story_words = []
for line in story:
line_words = line.decode('utf8').split()
for word in line_words:
story_words.append(word)
story.close()
return story_words