Saturday, September 10, 2016

Python basics cheatsheet

Python Basics Cheatsheet




Python is an interpreted language.

Math, numbers and variables 

Mathematical Operators


Besides the usual operators (+, -, * and /), Python has exponent ( ** ) and negation ( - as a prefix to a number ).

Integers and Floats

Integers: 50
Floats: 3.1421

Order of operations

 PEMDAS: Parentheses, Exponent, Multiplication, Division, Addition and Subtraction

Using Variables

 No spaces in the variable name and must start with a character. Python style Pep 8 recommends lowercase words separated by underscore.

Rounding


import math
math.ceil(4.8) // will print 5

Other python libraries



Strings

Create strings

first_name = ‘Aditya’
last_name = ‘Inapurapu’

Concatenate strings

full_name = first_name + ‘ ‘ + last_name

Print strings

// Print one string
print(first_name)

// Print multiple strings one after the other with a space in between
print(first_name, last_name)

Python script

 Example: script.py
first_name = ‘Aditya’
last_name = ‘Inapurapu’
full_name = first_name + ‘ ‘ + last_name
print(first_name)
print(first_name, last_name)

Execute the following shell command to execute the python script:
python script.py

Comments

# is the comment character that makes the entire line in the python script as a comment.

Number to string

year = 1969
sentence = ‘The year was’ + str(year)
// A print statement automatically converts a number to a string
print(‘The year was’, year)

Single quotes in the string

famous_sketch = “Hell’s Grannies”

New line characters and tabs

famous_sketch1 = “\n\tHell’s Grannies”

String is an array of characters


greeting = ‘Hello World!’
#Prints H
print(greeting[0])
#Prints !
print(greeting[11])
#IndexError: string index out of range
print(greeting[12])

Built-in String functions

len()

greeting = ‘Hello World!’
print(len(greeting))

Sliceword = ‘Python’

# Prints ‘tho’
print(word[2:5])

Slice from the beginning of the string

word = ‘Good’
#Print from the beginning of the string to index 2
print(word[0:2])
#Also prints from the beginning of the string to index 2
print(word[:2])

Slice from the middle to the end of the string

word = ‘Good’
#Print from index 2 to the end of the string
print(word[2:])

Halfway index of the string using Integer division

// - is the Integer division operator which divides and always returns a whole number
word1 = ‘Good’
half1 = len(word1)//2
end1 = word1[half1:]
word2 = ‘Evening’
half2 = len(word2)//2
end2 = word2[half2:]
print(end1, end2)




Conditionals

< 
<=
==
>=
> 
!=

if num_knights < 3:
      print(‘Retreat!’)
      print(‘Raise the white flag!’)
else:
      print(‘Truce?’)
print (‘Knights of the Round Table!’)

if num_knights < 3:
      print(‘Retreat!’)
elif num_knights >= 10:
      print(‘Trojan Rabbit’)
else:
      print(‘Truce?’)

Input

day = input(“Enter the day of the week”)
print(‘You entered:’, day)

Convert from string to int

num_knights = int(input(‘Enter the number of knights’))
print(‘You entered: ‘, num_knights)
if num_knights < 3 or day == ‘Monday’:
      print(‘Retreat!’)




Nested if

if enemy == ‘Killer bunny’:
      print(‘Holy Hand Grenade!’)
if num_knights >= 10 and day == ‘Wednesday’
      print(‘Trojan Rabbit!’)
else:
      print(‘Truce?’)

Core data structures

List

# An empty list
empty = []

# A list of numbers
nums = [1, 2, 3, 4]

# A list of strings
words = [‘word1’, ‘word2’, ‘word3’]

# A list of mixed items
anything = [10, ‘hello’, ‘ahoy’, ‘mate’, 123.45]
# Prints 10
print(anything[0])
# Prints ahoy
print(anything[2])
# Prints hello ahoy
print(anything[1:3])

# Append items to the list
anything.append(‘end’)

# Remove item by value
anything.remove(‘hello’)

# Remove item by index
del anything[0]

# Remove items by slice
del anything[1:3]


Dictionaries

Dictionaries are equivalent to maps in Java where the data structure is a heap of key value pairs.
slang = {‘cheerio’: ‘goodbye’, ‘knackered’: ‘tired’, ‘yonks’: ‘ages’}
# Prints goodbye
print(slang[‘cheerio’])

# Empty dictionary
slang = {}

# Add key value pairs or update values
slang[‘knackered’] = ‘tired’
slang[‘smashing’] = ‘terrific’

# Delete items from the dictionary
del slang[‘cheerio’]

# If the key does not exist, a KeyError occurs and stops program execution. Use the get method to avoid this issue. If the key does not exist, ‘None’ will be returned.
result = slang.get(‘bloody’)
# if result exists
if result:
      print(result)
else:
      print(‘Key does not exist’)


Comparing Lists


my_list = [1, 2, 3, 4]
your_list = [4, 3, 2, 1]
his_list = [1, 2, 3, 4]
# Not equals returns false
print(my_list == your_list)
# Equals returns true
print(my_list == his_list)




Comparing Dictionaries

my_dictionary = {1:1, 2:2, 3:3, 4:4}
your_dictionary = {4:4, 3:3, 2:2, 1:1}
# Equals returns true
print(my_dictionary == your_dictionary)

List of lists

menus = [[ ‘Spam n Eggs’, ‘Spam n Jam’, ‘Span n Ham’],
      [‘SLT (Spam-Lettuce-Tomato)’, ‘PB&S (PB&Spam)’],
      [‘Spalad’, ‘Spamghetti’, ‘Spam noodle soup’]]
print(menus[0][1])

Dictionary of lists

menus = {‘Breakfast’: [ ‘Spam n Eggs’, ‘Spam n Jam’, ‘Span n Ham’],
      ‘Lunch’: [‘SLT (Spam-Lettuce-Tomato)’, ‘PB&S (PB&Spam)’],
      ‘Dinner’: [‘Spalad’, ‘Spamghetti’, ‘Spam noodle soup’]}
print(‘Breakfast Menu:\t’, menus[‘Breakfast’])
print(‘Lunch Menu:\t’, menus[‘Lunch’])

Loops

For loop

prices = [2.50, 3.50, 4.50]
# Print all prices using a loop
for price in prices:
      print(‘Price is’, price)
total = 0
for price in prices:
      print(‘Price is’, price)
      total = total + price
      print(‘total is’, total)
average = total/len(prices)
print(‘Average is’, average)

Generate a random number

import random
# Generates a random number from [0.0, 1.0]
r1 = random.random()
print(r1)
# Generates a random choice from a list
r2 = random.choice([1, 2, 3, 4, 5])
print(r2)
# Generates a random number between 1 and 1000
r3 = random.randint(1, 1000)
print(r3)

Simple range function


# Creates a list containing numbers 0 to 9
range(10)

for i in range(10):
      ticket = random.randint(1, 1000)
      print(ticket)

Start, Stop and Step range function


# Creates a list containing numbers ranging from 2005 to 2016 incrementing by 2
for i in range(2005, 2016, 2):
      print(i)
# The above prints 2005, 2007, 2009, 2011, 2013, 2015




More loops

# Append ‘spam’ to each word inside a list.
slang = [‘Knackered’, ‘Pip pip’, ‘Squidgy’, ‘Smashing’]
for word in slang:
      menu.append(word + ‘ Spam)
print(menu)
# Assign prices to each menu item in a dictionary.
menu = [‘Knackered Spam’, ‘Pip pip Spam’, ‘Squidgy Spam’, ‘Smashing Spam’]
menu_price = {}
price = 0.50
for item in menu
      menu_prices[item] = price
      price = price + 1
print(menu_prices)

# Print the keys in the dictionary
for item in menu_prices:
      print(item)

# Print key value pairs
for name, price in menu_prices.items():
      print(name, ‘: $’, price)

# Print without extra spaces
print(name, ‘: $’, price, sep=’’)

# Round/Format to 2 decimal places
print(name, ‘: $’, format(price, ‘.2f’), sep=’’)




While loop

x = 1
while x != 3:
      print(‘x is’, x)
      x = x + 1

orders = []
order = input(“What would like to order? (Q for Quit)”)
while (order.upper() != ‘Q’)
      # Find the order and add it to the list if it exists
found = menu.get(order)
if found:
orders.append(order)
else:
print(“Menu item doesn’t exist”)

# Check if the customer wants to order anything else
order = input(“Anything else? (Q to Quit)”)
print(prders)

Break

while (True)
      if order.upper() == ‘Q’:
           break
      else:
           …

Continue

while (True)
      if order.upper() == ‘Q’:
           break
      if order == ‘Cheeky Spam’:
           print(“Sorry, we’re all out of that!”)
           continue



Functions


Define a function

def average(prices):
      …
return avg

Call a function


numbers = [1, 2, 3, 4, 5]
my_average = average(numbers)
print(my_average)


main()

Good practice to have a function name main.

def average(numbers):
      total = 0
      for num in list:
           total = total + num
      avg = total/len(numbers)
      return avg

def main():
prices = [29, 21, 55, 10]
result = average(prices)
print(result)
main()




Files


Writing files


#Open the file in ‘w’ write mode
sales_log = open(‘spam_orders.txt’, ‘w’)
# If the file does not exist, python will create it for us.
sales_log.write(‘The Spam Van’)
sales_log.write(‘Sales log’)
sales_log.close()

# Append  mode
sales_log = open(‘spam_orders.txt’, ‘a’)

Reading files

# Read and print the entire file
dollar_spam = open(‘dollar_menu.txt’, ‘r’)
print(dollar_spam.read())
dollar_spam.close()

# Read one line at a time
dollar_spam = open(‘dollar_menu.txt’, ‘r’)
print(‘1st line:’, dollar_spam.readline())
print(‘2nd line:’, dollar_spam.readline())
dollar_spam.close()

# Read one line at a time in a loop till end of the file
dollar_spam = open(‘dollar_menu.txt’, ‘r’)
for line in dollar_spam:
        print(line)
dollar_spam.close()

# Read one line at a time into a list
dollar_spam = open(‘dollar_menu.txt’, ‘r’)
dollar_menu = []
for line in dollar_spam:
        dollar_menu.append(line)
print(dollar_menu)
dollar_spam.close()

#Remove the leading and trailing new line character
dollar_spam = open(‘dollar_menu.txt’, ‘r’)
dollar_menu = []
for line in dollar_spam:
        line = line.strip()
        dollar_menu.append(line)
print(dollar_menu)
dollar_spam.close()

Exceptions

Python has 60 plus exceptions.

Try, Except

try:
      file = open(‘sales.txt’, ‘r’)
      print(file.read())
except:
      print(“File doesn’t exist”)

Capture the error as a variable


try:
price = float(price)
print(‘Price =’, price)
except ValueError as err:
      print(err)






Modules


Installing modules


pip install requests

http://go.codeschool.com/pypi - for all available Python packages

JSON to format and share data


first_item = {‘name’: ‘Spam n Eggs’,
           ‘description’: ‘Two eggs with Spam’,
           ‘price’: 2.50}
second_item = {‘name’:’Span n Jam’,
‘description’:’Biscuit with Jam with Spam’,
‘price’: 3.50}
menu_items = [first_item, second_item]
print(menu_items[0][‘name], menu_items[0][‘price’], menu_items[0][‘desc’]

# Get JSON from a http request
import requests

my_request = requests.get(‘http://go.codeschool.com/spamvanmenu’)
menu_list = my_request.json()
print(“Today’s Menu:”)
for item in menu_list:
      print(item[‘name’], item[‘desc’], item[‘price’]




Create your own module



# orders.py
def print_menu(menu):

def get_order(menu):

def total_bill(orders, menu):


# spam_van.py
import orders

def main():
      menu = {‘Cheerio Spam”: 0.50, …}
      orders.print_menu(menu)
      orders = orders.get_order(menu)
      total = orders.bill_total(orders, menu)
      print(‘You ordered:’, order, ‘Total:’ total)
main()