Testing PHP
Yantrajaal-test
Friday, November 15, 2019
Friday, October 27, 2017
Monday, October 9, 2017
BDSP-LPHW39
In [1]:
#Exercises from Learning Python the Hard Way
#https://learnpythonthehardway.org/book/
#modified to work with Python 3 and Jupyter Notebook
In [3]:
#exercise 1
print ("Hello World!")
print ("Hello Again")
print ("I like typing this.")
print ("This is fun.")
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
Hello World! Hello Again I like typing this. This is fun. Yay! Printing. I'd much rather you 'not'. I "said" do not touch this.
In [4]:
# exerxise 2
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print ("I could have code like this.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print ("This will run.")
I could have code like this. This will run.
In [5]:
# exerise 3
print ("I will now count my chickens:")
print ("Hens", 25 + 30 / 6)
print ("Roosters", 100 - 25 * 3 % 4)
print ("Now I will count the eggs:")
print (3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print ("Is it true that 3 + 2 < 5 - 7?")
print (3 + 2 < 5 - 7)
print ("What is 3 + 2?", 3 + 2)
print ("What is 5 - 7?", 5 - 7)
print ("Oh, that's why it's False.")
print ("How about some more.")
print ("Is it greater?", 5 > -2)
print ("Is it greater or equal?", 5 >= -2)
print ("Is it less or equal?", 5 <= -2)
I will now count my chickens: Hens 30.0 Roosters 97 Now I will count the eggs: 6.75 Is it true that 3 + 2 < 5 - 7? False What is 3 + 2? 5 What is 5 - 7? -2 Oh, that's why it's False. How about some more. Is it greater? True Is it greater or equal? True Is it less or equal? False
In [6]:
# exerise 4
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print ("There are", cars, "cars available.")
print ("There are only", drivers, "drivers available.")
print ("There will be", cars_not_driven, "empty cars today.")
print ("We can transport", carpool_capacity, "people today.")
print ("We have", passengers, "to carpool today.")
print ("We need to put about", average_passengers_per_car, "in each car.")
There are 100 cars available. There are only 30 drivers available. There will be 70 empty cars today. We can transport 120.0 people today. We have 90 to carpool today. We need to put about 3.0 in each car.
In [7]:
# exercise 5
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print ("Let's talk about %s." % my_name)
print ("He's %d inches tall." % my_height)
print ("He's %d pounds heavy." % my_weight)
print ("Actually that's not too heavy.")
print ("He's got %s eyes and %s hair." % (my_eyes, my_hair))
print ("His teeth are usually %s depending on the coffee." % my_teeth)
# this line is tricky, try to get it exactly right
print ("If I add %d, %d, and %d I get %d." % (
my_age, my_height, my_weight, my_age + my_height + my_weight))
Let's talk about Zed A. Shaw. He's 74 inches tall. He's 180 pounds heavy. Actually that's not too heavy. He's got Blue eyes and Brown hair. His teeth are usually White depending on the coffee. If I add 35, 74, and 180 I get 289.
In [8]:
#exercise 6
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print (x)
print (y)
print ("I said: %r." % x)
print ("I also said: '%s'." % y)
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print (joke_evaluation % hilarious)
w = "This is the left side of..."
e = "a string with a right side."
print (w + e)
There are 10 types of people. Those who know binary and those who don't. I said: 'There are 10 types of people.'. I also said: 'Those who know binary and those who don't.'. Isn't that joke so funny?! False This is the left side of...a string with a right side.
In [9]:
#exercise 7
print ("Mary had a little lamb.")
print ("Its fleece was white as %s." % 'snow')
print ("And everywhere that Mary went.")
print ("." * 10) # what'd that do?
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
print (end1 + end2 + end3 + end4 + end5 + end6,)
print (end7 + end8 + end9 + end10 + end11 + end12)
Mary had a little lamb. Its fleece was white as snow. And everywhere that Mary went. .......... Cheese Burger
In [10]:
#exercise 8
formatter = "%r %r %r %r"
print (formatter % (1, 2, 3, 4))
print (formatter % ("one", "two", "three", "four"))
print (formatter % (True, False, False, True))
print (formatter % (formatter, formatter, formatter, formatter))
print (formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
))
1 2 3 4 'one' 'two' 'three' 'four' True False False True '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' 'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'
In [2]:
#exercise 9
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print ("Here are the days: ", days)
print ("Here are the months: ", months)
print ("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")
Here are the days: Mon Tue Wed Thu Fri Sat Sun Here are the months: Jan Feb Mar Apr May Jun Jul Aug There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6.
In [1]:
#exercise 10
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print (tabby_cat)
print (persian_cat)
print (backslash_cat)
print (fat_cat)
I'm tabbed in. I'm split on a line. I'm \ a \ cat. I'll do a list: * Cat food * Fishies * Catnip * Grass
In [ ]:
#exercise 11
print ("How old are you?")
age = input()
print ("How tall are you?")
height = input()
print ("How much do you weigh?")
weight = input()
print ("So, you're", age," old,", height," tall and ", weight, "heavy")
print ("Your height again, in numbers")
int_height = int(input())
print ("Your weight again, in numbers")
int_weight = int(input())
print("height =", int_height, "weight = ", int_weight, "junk = ", int_height+int_weight)
How old are you?
In [8]:
#exercise 13
from sys import argv
#script, first, second, third = argv
script, first, second = argv
print ("The script is called:", script)
print ("Your first variable is:", first)
print ("Your second variable is:", second)
#print ("Your third variable is:", third)
# instead, do this to hardcode the parameters that will be passed
script = "Exercise13"
first = "string param1"
second = 34
third = 23.5
print ("The script is called:", script)
print ("Your first variable is:", first)
print ("Your second variable is:", second)
print ("Your third variable is:", third)
The script is called: /home/py3user/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py Your first variable is: -f Your second variable is: /run/user/1003/jupyter/kernel-c540726a-1a75-499f-be25-2c6efcbdd217.json The script is called: Exercise13 Your first variable is: string param1 Your second variable is: 34 Your third variable is: 23.5
In [9]:
#exercise 14
from sys import argv
script = argv # read from the argument
user_name = "pyLover" # username hardcoded
prompt = '> '
print ("Hi", user_name, " I'm the script ", script)
print ("I'd like to ask you a few questions.")
print ("Do you like me ?", user_name )
likes = input(prompt)
print(user_name, "says ", likes)
Hi pyLover I'm the script ['/home/py3user/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py', '-f', '/run/user/1003/jupyter/kernel-c540726a-1a75-499f-be25-2c6efcbdd217.json'] I'd like to ask you a few questions. Do you like me ? pyLover > no pyLover says no
In [12]:
#exercise 15
filename = "sample.txt"
txt = open(filename)
print ("Contents of your file ", filename)
print (txt.read())
print ("Type the filename again:")
file_again = input("file? ")
txt_again = open(file_again)
print (txt_again.read())
Contents of your file sample.txt The king beneath the mountain, The king of carven stone, The lord of silver fountain, Shall come unto his own. Type the filename again: file? sample.txt The king beneath the mountain, The king of carven stone, The lord of silver fountain, Shall come unto his own.
In [15]:
#exercise 16
filename = "junk.txt"
print ("We're going to erase", filename)
print ("If you don't want that, hit CTRL-C (^C).")
print ("If you do want that, hit RETURN.")
input("?")
print ("Opening the file...")
target = open(filename, 'w')
print ("Truncating the file. Goodbye!")
target.truncate()
print ("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print ("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print ("And finally, we close it.")
target.close()
readfile = open(filename)
print ("Contents of your file ", filename)
print (readfile.read())
We're going to erase junk.txt If you don't want that, hit CTRL-C (^C). If you do want that, hit RETURN. ? Opening the file... Truncating the file. Goodbye! Now I'm going to ask you for three lines. line 1: eee line 2: ddd line 3: fff I'm going to write these to the file. And finally, we close it. Contents of your file junk.txt eee ddd fff
In [19]:
#exercise 17
from sys import argv
from os.path import exists
from_file = "sample.txt"
to_file = "copy-sample.txt"
print ("Copying from ", from_file, "to ", to_file)
# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()
print ("The input file is ", len(indata)," bytes long")
print ("Does the output file exist?", exists(to_file))
input("continue ..")
out_file = open(to_file, 'w')
out_file.write(indata)
print ("Alright, all done.")
out_file.close()
in_file.close()
readfile = open(to_file)
print ("Contents of your file ", to_file)
print (readfile.read())
Copying from sample.txt to copy-sample.txt The input file is 111 bytes long Does the output file exist? True continue ..dd Alright, all done. Contents of your file copy-sample.txt The king beneath the mountain, The king of carven stone, The lord of silver fountain, Shall come unto his own.
In [21]:
#exeercise 18
def print_two(*args):
arg1, arg2 = args
print ("arg1: ", arg1, "arg2: ", arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print ("arg1: ", arg1, "arg2: ", arg2)
# this just takes one argument
def print_one(arg1):
print ("arg1: ", arg1)
# this one takes no arguments
def print_none():
print ("I got nothin'.")
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
arg1: Zed arg2: Shaw arg1: Zed arg2: Shaw arg1: First! I got nothin'.
In [25]:
#exercise 19
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print ("You have ",cheese_count, "cheeses!")
print ("You have ", boxes_of_crackers," boxes of crackers")
print ("Man that's enough for a party!")
print ("Get a blanket.\n")
print ("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)
print ("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print ("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
print ("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
We can just give the function numbers directly: You have 20 cheeses! You have 30 boxes of crackers Man that's enough for a party! Get a blanket. OR, we can use variables from our script: You have 10 cheeses! You have 50 boxes of crackers Man that's enough for a party! Get a blanket. We can even do math inside too: You have 30 cheeses! You have 11 boxes of crackers Man that's enough for a party! Get a blanket. And we can combine the two, variables and math: You have 110 cheeses! You have 1050 boxes of crackers Man that's enough for a party! Get a blanket.
In [28]:
#exercise 20
input_file = "sample.txt"
def print_all(f):
print (f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print (line_count, f.readline())
current_file = open(input_file)
print ("First let's print the whole file:\n")
print_all(current_file)
print ("Now let's rewind, kind of like a tape.")
rewind(current_file)
print ("Let's print three lines:\n")
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
First let's print the whole file: The king beneath the mountain, The king of carven stone, The lord of silver fountain, Shall come unto his own. Now let's rewind, kind of like a tape. Let's print three lines: 1 The king beneath the mountain, 2 The king of carven stone, 3 The lord of silver fountain,
In [30]:
#exercise 21
def add(a, b):
print ("ADDING ", a, b)
return a + b
def subtract(a, b):
print ("Subtracting ", a, b)
return a - b
def multiply(a, b):
print ("Multiplying ", a, b)
return a * b
def divide(a, b):
print ("Dividing ", a, b)
return a / b
print ("Let's do some math with just functions!")
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print ("Age: Height: Weight: IQ: " , age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print ("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print ("That becomes: ", what, "Can you do it by hand?")
Let's do some math with just functions! ADDING 30 5 Subtracting 78 4 Multiplying 90 2 Dividing 100 2 Age: Height: Weight: IQ: 35 74 180 50.0 Here is a puzzle. Dividing 50.0 2 Multiplying 180 25.0 Subtracting 74 4500.0 ADDING 35 -4426.0 That becomes: -4391.0 Can you do it by hand?
In [33]:
#exercise 24
print ("Let's practice everything.")
print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print ("--------------")
print (poem)
print ("--------------")
five = 10 - 2 + 3 - 6
print ("This should be five: ",five)
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print ("With a starting point of: ",start_point)
print ("We'd have ",beans," beans,", jars, " jars and ", crates, " crates.")
start_point = start_point / 10
print ("We can also do that this way:")
print ("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))
Let's practice everything. You'd need to know 'bout escapes with \ that do newlines and tabs. -------------- The lovely world with logic so firmly planted cannot discern the needs of love nor comprehend passion from intuition and requires an explanation where there is none. -------------- This should be five: 5 With a starting point of: 10000 We'd have 5000000 beans, 5000.0 jars and 50.0 crates. We can also do that this way: We'd have 500000 beans, 500 jars, and 5 crates.
In [15]:
#exercise 25A
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return (words)
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print (word)
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print (word)
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
# save the contents of this cell as a python file lphw25.py
In [16]:
#exercise 25
import lphw25 # imported from the file lphw25.py created and saved in the previous cell
sentence = "All good things come to those who wait."
words = lphw25.break_words(sentence)
words
sorted_words = lphw25.sort_words(words)
sorted_words
lphw25.print_first_word(words)
lphw25.print_last_word(words)
words
lphw25.print_first_word(sorted_words)
lphw25.print_last_word(sorted_words)
sorted_words
sorted_words = lphw25.sort_sentence(sentence)
sorted_words
lphw25.print_first_and_last(sentence)
lphw25.print_first_and_last_sorted(sentence)
All wait. All who All wait. All who
In [45]:
#exercise 29
people = 20
cats = 30
dogs = 15
if people < cats:
print ("Too many cats! The world is doomed!")
if people > cats:
print ("Not many cats! The world is saved!")
if people < dogs:
print ("The world is drooled on!")
if people > dogs:
print ("The world is dry!")
dogs += 5
if people >= dogs:
print ("People are greater than or equal to dogs.")
if people <= dogs:
print ("People are less than or equal to dogs.")
if people == dogs:
print ("People are dogs.")
Too many cats! The world is doomed! The world is dry! People are greater than or equal to dogs. People are less than or equal to dogs. People are dogs.
In [46]:
#exercise 30
people = 30
cars = 40
trucks = 15
if cars > people:
print ("We should take the cars.")
elif cars < people:
print ("We should not take the cars.")
else:
print ("We can't decide.")
if trucks > cars:
print ("That's too many trucks.")
elif trucks < cars:
print ("Maybe we could take the trucks.")
else:
print ("We still can't decide.")
if people > trucks:
print ("Alright, let's just take the trucks.")
else:
print ("Fine, let's stay home then.")
We should take the cars. Maybe we could take the trucks. Alright, let's just take the trucks.
In [47]:
#exercise 31
print ("You enter a dark room with two doors. Do you go through door #1 or door #2?")
door = input("> ")
if door == "1":
print ("There's a giant bear here eating a cheese cake. What do you do?")
print ("1. Take the cake.")
print ("2. Scream at the bear.")
bear = input("> ")
if bear == "1":
print ("The bear eats your face off. Good job!")
elif bear == "2":
print ("The bear eats your legs off. Good job!")
else:
print ("Well, doing ", bear, " is probably better. Bear runs away.")
elif door == "2":
print ("You stare into the endless abyss at Cthulhu's retina.")
print ("1. Blueberries.")
print ("2. Yellow jacket clothespins.")
print ("3. Understanding revolvers yelling melodies.")
insanity = input("> ")
if insanity == "1" or insanity == "2":
print ("Your body survives powered by a mind of jello. Good job!")
else:
print ("The insanity rots your eyes into a pool of muck. Good job!")
else:
print ("You stumble around and fall on a knife and die. Good job!")
You enter a dark room with two doors. Do you go through door #1 or door #2? > 2 You stare into the endless abyss at Cthulhu's retina. 1. Blueberries. 2. Yellow jacket clothespins. 3. Understanding revolvers yelling melodies. > 3 The insanity rots your eyes into a pool of muck. Good job!
In [48]:
#exercise 32
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print ("This is count %d" % number)
# same as above
for fruit in fruits:
print ("A fruit of type: %s" % fruit)
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print ("I got %r" % i)
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print ("Adding %d to the list." % i)
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print ("Element was: %d" % i)
This is count 1 This is count 2 This is count 3 This is count 4 This is count 5 A fruit of type: apples A fruit of type: oranges A fruit of type: pears A fruit of type: apricots I got 1 I got 'pennies' I got 2 I got 'dimes' I got 3 I got 'quarters' Adding 0 to the list. Adding 1 to the list. Adding 2 to the list. Adding 3 to the list. Adding 4 to the list. Adding 5 to the list. Element was: 0 Element was: 1 Element was: 2 Element was: 3 Element was: 4 Element was: 5
In [49]:
#exercise 33
i = 0
numbers = []
while i < 6:
print ("At the top i is %d" % i)
numbers.append(i)
i = i + 1
print ("Numbers now: ", numbers)
print ("At the bottom i is %d" % i)
print ("The numbers: ")
for num in numbers:
print (num)
At the top i is 0 Numbers now: [0] At the bottom i is 1 At the top i is 1 Numbers now: [0, 1] At the bottom i is 2 At the top i is 2 Numbers now: [0, 1, 2] At the bottom i is 3 At the top i is 3 Numbers now: [0, 1, 2, 3] At the bottom i is 4 At the top i is 4 Numbers now: [0, 1, 2, 3, 4] At the bottom i is 5 At the top i is 5 Numbers now: [0, 1, 2, 3, 4, 5] At the bottom i is 6 The numbers: 0 1 2 3 4 5
In [2]:
#exercise 35
from sys import exit
def gold_room():
print ("This room is full of gold. How much do you take?")
choice = input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print ("Nice, you're not greedy, you win!")
exit(0)
else:
dead("You greedy bastard!")
def bear_room():
print ("There is a bear here.")
print ("The bear has a bunch of honey.")
print ("The fat bear is in front of another door.")
print ("How are you going to move the bear?")
bear_moved = False
while True:
choice = input("> ")
if choice == "take honey":
dead("The bear looks at you then slaps your face off.")
elif choice == "taunt bear" and not bear_moved:
print ("The bear has moved from the door. You can go through it now.")
bear_moved = True
elif choice == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif choice == "open door" and bear_moved:
gold_room()
else:
print ("I got no idea what that means.")
def cthulhu_room():
print ("Here you see the great evil Cthulhu.")
print ("He, it, whatever stares at you and you go insane.")
print ("Do you flee for your life or eat your head?")
choice = input("> ")
if "flee" in choice:
start()
elif "head" in choice:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why):
print (why, "Good job!")
#quit()
exit()
def start():
print ("You are in a dark room.")
print ("There is a door to your right and left.")
print ("Which one do you take?")
choice = input("> ")
if choice == "left":
bear_room()
elif choice == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
You are in a dark room. There is a door to your right and left. Which one do you take? > left There is a bear here. The bear has a bunch of honey. The fat bear is in front of another door. How are you going to move the bear? > taunt bear The bear has moved from the door. You can go through it now. > open door This room is full of gold. How much do you take? > 200 You greedy bastard! Good job!
An exception has occurred, use %tb to see the full traceback.
SystemExit
/home/py3user/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py:2889: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
In [3]:
#exercise 38
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print ("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print ("Adding: ", next_one)
stuff.append(next_one)
print ("There are %d items now." % len(stuff))
print ("There we go: ", stuff)
print ("Let's do some things with stuff.")
print (stuff[1])
print (stuff[-1]) # whoa! fancy
print (stuff.pop())
print (' '.join(stuff)) # what? cool!
print ('#'.join(stuff[3:5])) # super stellar!
Wait there are not 10 things in that list. Let's fix that. Adding: Boy There are 7 items now. Adding: Girl There are 8 items now. Adding: Banana There are 9 items now. Adding: Corn There are 10 items now. There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn'] Let's do some things with stuff. Oranges Corn Corn Apples Oranges Crows Telephone Light Sugar Boy Girl Banana Telephone#Light
In [6]:
#exercise 39
print ("working with lists")
things = ['a', 'b', 'c', 'd']
print (things[1])
things[1] = 'z'
print (things[1])
things
print ("working with dictionary")
stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
print (stuff['name'])
print (stuff['age'])
print (stuff['height'])
stuff['city'] = "San Francisco"
print (stuff['city'])
stuff
working with lists b z working with dictionary Zed 39 74 San Francisco
Out[6]:
{'age': 39, 'city': 'San Francisco', 'height': 74, 'name': 'Zed'}
In [ ]:
Subscribe to:
Posts (Atom)