Commit 30211312 authored by Phondanai Khanti's avatar Phondanai Khanti
Browse files

Update intro.py, temperature.py, graphics/__init__.py,...

Update intro.py, temperature.py, graphics/__init__.py, graphics/formats/__init__.py, graphics/primitive/__init__.py, book.py files
parent c9e1d209
class Book:
"""Information about a book."""
def __init__(self, title, authors):
""" (Book, str, list_of_str) -> NoneType
Create a new book titled title, with list of author(s)
"""
self.title = title
self.authors = authors
def num_authors(self):
""" (Book) -> int
Return the number of authors of this book.
"""
return len(self.authors)
def __str__(self):
return """Title: {0}
Authors: {1}""".format(self.title, self.authors)
42
42 + 2
42 - 2
42 * 2
42 / 2
42 // 4
42 % 4
3 ** 4
-42
--42
# Assignment
meaning_of_life = 42
degrees_celsius = 24.0
difference = 100 - degrees_celsius
difference
a_string = "This is a string"
a_list = [1, "two", True, {"hello": "world"}]
meaning_of_life = 42
double = meaning_of_life * 2
meaning_of_life = 5.5
# 42 + foo # error
# 1 + # error
# Function
abs(-42)
abs(5.5)
pow(8, 2)
str(abs(-42))
list(str(abs(-42)))
set(str(abs(-42)))
isinstance(set(str(abs(-422))), set)
isinstance(set(str(abs(-422))), list)
pow(abs(-2), round(4.3))
help()
help(abs)
help(dir)
# convert_to_celsius(212)
# convert_to_celsius(78.8)
# convert_to_celsius(10.4)
def convert_to_celsius(fahrenheit):
return ((fahrenheit - 32) * 5) / 9
convert_to_celsius(80)
def quadratic(a, b, c, x):
first = a * x ** 2
second = b * x
third = c
return first + second + third
quadratic(2, 3, 4, 0.5)
# first # NameError
# Working with Text
'slowpoke'
"psyduck"
# "Barry Allen' # SyntaxError
'''This is
multi-line
string'''
"""Me
Too!"""
'This is "slowpoke!"'
"This is 'psyduck!'"
str(3000)
"This is \"PSYDUCK\"".center(20)
len('slowpoke')
len('psyduck')
"psyduck" + " golduck"
len("""Me
Too!""")
#'slowpoke' + 3 # TypeError
'slowpoke' * 3
# Working with File
f = open('/path/to/file')
content = f.read()
f.close()
f = open('/path/to/file', 'w')
f.write("hello world")
f.close()
with open('/path/to/file') as f:
content = f.read()
# Printing Information
print(1+1)
print("Lorem Ipsum")
print("One\nTwo\nThree")
numbers = """One
Two
Three"""
print(numbers)
print()
print(1, 2, 3)
print(1, 2, 3, sep=', ')
pokemon_name = "Slowpoke"
pokedex = 79
print("Pokedex #{1} is {0}".format(pokemon_name, pokedex))
# Get information from te keyboard
species = input()
species
population = input()
population
type(population)
population = int(input())
population += 42
species = input("Please enter a species: ")
print(species)
# Decorators
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
def say_whee():
print("Whee!")
say_whee = my_decorator(say_whee)
say_whee()
@my_decorator
def say_whee():
print("Whee!")
# Boolean operators
not True
not False
True and True
False or False
type(False)
42 > 32
23.1 == 23
42 != 42
# Comparing strings
'A' < 'a'
'A' > 'z'
'abc' < 'abc'
'Jan' in '01 Jan 1870'
'Feb' in '01 Jan 1870'
'a' in 'abc'
'' in 'abc'
'' in ''
# What if
ph = float(input('Enter the pH level: '))
if ph < 7.0:
print(ph, "is acidic.")
ph = float(input('Enter the pH level: '))
if ph < 7.0:
print(ph, "is acidic.")
elif ph > 7.0:
print(ph, "is basic.")
else:
print(ph, "is neutral")
# Nested if
value = input('Enter the pH level: ')
if len(value) > 0:
ph = float(value)
if ph < 7.0:
print(ph, "is acidic.")
elif ph > 7.0:
print(ph, "is basic.")
else:
print(ph, "is neutral.")
else:
print("No pH value was given!")
# A Modular approach to program organization
import this
import math
type(math)
help(math)
#sqrt(9) # NameError
math.sqrt(9)
#math.pi = 3 # No!
print('area is', math.pi * radius ** 2)
help(str)
str.captitalize('slowpoke')
str.count("Ever since my baby went away It's been the blackest day, it's been the blackest day", 'y')
'slowpoke'.captitalize()
"Ever since my baby went away It's been the blackest day, it's been the blackest day".count('y')
# chaining method calls
'Computer Science'.swapcase().endswith('ENCE')
# Defining your own modules
def convert_to_celsius(fahrenheit):
""" (number) -> float
Return the number of Celsius degrees
equivalent to fahrenheit degrees.
>>> convert_to_celsius(75)
23.88888888888889
"""
return (fahrenheit - 32.0) * 5.0 / 9.0
def above_freezing(celsius):
""" (number) -> bool
Return True if temperature celsius degree is
above freezing.
>>> above_freezing(4.2)
True
>>> above_freezing(-2)
False
"""
return celsius > 0
import temperature
temperature.convert_to_celsius(120)
temperature.above_freezing(24)
from temperature import convert_to_celsius, above_freezing
convert_to_celsius(12)
above_freezing(24)
from temperature import convert_to_celsius as f_to_c
f_to_c(120)
# Package of Modules
import graphics.primitive.line
from graphics.formats import jpg
import graphics.formats.jpg as jpg
# Lists
my_list = []
your_list = [3, 4, 5]
my_list.append(1)
my_list.append(2)
my_list.append(4)
my_list.append(3)
my_list.pop()
my_list.append(3)
krypton = ['Krypton', 'Kr', -157.2, -153.4]
krypton[1]
my_list[0]
my_list[-1]
my_list[1:3]
my_list[::2]
my_list[::-1]
# Modifying Lists
nobles = ['helium', 'none', 'argon', 'krypton', 'xenon', 'radon']
nobles[1] = 'neon'
nobles
# Operations on Lists
half_lives = [887.7, 24100.0, 6563.0, 14, 373300.0]
len(half_lives)
max(half_lives)
min(half_lives)
sum(half_lives)
sorted(half_lives)
half_lives
original = ['H', 'He', 'Li']
final = original + ['Be']
final
#['H', 'He', 'Li'] + 'Be'
metals = ['Fe', 'Ni']
metals * 3
del metals[0]
metals
nobles = ['helium', 'neon', 'argon', 'krypton', 'xenon', 'radon']
'xenon' in nobles
gas = input("Enter a gas: ")
if gas in nobles:
print('{} is noble.'.format(gas))
#Slicing Lists
celegans_markers = ["Emb", "Him", "Unc", "Lon", "Dpy", "Sma"]
celegans_markers[0:4]
usefule_makers = celegans_markers[0:4]
celegans_copy = celegans_markers[:]
celegans_markers[::-1]
# List methods
colors = ["red", "orange", "green"]
colors.extend(["black", "blue"])
colors
colors.append("purple")
colors
colors.insert(2, "yellow")
colors
colors.remove("black")
colors
# List of Lists
elements = [["Copper", "Cu"], ["Tellurium", "Te"]]
elements[0]
elements[1]
len(elements)
"You're so " + (elements[0][1] + elements[1][1]).captitalize()
# Storing data using dictionaries
empty_dict = {}
my_dict = {"one": 1, "two": two, "three": 3}
my_dict["one"]
list(my_dict.keys())
list(my_dict.values())
for key, value in my_dict.items():
print(key, value)
my_dict["four"] # KeyError
my_dict.get("four", 4)
# Repeating code using Loops
velocities = [0.0, 9.81, 19.62, 29.43]
for velocity in velocities:
print("Metric:", velocity, "m/sec",
"Imperial:", velocity * 3.28, "ft/sec")
count = 0
while True:
if count != 100:
print(count)
count += 1
else:
break
# Processing characters in String
country = "United Kingdom"
for ch in country:
if ch.isupper():
print(ch)
country = "United States of America"
for ch in country:
if ch.isupper():
print(ch)
# Looping over a range of numbers
range(10)
for num in range(10):
print(num)
list(range(10))
list(range(3))
list(range(0))
list(range(1, 5))
list(range(2000, 2050, 4))
list(range(2050, 2000, -4))
# Processing Lists Using Indices
values = [4, 10, 3, 8, -6]
for num in values:
num = num * 2
values
values = [4, 10, 3, 8, -6]
for i in range(len(values)):
values[i] = values[i] * 2
values
# Nesting loops in loops
outer = ['Li', 'Na', 'K']
inner = ['F', 'Cl', 'Br']
for metal in outer:
for halogen in inner:
print(metal + halogen)
# Controlling Loops using break and continue
s = "C3H7"
digit_index = -1
for i in range(len(s)):
if s[i].isdigit():
digit_index = i
break
s = "C3H7"
total = 0
count = 0
for i in range(len(s)):
if s[i].isalpha():
continue
total = total + int(s[i])
count = count + 1
total
count
# List comprehensions
list(range(20))
[x ** 2 for x in range(20)]
[x for x in range(20) if x % 2 == 0]
# Object-Oriented programming
isinstance('abc', str)
help(object)
type(str)
class Book:
"""Information about a book."""
type(Book)
ruby_book = Book()
ruby_book.title = "Programming Ruby"
ruby_book.authors = ['Thomas', 'Fowler', 'Hunt']
# Writing a Method in Class Book
str.capitalize('slowpoke')
'slowpoke'.capitalize()
class Book:
"""Information about a book."""
def num_authors(self):
""" (Book) -> int
Return the number of authors of this book.
"""
return len(self.authors)
Book.num_authors(ruby_book)
ruby_book.num_authors()
print(ruby_book)
class Book:
"""Information about a book."""
def num_authors(self):
""" (Book) -> int
Return the number of authors of this book.
"""
return len(self.authors)
def __str__(self):
return """Title: {0}
Authors: {1}""".format(self.title, self.authors)
ruby_book = Book()
ruby_book.title = "Programming Ruby"
ruby_book.authors = ['Thomas', 'Fowler', 'Hunt']
print(ruby_book)
import book
ruby_book = book.Book()
ruby_book.title = "Programming Ruby"
ruby_book.authors = ['Thomas', 'Fowler', 'Hunt']
book.Book.num_authors(ruby_book)
ruby_book.num_authors()
isinstance(ruby_book, book.Book())
# __init__
class Book:
"""Information about a book."""
def __init__(self, title, authors):
""" (Book, str, list_of_str) -> NoneType
Create a new book titled title, with list of author(s)
"""
self.title = title
self.authors = authors
def num_authors(self):
""" (Book) -> int
Return the number of authors of this book.
"""
return len(self.authors)
def __str__(self):
return """Title: {0}
Authors: {1}""".format(self.title, self.authors)
scip = Book("Structure and Interpretation of Computer Programs", ["Harold Abelson", "Gerald Jay Susman", "Julie Sussman"])
scip.title
scip.authors
# Inheritance
class Member:
"""A member of university"""
def __init__(self, name, address, email):
"""(Member, str, str, str) -> NoneType
Create a new member named name, with home address and email address.
"""
self.name = name
self.address = address
self.email = email
def hello(self):
print("Hello {}".format(self.name))
class Student(Member):
"""A student member at a university."""
def __init__(self, name, address, email, student_id):
"""(Member, str, str, str, str) -> NoneType
Create a new student named name, with home address and email address,
student ID student_id, an empty list of courses taken, and an
empty list of current courses.
"""
super().__init__(name, address, email)
self.student_id = student_id
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World"
app.run()
# Rendering HTML page
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello():
return render_template("index.html")
def convert_to_celsius(fahrenheit):
""" (number) -> float
Return the number of Celsius degrees
equivalent to fahrenheit degrees.
>>> convert_to_celsius(75)
23.88888888888889
"""
return (fahrenheit - 32.0) * 5.0 / 9.0
def above_freezing(celsius):
""" (number) -> bool
Return True if temperature celsius degree is
above freezing.
>>> above_freezing(4.2)
True
>>> above_freezing(-2)
False
"""
return celsius > 0
Supports Markdown
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