Commit 500294a4 authored by Bstrdsmkr's avatar Bstrdsmkr
Browse files

Basic python code examples

parent 8565948b
from bottle import Bottle, request, run
app = Bottle()
@app.route('/say_hello', method='POST')
def hello():
name = request.forms['name']
return "Hello {}!".format(name)
run(app, host='localhost', port=8080)
list = ['Bob', 'Sue', 'Sally', 'George', 'Karen', 'Mike', 'Carol', 'Matt']
for name in list:
if name is 'Bob':
print 'I found Bob'
elif name is 'Sally' or name is 'Matt':
print 'The managers are here.'
elif name is 'Sue' and 'George' in list:
print "Uhoh... We can't seat them together"
else:
print "{} has arrived".format(name)
Bob = {'Hair': 'Pink', 'Age': 33, 'Height': '6\'1"'}
print Bob['Hair']
print Bob['Age'] * 2
# Print only the keys in the dict
for key in Bob.keys():
print key
# Print only the values in the dict
for value in Bob.values():
print value
# Print each pair using the "unpacking" syntax
for key, value in Bob.items():
print "Bob's {}: {}".format(key, value)
# Dicts create more explicit string templates
template = "Bob is a great guy. He has {Hair} hair, is {Age} years old, and {Height} tall."
print template.format(**Bob)
# Keys can be reassigned
Bob['Hair'] = 'Brown'
with open('/tmp/myfile.txt', 'w') as output_file:
output_file.write('Hello World')
with open('/tmp/myfile.txt', 'r') as input_file:
for line in input_file:
if line.startswith('Hello'):
print line
with open('/tmp/myfile.txt', 'r') as input_file:
content = input_file.read()
print content
######################################################
# File modes
# r = read
# w = write
# r+ = read and write
# b = binary mode
# r+b = read and write in binary mode
######################################################
# Create and execute a funtion that accepts no inputs
def greet_the_world():
print "Hello world!"
greet_the_world()
# Functions can return values
def get_greeting():
return "Hello world!"
greeting = get_greeting()
print greeting
# Functions can require inputs
def greet_someone(who):
print "Hello {}!".format(who)
greet_someone('Bob')
# or inputs can be made optional by specifying default values
def greet_someone(who='coder'):
print "Hello {}!".format(who)
greet_someone()
# You can import an entire library
import bottle
bottle.run()
# or just the parts you need:
from bottle import run, route
run()
list = ['Bob', 'Sue', 'Sally', 'George', 'Karen', 'Mike', 'Carol', 'Matt']
# get an item from the list:
print list[2]
# get the last item in a list:
print list[-1]
# get a chunk of the list:
print list[2:5]
# cherry pick every second item in the list:
print list[:2:]
# Reverse the list
print list[::-1]
# Assignment
list[1] = 'Terry'
# Strings as lists
mac = "The customer's mac address is 9B:B9:9D:48:47:D4"
print mac[-17]
print mac[-17:]
################################################################
# You can't change strings by assigning new characters to slices
# Instead, create the pieces and add them together
################################################################
list = ['Bob', 'Sue', 'Sally', 'George', 'Karen', 'Mike', 'Carol', 'Matt']
# Print each item in the list
for item in list:
print item
# Print the last 3 items in the list
for item in list[-3]:
print item
# Print the 3rd from last character of each item in the list
for item in list:
print item[-3]
# Check each item in the list, print everything but "Bob"
for item in list:
if item is not "Bob":
print item
# While loops are the same syntax
# "Iterator loops" like this one should generally be replaced
# with "for i in range(0, 10):" style for loops
x = 0
while x is not 10:
print "X too small: {}".format(x)
x += 1
# List Comprehensions are an alternate, but more compact syntax for
# "simple loops" that create lists
upper_list = []
for name in list:
upper_list.append(name.upper())
upper_list = [name.upper() for name in list]
print upper_list
# Bring in the requests library
import requests
# Send a 'GET' type request and print the response
r = requests.get('https://www.google.com')
print r.text
# Send data to a url
url = 'https://www.google.com'
payload = {'name': 'Bob', 'Hair': 'Pink'}
r = requests.post(url, data=payload)
# Assignment
a = 1
b = 2
c = 5
# Arithmetic
print a + b # 3
print a - b # -1
print a * b # 2
print a / b # 0.5
#######################################
# If it divides evenly, return 0; otherwise, returns the remainder
print a % b # 1
#######################################
print a ** b # 1
print a // b # 0
# Comparison
print a == b # False
print a != b # True
print a > b # False
print a < b # True
print a >= b # False
print a <= b # True
# Compound Assignment
c += a
print c # c = 6
c -= a
print c # c = 5
# Operators on strings
# Assignment
a = 'aabb'
b = 'bbcc'
# Arithmetic
print a + b # 'aabbbbcc'
print a * 2 # 'aabbaabb'
# Comparison
print a == b # False
print a != b # True
# Compare Alphabetically
print a > b # False
print a < b # True
print a >= b # False
print a <= b # True
# Single and double quotes are interchangable
quote = 'he exclaimed "I am Sir Didymus, and none may pass without my permission."'
print quote
# String formatting allows you to create templates to be filled in later
template = "%s wrote this code in %s"
output = template.format("Bob", "Python")
print output
output = "{} wrote this code in {}".format("Bob", "Python")
print output
# Triple quoted strings (Heredocs in other languages) allow multi-line strings
text_block = '''
Sometimes you want to include Python code in a string without
\e\s\c\a\p\i\n\g everything:
for item in list:
do_stuff_with(item)
"Triple quoted strings" (Heredocs in other languages) let you
do just that.'''
print text_block
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment