1. Python Syntax
print "Welcome to Python!"
my_int = 7
my_float = 1.23
my_bool = True
my_int = 7
my_int = 3
print my_int
def spam():
eggs = 12
return eggs
print spam()
# just a comment
"""
first comment
second comment
third comment
"""
count_to = 1 + 2
count_to = 5 - 2
ni = 2 * 10
ni = 20 / 4
eggs = 10 ** 2
spam = 3 % 22. Strings and Console Output'Help! Help! I\'m being repressed!'
fifth_letter = "MONTY"[4]
parrot = "Norwegian Blue"
print len(parrot)
print parrot.lower()
print parrot.upper()
pi = 3.14
print str(pi)
print "Spam " + "and " + "eggs"
print "The value of pi is around " + str(3.14)
string_1 = "Camelot"
string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")
print "Ah, so your name is %s, your quest is %s, and your favorite color is %s." % (name, quest, color)3. Conditionals and Control Flow# / and * are evaluated before + and -
bool_one = 17 < 118 % 100
bool_two = 100 == (33 * 3) + 1
bool_three = 19 <= 2**4
bool_four = -22 >= -18
bool_five = 99 != 98 + 1
# not is evaluated first, and is evaluated next, or is evaluated last
"""
True and True is True
False or False is False
Not True is False
Not False is True
"""
answer=7
if 5 <= answer:
print 1
elif answer < 5:
print -1
else:
print 04. Functionsdef square(n):
"""Returns the square of a number."""
squared = n**2
print "%d squared is %d." % (n, squared)
return squared
def favorite_actors(*args):
"""Prints out your favorite actorS (plural!)"""
print "Your favorite actors are:" , args
favorite_actors("Michael Palin", "John Cleese", "Graham Chapman")
def cube(number):
return number**3
def by_three(number):
if number%3 == 0:
return cube(number)
else:
return False
by_three(9)
import math
print math.sqrt(25)
from math import sqrt
print sqrt(25)
from math import *
print sqrt(25)
print max(-10, -5, 5, 10)
print min(-10, -5, 5, 10)
print abs(-10)
print type(42) # => integer
print type(4.2) # => float
print type('spam') # => unicode
print type({'Name':'John Cleese'}) # => dict
print type((1,2)) # => tuple5. Lists and Dictionarieszoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
print zoo_animals[0]
suitcase = []
suitcase.append("sunglasses")
list_length = len(suitcase)
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2]
middle = suitcase[2:4]
last = suitcase[4:6]
animals = "catdogfrog"
cat = animals[:3]
dog = animals[3:6]
frog = animals[6:]
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")
animals.insert(duck_index,"cobra")
my_list = [1,9,3,8,5,7]
for number in my_list:
print number * 2
start_list = [5, 3, 1, 2, 4]
square_list = []
for number in start_list:
square_list.append(number**2)
square_list.sort()
print square_list
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin']
print residents['Sloth']
print residents['Burmese Python']
menu = {}
menu['Chicken Alfredo'] = 14.50
menu['Spam'] = 2.50
print "There are " + str(len(menu)) + " items on the menu."
zoo_animals = { 'Unicorn' : 'Cotton Candy House','Rockhopper Penguin' : 'Arctic Exhibit'}
del zoo_animals['Unicorn']
zoo_animals['Rockhopper Penguin'] = 'Anything other'
beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")6. Lists and Functionsn = [1, 3, 5]
n.pop(0)
n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
print x[i]
print_list(n)
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(x):
r=[]
for i in x:
for j in i:
r.append(j)
return r
print flatten(n)7. Loopswhile count < 10:
print "Hello, I am a while and count is", count
count += 1
choice = raw_input('Enjoying the course? (y/n)')
while choice != 'y' and choice != 'n':
choice = raw_input("Sorry, I didn't catch that. Enter again: ")
from random import randrange
random_number = randrange(1, 10)
count = 0
while count < 3:
guess = int(raw_input("Enter a guess:"))
if guess == random_number:
print 'You win!'
break
count += 1
else:
print 'You lose.'
for i in range(20):
print i
word = "eggs!"
for c in word:
print c
d = {'x': 9, 'y': 10, 'z': 20}
for key in d:
print key,d[key]
choices = ['pizza', 'pasta', 'salad', 'nachos']
for index, item in enumerate(choices):
print index+1, item
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
print max(a,b)
for i in range(1,10):
print i
else:
print i+18. Advanced Topics in Pythonmy_dict = {"Name": "Guido", "Age": 56, "BDFL": True}
print my_dict.items()
print my_dict.keys()
print my_dict.values()
for i in my_dict:
print i, my_dict[i]
even_squares = [i ** 2 for i in range(1,11) if i ** 2 % 2 == 0]
print even_squares
l = [i ** 2 for i in range(1, 11)]
print l[2:9:2]
my_list = range(1, 11)
print my_list[::2]
to_one_hundred = range(101)
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens
languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda l: l == "Python", languages)
squares=[i ** 2 for i in range(1,11)]
print filter(lambda s: 30 <= s <= 70, squares)
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda g: g != "X" , garbled[::])
print message9. Introduction to Bitwise Operatorsprint 5 >> 4 # Right Shift
print 5 << 1 # Left Shift
print 8 & 5 # AND
print 9 | 4 # OR
print 12 ^ 42 # XOR
print ~88 # NOT
print 0b11 * 0b11 # 9
print bin(2) # 0b10
print int("0b11001001", 2) # 201
print bin(0b1110 & 0b101) # 0b100
print bin(0b1110 | 0b101) # 0b1111
print bin(0b1110 ^ 0b101) # 0b1011
def check_bit4(number):
if number & 0b1000 == 0b1000:
return "on"
else:
return "off"
a = 0b11101110
def flip(number):
i = 0
while 2**i-1 < number:
i+=1
return number^2**i-1
print bin(flip(a))10. Introduction to Classesclass ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
def remove_item(self, product):
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + " removed."
else:
print product + " is not in the cart."
my_cart = ShoppingCart("John")
my_cart.add_item("Aquarius",1)
class Employee(object):
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12
def full_time_wage(self, hours):
return super(PartTimeEmployee, self).calculate_wage(hours)
milton = PartTimeEmployee("Milton")
print milton.full_time_wage(10)11. File Input and Outputmy_list = [i**2 for i in range(1,11)]
f = open("output.txt", "w")
for item in my_list:
f.write(str(item) + "\n")
f.close()
f = open("output.txt", "r")
print f.read()
f.close()
f = open("output.txt", "r")
print f.readline()
print f.readline()
f.close()
with open("text.txt", "w") as my_file:
my_file.write("Success!")
print my_file.closed # True
No comments:
Post a Comment