Introduction.

import sys
print(sys.version)
## 2.7.12 (default, Nov 19 2016, 06:48:10) 
## [GCC 5.4.0 20160609]

Hello world

print("Hello world!")
## Hello world!

Hello world with a variable

msg = "Hello world!"
print(msg)
## Hello world!

Concatenation (combining strings)

first_name = 'RL'
last_name = 'Burnside'
full_name = first_name + ' ' + last_name
print(full_name)
## RL Burnside

Lists

# Make a list
bikes = ['trek', 'redline', 'giant']
# Get the first item in a list 
first_bike = bikes[0]
# Looping through a list
for bike in bikes:
    print(bike)
## trek
## redline
## giant
# Adding items to a list
bikes = []
bikes.append('trek')
bikes.append('redline')
bikes.append('giant')
# Making numerical lists
squares = []
for x in range(1, 11):
    squares.append(x**2)
    
print(squares)
## [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# List comprehensions
squares = [x**2 for x in range(1, 11)]
# Slicing a list
finishers = ['sam', 'bob', 'ada', 'bea']
first_two = finishers[:2]
print(first_two)
## ['sam', 'bob']
# Copying a list
bikes = ['trek', 'redline', 'giant']
copy_of_bikes = bikes[:]
print(bikes)
print(copy_of_bikes)
## ['trek', 'redline', 'giant']
## ['trek', 'redline', 'giant']

Tuples

Tuples are similar to lists, but the items in a tuple can’t be modified.

# Making a tuple
dimensions = (1920, 1080)
print(dimensions)
## (1920, 1080)

Conditional logic

# Conditional test with lists
bikes = ['trek', 'redline', 'giant']
if 'trek' in bikes:
    print("trek is in bikes")
if 'surly' not in bikes:
    print("surly is not in bikes")
## trek is in bikes
## surly is not in bikes
# Assigning boolean values
game_active = True
can_edit = False
# A simple if test
age = 21
if age >= 18:
    print("You can vote!")
    
# If-elif-else statements
if age < 4:
    ticket_price = 0
elif age < 18:
    ticket_price = 10
else:
    ticket_price = 15

print("ticket price is ", ticket_price)
## You can vote!
## ('ticket price is ', 15)

Dictionaries.

Dictionaries store connections between pieces of information. Each item in a dictionary is a key-value pair.

alien = {'color': 'green', 'points': 5}
print(alien)
# Accessing a value
print("The alien's color is " + alien['color'])
# Adding a new key-value pair
alien['x_position'] = 0
print(alien)
## {'color': 'green', 'points': 5}
## The alien's color is green
## {'color': 'green', 'points': 5, 'x_position': 0}

Looping through all key-value pairs

fav_numbers = {'eric': 17, 'ever' : 4}
for name, number in fav_numbers.items():
    print(name + ' loves ' + str(number))
    
# Looping through all keys
fav_numbers = {'eric': 17, 'ever': 4}
for name in fav_numbers.keys():
    print(name + ' loves a number')
    
# Looping through all the values
fav_numbers = {'eric': 17, 'ever': 4}
for number in fav_numbers.values():
    print(str(number) + ' is a favorite')
## ever loves 4
## eric loves 17
## ever loves a number
## eric loves a number
## 4 is a favorite
## 17 is a favorite

References.

End