Python: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 181: Line 181:
print(a) // Pear
print(a) // Pear
print(b) // Apple
print(b) // Apple
</syntaxhighlight>
== Ranges ==
Range supports arguments stop, start, stop or start, stop, step. e.g.
<syntaxhighlight lang="python">
# 0-5
range(5)
# 10-20
range(10,20)
# 10-20 step 2
range(10,20,2)
</syntaxhighlight>
</syntaxhighlight>



Revision as of 02:05, 16 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)

Data types

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'

Format string

m = "The age of {0} is {1}".format('Jim', 32)
print(m) //  The age of Jim is 32

# Or without numbers
m = "The age of {} is {}".format('Jim', 32)


# f-strings are like c#
value = 3000
m = f"The value is {value}"

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

Tuples

Tuples look like lists but have round brackets.

t = ('Apple', 3.5, False)
# to make a single you need to use the trailing comma or it thinks it is a single type e.g.
t = ('Apple',) 
# to index one with pairs use second index e.g
t = ((220,284),(220,285),(220,284),(220,281))
print(t[0][1])

Unpacking like javascript works and swapping

def minmax(items):
    return min(items), max(items)

lower, upper = minmax([83, 33, 84,32, 85, 31, 86])
print(lower) // 31
print(upper) // 86

a = 'Apple'
b = 'Pear'

a, b = b, a

print(a) // Pear
print(b) // Apple

Ranges

Range supports arguments stop, start, stop or start, stop, step. e.g.

# 0-5
range(5) 

# 10-20
range(10,20)

# 10-20 step 2
range(10,20,2)

Modularity

Functions

General

These are created as below

def foo(arg1, arg2):
    return arg1 * arg2

Defaults

def foo(arg1, arg2=9):
    return arg1 * arg2

Be aware that the def assignment is only run once. Therefore These are created as below

def add_spam(menu=[]):
    menu.append('spam')

add_spam() // ['spam']
add_spam() // ['spam','spam']

Advice is to make default arguments not mutable. i.e. not strings and not ints

def add_spam(menu=None):
    if(menu==None)
       menu = []
    menu.append('spam')
    return menu

add_spam() // ['spam']
add_spam() // ['spam']

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])

Comments

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

Scope of Objects

Types of Scope

  • Local - Inside current function
  • Enclosing - Inside enclosing function
  • Global - At the top level of the module
  • Built-in - In the special builtins module

Overriding Scope

Not using global creates a new count and it shadows the global count.

count = 0

def show_count(): 
    print(count)

def set_count(c)
    global count = c

set_count(5)
show_count()

Objects and Types

Named references to objects

Assigning variables is the same as references. Use id() to prove this.

s = [1,2,3]
r = s
s[0] = 500
print(r)
[500,2,3]
p = [4,5,6]
q = [4,5,6]
print(p == q) // True
print(p is q) // False

Passing Arguments are like references

Passing arguments is like passing references

m = [9,15,24]
def modify(k):
    k.append(39)
    print("k = ", k)

modify(m)
k = [9,15,24, 39]
print(m)
[9,15,24, 39]

Passing Arguments are like references II

Or are they. g is reassigned not mutated

f = [14, 23, 37]
def replace(g):
    g = [17,28, 45]
    print("g = ", g)

replace(f)
g = [17,28, 45]
print(f)
[14,23,37]