(In Python 3)
Timothy Clark
# Ubuntu Linux sudo apt install -y python3 # Mac - open a terminal!
# Windows py main.py # Mac/Linux python3 main.py
def add(a, b): print("{} + {} = {}".format(a, b, a + b)) print("Hello World!") add(2, 6)
Not working? Try repl.it/languages/python3
# Your first program! print("Hello World!")
Comments tell others programmers (and you) what a line of code does
They tell the interpreter to ignore the line(s)
# This is a single line comment # This is another single line comment # print("hello!") ''' This comment is a multi-line comment '''
Computers are very good at Mathematics!
How fast can you calculate:
3 * 4
What about? 3245 * 4657
a = 4 b = 3 a + b # 7 a - b # 1 a * b # 12 a ** b # 64 13 / 2 # 6.5 13 // 2 # 6 16 % b # 1
Python can store a few primitive types of data:
# Integer (int) 34 786 345 # Float (float) 3.14159 2.5 # String (str) "Hello" 'Python 2 is dead' "a" # Booleans (bool) True False True and False True or False not True # Declaration my_variable = 42
You can store values for later use in variables
# Integer (int) 34 786 345 # Float (float) 3.14159 2.5 # String (str) "Hello" 'Python 2 is dead' "a" # Booleans (bool) True False True and False True or False not True
Conditionals (or "if" statements) evaluates a boolean statement, and performs different actions dependent on the result
# if <BOOLEAN>: # do something if True: pass if x > y: print("x is bigger") elif x < 0: print("x and y are negative") else: print("something else")
"for" and "while" statements allow you to repeat a statement multiple times
This allows you to write "DRY" code
for i in range(10): print(i) j = 0 while j < 10: print(j) j += 1
Functions are like putting snippets of code in a box, and dealing with it more abstractly.
They can receive parameters when called/invoked, and they can return values.
def do_something(): print("I did something") print("I did another thing!") def do_nothing(): pass def add(a, b): return a + b def add_and_multiply_by_20(blah, bleh): x = add(blah, bleh) return x * 20 do_something() do_nothing() add(3, 4) add_and_multiply_by_20(43, 26)
Lists (or arrays, as they are called in most programming languages) are data structures that can store any type of data in an ordered, indexed structure
trees = ["Maple", "Birch", "Oak", "Beech"] trees[0] # "Maple" trees[2] # "Oak" print(trees) trees.append("Willow") print(trees) nums = range(1, 10) nums[3] # 4 stuff = ["blah", "blah", 34, 3.14] stuff[1:3] stuff[:3] print(stuff) stuff[1] = "bleh" print(stuff) del stuff[0] stuff.remove(34) print(stuff)
Tuples are like lists, but immutable, meaning you can't modify their contents
Dictionaries are a key-value store that you can use to associate a set of keys to some data
fruits = ("orange", "apple", "banana") fruits[1] = "cherry" # This won't work for fruit in fruits: print(fruit) o, a, b = fruits print(a) my_dict = { "brand": "Apple", "model": "iPhone", "year": 2007 } my_dict["model"] # "iPhone" for key in my_dict: print(key, my_dict[key])
Python allows reuse of code by importing functions from modules, simply just another file.
# main.py import stuff stuff.say_hello("World") stuff.say_hello("Everyone")
main.py
stuff.py
/
# stuff.py def say_hello(thing): print("Hello", thing)
# main.py (alternative) from stuff import say_hello # from stuff import * (imports everything) say_hello("World") say_hello("Everyone")
import random things = ("cherry", "bell", "orange", "pear") # Tuple while True: spin = [things[random.randint(0, 3)] for x in range(3)] print(spin) if spin[0] == spin[1] == spin[2]: print("You Win!") else: print("You lose.") if input("Spin again?"): break print()
How can we represent a Person?
People have names, ages and birthdays!
class Person: def __init__(self, name): self.name = name self.age = 0 def birthday(self): self.age += 1 me = Person("Tim") you = Person("Derek") print(me.name, me.age) print(you.name, you.age) for i in range(21): me.birthday() for i in range(30): you.birthday() you.name = "Steve" print(me.name, me.age) print(you.name, you.age)
class Person: def __init__(self, name): self.name = name self.age = 0 def birthday(self): self.age += 1 def __str__(self): return "Hi, my name is {}, and I'm {} years old".format(self.name, self.age) p1 = Person("Derek") p2 = Person("Steve") for i in range(11): p1.birthday() for i in range(37): p2.birthday() print(p1) print(p2)
class Person: def __init__(self, name): self.name = name self.age = 0 def birthday(self): self.age += 1 def __str__(self): return "Hi, my name is {}, and I'm {} years old".format(self.name, self.age) class Student(Person): def __init__(self, name, subject, year): super().__init__(name) self.degree = subject self.graduation = year def graduate(self, grade): print("Congratulations {}! You graduated {} with a {} in {}".format(self.name, self.degree, grade, self.graduation)) s = Student("Sarah", "Computer Science", 1999) for i in range(19): s.birthday() s.graduate("1.1")