0% found this document useful (0 votes)
19 views

Sol_OOP I(Python+Java) (1)

ertfyguhj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Sol_OOP I(Python+Java) (1)

ertfyguhj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

SOLUTION OF PYTHON II

DRONA FOUNDATION
BVOC - IT
Sr No INDEX
1 Modules in Python
1.1 Modules Python Introduction
1.2 Modules Python Random
Modules Python Namespaces
1.3
1.4 Modules Python Decimals
1.5 Modules Python Files and Scope

2 CREATING DICTIONARIES
2.1 Introduction to Python Dictionaries
2.2 Make a Dictionary
2.3 Invalid Keys
2.4 Empty Dictionary
Add A Key
2.5
2.6 Add Multiple Keys
2.7 Overwrite Values
2.8 Dict Comprehensions
2.9 Review
2 Quiz

3 USING DICTIONARIES
3.2 Get A Key
3.3 Get an Invalid Key
3.4 Safely Get a Key
3.5 Delete a Key
3.6 Get All Keys
3.7 Get All Values
3.8 Get All Items
3.9 Review
1 Project : Scrabble
3 Quiz

4 LEARN PYTHON: FILES


4.1 Reading a File
1
4.2 Iterating Through Lines
4.3 Reading a Line
4.4 Writing a File
4.5 Appending to a File
4.6 What's With "with"?
4.7 What Is a CSV File?
4.8 Reading a CSV File
4.9 Reading Different Types of CSV Files
4.1 Writing a CSV File
4.11 Reading a JSON File
4.3 Writing a JSON File
4 Quiz
11 Project : Hacking The Fender

5 INTRODUCTION TO CLASSES
5.1 Types
5.2 Class
5.3 Instantiation
5.4 Object-Oriented Programming
5.5 Class Variables
5.6 Methods
5.7 Methods with Arguments
5.8 Constructors
5.9 Instance Variables
5.1 Attribute Functions
5.11 Self
5.3 Everything is an Object
5.13 String Representation
5.5 Review
5 Quiz
3 Project : Basta Fazoolin’

JAVA
1 HELLO WORLD
1.2 Hello Java File!
1.3 Print Statements

2
1.4 Commenting Code
1.5 Semicolons and Whitespace
1.6 Compilation: Catching Errors
1.8 Java Review: Putting It All Together
1 Quiz
1 Project : Planting a Tree

2 VARIABLES
2.1 Introduction
2.2 Ints
2.3 Doubles
2.4 Booleans
2.5 Char
2.6 String
2.7 Static Checking
2.8 Naming
2.9 Review
2 Quiz
2 Project : Java Variables : Mad Libs

3 Manipulating Variables
3.1 Introduction
3.2 Addition and Subtraction
3.3 Multiplication and Division
3.4 Modulo
3.5 Compound Assignment Operators
3.6 Order of Operations
3.7 Greater Than and Less Than
3.8 Equals and Not Equals
3.9 Greater/Less Than or Equal To
3.10 .equals()
3.11 String Concatenation
3.12 final Keyword
3.13 Review
3 Quiz
3 Project : Math Magic

3
1. Modules in Python
1.1 Modules Python Introduction Instructions
# Import datetime from datetime below:
from datetime import datetime

current_time = datetime.now()

print(current_time)

1.2 Modules Python Random Instructions

# Import random below:


import random

# Create random_list below:


random_list = [random.randint(1,10) for i in range(11)]

# Create randomer_number below:


randomer_number = random.choice(random_list)

# Print randomer_number below:

4
print(randomer_number)

1.3 Modules Python Namespaces Instructions

import codecademylib3_seaborn

# Add your code below:


from matplotlib import pyplot as plt

import random

numbers_a = range(1, 13)

numbers_b = random.sample(range(100), 3)

plt.plot(numbers_a, numbers_b)

plt.show()

1.4 Modules Python Decimals Instructions

# Import Decimal below:


from decimal import Decimal

5
# Fix the floating point math below:
two_decimal_points = Decimal('0.2') + Decimal('0.69')
print(two_decimal_points)

four_decimal_points = Decimal('0.53') * Decimal('0.65')


print(four_decimal_points)

1.5 Modules Python Files and Scope Instructions

# Import library below:


from library import always_three

# Call your function below:


always_three()

6
2.CREATING DICTIONARIES
2.1 Introduction to Python Dictionaries Instructions

sensors = {"living room": 21, "kitchen": 23, "bedroom": 20, "pantry": 22}
num_cameras = {"backyard": 6, "garage": 2, "driveway": 1}

print(sensors)

2.2 Make a Dictionary Instructions


translations = {"mountain": "orod", "bread": "bass", "friend": "mellon", "horse":
"roch"}

2.3 Invalid Keys Instructions


children = {"von Trapp":["Johannes", "Rosmarie", "Eleonore"] ,
"Corleone":["Sonny", "Fredo", "Michael"]}

2.4 Empty Dictionary Instructions


my_empty_dictionary = {}

2.5 Add A Key Instructions


animals_in_zoo = {}
animals_in_zoo['zebras'] = 8

7
animals_in_zoo['monkeys'] = 3
animals_in_zoo['dinosaurs'] = 0
print(animals_in_zoo)

2.6 Add Multiple Keys Instructions


user_ids = {"teraCoder": 9018293, "proProgrammer": 119238}
user_ids.update({"theLooper": 138475, "stringQueen": 85739})
print(user_ids)

2.7 Overwrite Values Instructions


oscar_winners = {"Best Picture": "La La Land", "Best Actor": "Casey Affleck", "Best
Actress": "Emma Stone", "Animated Feature": "Zootopia"}

oscar_winners["Supporting Actress"] = "Viola Davis"


oscar_winners["Best Picture"] = "Moonlight"

2.8 Dict Comprehensions Instructions


drinks = ["espresso", "chai", "decaf", "drip"]
caffeine = [64, 40, 0, 30]
zipped_drinks = zip(drinks, caffeine)
drinks_to_caffeine = {key: value for key, value in zipped_drinks}

2.9 Review Instructions

8
songs = ["Like a Rolling Stone", "Satisfaction", "Imagine", "What's Going On",
"Respect", "Good Vibrations"]
playcounts = [78, 29, 44, 21, 89, 5]

plays = {song:playcount for [song, playcount] in zip(songs, playcounts)}

plays["Respect"] = 94
plays["Purple Haze"] = 1

library = {"The Best Songs": plays, "Sunday Feelings": {}}

print(library)

__________________________________________
2. Quiz

1. What is the value of inventory after this code is run?


inventory = {"iron spear": 3, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20}

inventory["invisible knife"] = 40
inventory["mithril shield"] = 25
a) {"iron spear": 3, "invisible knife": 70, "needle of ambition": 1, "stone glove":
20, "mithril shield": 25}
b) {"iron spear": 3, "invisible knife": 40, "needle of ambition": 1, "stone
glove": 20, "mithril shield": 25}

9
c) {"iron spear": 3, "invisible knife": 70, "needle of ambition": 1, "stone glove":
20}
d) {"iron spear": 3, "invisible knife": 30, "needle of ambition": 1, "stone glove":
20, "invisible knife": 40, "mithril shield": 25}

2. What is the line of code to initialize an empty dictionary called thesaurus?


a) thesaurus = {}
b) thesaurus = new Dictionary()
c) thesaurus = []
d) thesaurus = empty_dict()

3. Which of these dictionaries has integers as the keys and strings as the values?
a) zipcodes = {"Alabama":35801,"Alaska":99501, "Oregon":97201,
"Vermont":05751, "New Jersey":07039}
b) zipcodes = {35801: "Alabama", "No Value": "N/A", "APO": "Overseas"}
c) zipcodes = {35801: "Alabama", 99501: "Alaska", 97201: "Oregon", 05751:
"Vermont", 07039: "New Jersey"}
d) zipcodes = {35801: ["Huntsville", "Montgomery"], 99501: ["Anchorage"],
97201: ["Portland", "Salem"], 05751: ["Burlington", "Montpelier",
"Rutland"], 07039: ["Hoboken"]}

4. What will the following code output?


conference_rooms = ["executive", "hopper", "lovelace", "pod", "snooze booth"]
capacity = [7, 20, 6, 2, 1]
room_dict = {key:value for key, value in zip(conference_rooms, capacity)}

print(room_dict)

a) {7: "executive", 20: "hopper", 6: "lovelace", 2: "pod", 1: "snooze booth"}

10
b) [("executive", 7), ("hopper", 20), ("lovelace", 6), ("pod", 2), ("snooze
booth", 1)}
c) ["executive", 7, "hopper", 20, "lovelace", 6, "pod", 2, "snooze booth", 1]
d) {"executive": 7, "hopper": 20, "lovelace": 6, "pod": 2, "snooze booth": 1}

5. Which of these is an invalid dictionary (will result in a TypeError when trying to


run)?
a) {["apple", "orange"]: "fruit", ["broccoli"]: "vegetable", ["salt", "paprika",
"saffron"]: "spice"}
b) {2: ["apple", "orange"], 1: ["broccoli"], 3: ["salt", "paprika", "saffron"]}
c) {"fruit": "apple", "vegetable": 10, "spice": ["salt", "paprika", "saffron"]}

11
3.USING DICTIONARIES
3.2 Get A Key Instructions

zodiac_elements = {"water": ["Cancer", "Scorpio", "Pisces"], "fire": ["Aries",


"Leo", "Sagittarius"], "earth": ["Taurus", "Virgo", "Capricorn"], "air":["Gemini",
"Libra", "Aquarius"]}

print(zodiac_elements['earth'])
print(zodiac_elements['fire'])

3.3 Get an Invalid Key Instructions


zodiac_elements = {"water": ["Cancer", "Scorpio", "Pisces"], "fire": ["Aries",
"Leo", "Sagittarius"], "earth": ["Taurus", "Virgo", "Capricorn"], "air":["Gemini",
"Libra", "Aquarius"]}

zodiac_elements["energy"] = "Not a Zodiac element"

if "energy" in zodiac_elements:
print(zodiac_elements["energy"])

3.4 Safely Get a Key Instructions

12
user_ids = {"teraCoder": 10019, "pythonGuy": 182921, "samTheJavaMaam":
3313, "lyleLoop": 3931, "keysmithKeith": 39384}

tc_id = user_ids.get("teraCoder", 10000)


stack_id = user_ids.get("superStackSmash", 10000)

print(tc_id)
print(stack_id)

3.5 Delete a Key Instructions

available_items = {"health potion": 1, "cake of the cure": 5, "green elixir": 20,


"strength sandwich": 25, "stamina grains": 15, "power stew": 30}
health_points = 20

health_points += available_items.pop("stamina grains", 0)


health_points += available_items.pop("power stew", 0)
health_points += available_items.pop("mystic bread", 0)

print(available_items)
print(health_points)

3.6 Get All Keys Instructions


user_ids = {"teraCoder": 10019, "pythonGuy": 182921, "samTheJavaMaam":
3313, "lyleLoop": 3931, "keysmithKeith": 39384}

13
num_exercises = {"functions": 1, "syntax": 13, "control flow": 15, "loops": 22,
"lists": 19, "classes": 18, "dictionaries": 18}

users = user_ids.keys()
lessons = num_exercises.keys()

print(users)
print(lessons)

3.7 Get All Values Instructions


num_exercises = {"functions": 1, "syntax": 13, "control flow": 15, "loops": 22,
"lists": 19, "classes": 18, "dictionaries": 18}

total_exercises = 0

for exercises in num_exercises.values():


total_exercises += exercises
print(total_exercises)

3.8 Get All Items Instructions

pct_women_in_occupation = {"CEO": 28, "Engineering Manager": 9, "Pharmacist":


58, "Physician": 40, "Lawyer": 37, "Aerospace Engineer": 9}

for occupation, percentage in pct_women_in_occupation.items():

14
print("Women make up " + str(percentage) + " percent of " + occupation + "s.")

3.9 Review Instructions

tarot = { 1: "The Magician", 2: "The High Priestess", 3: "The Empress", 4: "The


Emperor", 5: "The Hierophant", 6: "The Lovers", 7: "The Chariot", 8:
"Strength", 9: "The Hermit", 1: "Wheel of Fortune", 11: "Justice", 3:
"The Hanged Man", 13: "Death", 5: "Temperance", 15: "The Devil", 16:
"The Tower", 17: "The Star", 18: "The Moon", 19: "The Sun", 20:
"Judgement", 21: "The World", 22: "The Fool"}

spread = {}

spread["past"] = tarot.pop(13)
spread["present"] = tarot.pop(22)
spread["future"] = tarot.pop(1)

for key, value in spread.items():


print("Your "+key+" is the "+value+" card. ")

__________________________________________
Project-1

Scrabble

15
# Step 1
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 1, 1, 1, 1, 1, 4, 4, 8, 4, 1]

letter_to_points = {letter: point for letter, point in zip(letters, points)}

# Step 2
letter_to_points[" "] = 0

# Step 3-6
def score_word(word):
point_total = 0
for letter in word:
point_total += letter_to_points.get(letter, 0)
return point_total

# Step 7-8
brownie_points = score_word("BROWNIE")
print(brownie_points)

# Step 9
player_to_words = {
"player1": ["wordNerd", "Lexi", "Con", "Prof", "Reader"],
"BLUE": ["EARTH", "ERASER", "ZAP"],
16
"TENNIS": ["EYES", "BELLY", "COMA"],
"EXIT": ["MACHINE", "HUSKY", "PERIOD"]
}

# Step 1
player_to_points = {}

# Step 11-5
for player, words in player_to_words.items():
player_points = 0
for word in words:
player_points += score_word(word)
player_to_points[player] = player_points
print(player_to_points)

__________________________________________
3. Quiz

1. What will the following code output?


combo_meals = {1: ["hamburger", "fries"], 2: ["hamburger", "fries", "soda"], 4:
["veggie burger", "salad", "soda"], 6: ["hot dog", "apple slices", "orange juice"]}
print(combo_meals[3])
a) "fries"
b) ["hot dog", "apple slices", "orange juice"]

17
c) KeyError
d) ["veggie burger", "salad", "soda"]

2. What is the output of the following code?


oscars = {"Best Picture": "Moonlight", "Best Actor": "Casey Affleck", "Best
Actress": "Emma Stone", "Animated Feature": "Zootopia"}

for element in oscars.values():


print(element)
a) "Best Picture" : "Moonlight"
"Best Actor": "Casey Affleck"
"Best Actress": "Emma Stone"
"Animated Feature": "Zootopia"
b) "Best Picture"
"Best Actor"
"Best Actress"
"Animated Feature"
c) ("Best Picture", "Moonlight")
("Best Actor", "Casey Affleck")
("Best Actress", "Emma Stone")
("Animated Feature", "Zootopia")
d) "Moonlight"
"Casey Affleck"
"Emma Stone"
"Zootopia"

3. What will the following code output?


inventory = {"iron spear": 3, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20, "the peacemaker": 65, "demonslayer": 50}
print(inventory.get("stone glove", 30))
a) 20

18
b) 30
c) 1
d) ("stone glove", 20)

4. What is the output of the following code?


raffle = {223842: "Teddy Bear", 872921: "Concert Tickets", 320291: "Gift Basket",
4333: "Necklace", 298787: "Pasta Maker"}

raffle.pop(561721, "No Value")


print(raffle)

a) 'No Value'
b) {223842: 'Teddy Bear', 872921: 'Concert Tickets', 320291: 'Gift Basket',
4333: 'Necklace', 298787: 'Pasta Maker', 561721: 'No Value'}
c) KeyError
d) {223842: 'Teddy Bear', 872921: 'Concert Tickets', 320291: 'Gift Basket',
4333: 'Necklace', 298787: 'Pasta Maker'}

5. What will the following code output?


combo_meals = {1: ["hamburger", "fries"], 2: ["hamburger", "fries", "soda"], 4:
["veggie burger", "salad", "soda"], 6: ["hot dog", "apple slices", "orange juice"]}
print(combo_meals[2])
a) "soda"
b) KeyError
c) ["veggie burger", "salad", "soda"]
d) ["hamburger", "fries", "soda"]

6. What will the following code output?


inventory = {"iron spear": 3, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20, "the peacemaker": 65, "demonslayer": 50}
19
print("the peacemaker" in inventory)
a) KeyError
b) True
c) 65
d) False

7. What does the following code output?


inventory = {"iron spear": 3, "invisible knife": 30, "needle of ambition": 1, "stone
glove": 20, "the peacemaker": 65, "demonslayer": 50}

print(3 in inventory)
a) False
b) True
c) KeyError
d) "iron spear"

8. What is the output of the following code?


oscars = {"Best Picture": "Moonlight", "Best Actor": "Casey Affleck", "Best
Actress": "Emma Stone", "Animated Feature": "Zootopia"}

for element in oscars:


print(element)
a) "Moonlight"
"Casey Affleck"
"Emma Stone"
"Zootopia"
b) "Best Picture" : "Moonlight"
"Best Actor": "Casey Affleck"
"Best Actress": "Emma Stone"
"Animated Feature": "Zootopia"
20
c) ("Best Picture", "Moonlight")
("Best Actor", "Casey Affleck")
("Best Actress", "Emma Stone")
("Animated Feature", "Zootopia")
d) "Best Picture"
"Best Actor"
"Best Actress"
"Animated Feature"

9. What will the following code output?


combo_meals = {1: ["hamburger", "fries"], 2: ["hamburger", "fries", "soda"], 4:
["veggie burger", "salad", "soda"], 6: ["hot dog", "apple slices", "orange juice"]}
print(combo_meals.get(3, ["hamburger", "fries"]))
a) ["hot dog", "apple slices", "orange juice"]
b) ["veggie burger", "salad", "soda"]
c) ["hamburger", "fries"]
d) KeyError

21
4. LEARN PYTHON: FILES
4.1 Reading a File Instructions
with open('welcome.txt') as text_file:
text_data = text_file.read()
print(text_data)

4.2 Iterating Through Lines Instructions


with open('how_many_lines.txt') as lines_doc:
for line in lines_doc.readlines():
print(line)

4.3 Reading a Line Instructions


with open('just_the_first.txt') as first_line_doc:
first_line = first_line_doc.readline()
print(first_line)

4.4 Writing a File Instructions


with open('bad_bands.txt', 'w') as bad_bands_doc:

bad_bands_doc.write('The Beatles')
# Weren't expecting THAT were you??

22
4.5 Appending to a File Instructions
with open('cool_dogs.txt', 'a') as cool_dogs_file:
cool_dogs_file.write('Air Buddy\n')

4.6 What's With "with"? Instructions


with open('fun_file.txt') as close_this_file:

setup = close_this_file.readline()
punchline = close_this_file.readline()

print(setup)

4.7 What Is a CSV File? Instructions


with open('logger.csv') as log_csv_file:
print(log_csv_file.read())

4.8 Reading a CSV File Instructions


import csv

with open('cool_csv.csv') as cool_csv_file:


cool_csv_dict = csv.DictReader(cool_csv_file)
for row in cool_csv_dict:
print(row['Cool Fact'])

23
4.9 Reading Different Types of CSV Files Instructions

import csv

with open('books.csv') as books_csv:


books_reader = csv.DictReader(books_csv, delimiter='@')
isbn_list = [book['ISBN'] for book in books_reader]

4.10 Writing a CSV File Instructions


access_log = [{'time': '08:39:37', 'limit': 844404, 'address': '1.227.34.181'}, {'time':
'13:13:35', 'limit': 543871, 'address': '198.51.139.193'}, {'time': '19:40:45', 'limit':
3021, 'address': '172.1.254.208'}, {'time': '18:57:16', 'limit': 67031769, 'address':
'172.58.247.219'}, {'time': '21:17:13', 'limit': 9083, 'address': '34.54.20.113'},
{'time': '23:34:17', 'limit': 65913, 'address': '203.236.59.220'}, {'time': '13:58:05',
'limit': 154574, 'address': '192.52.206.76'}, {'time': '1:52:00', 'limit': 1565607,
'address': '5.47.59.93'}, {'time': '5:56:3', 'limit': 19, 'address': '192.31.185.7'},
{'time': '18:56:35', 'limit': 6207, 'address': '2.228.164.197'}]
fields = ['time', 'address', 'limit']

import csv

with open('logger.csv', 'w') as logger_csv:


log_writer = csv.DictWriter(logger_csv, fieldnames=fields)
log_writer.writeheader()
for line in access_log:
log_writer.writerow(line)

24
4.11 Reading a JSON File Instructions
import json

with open('message.json') as message_json:


message = json.load(message_json)
print(message['text'])

4.13 Writing a JSON File Instructions


data_payload = [
{'interesting message': 'What is JSON? A web application\'s little pile of secrets.',
'follow up': 'But enough talk!'}
]

import json

with open('data.json', 'w') as data_json:


json.dump(data_payload, data_json)

__________________________________________
4. Quiz

1. What function would you use to render Python data to a JSON file?
a) json.dump()
b) json.writelines()

25
c) json.write()

2. Which of the following opens a file in Python?


a) with open(file.txt) as file_obj:
pass
b) with file_obj = open('file.txt'):
pass
c) with open('file1.txt') as file_obj:
pass

3. What does the with command do in Python?


a) Opens a file in read-mode.
b) Creates a context-manager, which performs cleanup after exiting the
adjacent indented block.
c) Imports a new module for use by the writer of the code.

4. Which of the following methods on a file object (called file_object) reads the
contents of a file and returns it as a string?
a) file_contents = file_object.readlines()
b) file_contents = file_object.readline()
c) file_contents = file_object.read()
d) file_contents = file_object.get()

5. What different modes, passed as arguments to the open() function, are there
for opening a file in Python?
a) Read-mode (‘r’, the default mode), Delete-mode (‘d’), and Update-mode
(‘u’).
b) Read-mode (‘r’, the default mode), Write-mode (‘w’), and Append-mode
(‘a’).

26
c) Read-mode (‘r’, the default mode), Write-mode (‘w’), and Update-mode
(‘u’).

6. What Python data type would you use to read in a CSV file as a dictionary?
a) csv.DictReader
b) json.load
c) csv.DictWriter

7. What method reads a single line from a file object variable called file_object?
a) file_object.read()
b) file_object.readline()
c) file_object.readlines()

__________________________________________
Project-2

Hacking The Fender

import csv
import json

# Step 1
compromised_users = []

# Step 2

27
with open('passwords.csv') as password_file:
password_csv = csv.DictReader(password_file)
# Step 5
for password_row in password_csv:
# Step 6
compromised_users.append(password_row['Username'])
# Step 7
# print(password_row['Username'])

# Step 8
with open('compromised_users.txt', 'w') as compromised_user_file:
# Step 9
for compromised_user in compromised_users:
# Step 1
compromised_user_file.write(compromised_user + "\n")

# Step 3
boss_message_dict = {
"recipient": "The Boss",
"message": "Mission Success"
}

# Step 13
with open('boss_message.json', 'w') as boss_message:

28
# Step 15
json.dump(boss_message_dict, boss_message)

# Step 17
slash_null_sig = '''
_ _ ___ __ ____
/ )( \ / __) / \(_ _)
) \/ ( ( (_ \( O ) )(
\____/ \___/ \__/ (__)
_ _ __ ___ __ _ ____ ____
/ )( \ / _\ / __)( / )( __)( \
) __ (/ \( (__ ) ( ) _) ) D (
\_)(_/\_/\_/ \___)(__\_)(____)(____/
____ __ __ ____ _ _
___ / ___)( ) / _\ / ___)/ )( \
(___) \___ \/ (_/\/ \\___ \) __ (
(____/\____/\_/\_/(____/\_)(_/
__ _ _ _ __ __
( ( \/ )( \( ) ( )
/ /) \/ (/ (_/\/ (_/\
\_)__)\____/\____/\____/
'''

# Step 16

29
with open('new_passwords.csv', 'w') as new_passwords_obj:
# Step 18
new_passwords_obj.write(slash_null_sig)

30
5. INTRODUCTION TO CLASSES

5.1 Types Instructions

print(type(5))

my_dict = {}
print(type(my_dict))

my_list = []
print(type(my_list))

5.2 Class Instructions


class Facade:
pass

5.3 Instantiation Instructions


class Facade:
pass

facade_1 = Facade()

5.4 Object-Oriented Programming Instructions

31
class Facade:
pass

facade_1 = Facade()

facade_1_type = type(facade_1)
print(facade_1_type)

5.5 Class Variables Instructions


class Grade:
minimum_passing = 65

5.6 Methods Instructions


class Rules:
def washing_brushes(self):
return "Point bristles towards the basin while washing your brushes."

5.7 Methods with Arguments Instructions


class Circle:
pi = 3.5

def area(self, radius):


return Circle.pi * radius ** 2

32
circle = Circle()
pizza_area = circle.area(3 / 2)
teaching_table_area = circle.area(36 / 2)
round_room_area = circle.area(1560 / 2)

5.8 Constructors Instructions


class Circle:
pi = 3.5

# Add constructor here:


def __init__(self, diameter):
print('New circle with diameter: {}'.format(diameter))

teaching_table = Circle(36)

5.9 Instance Variables


class Store:
pass

alternative_rocks = Store()
isabelles_ices = Store()

alternative_rocks.store_name = "Alternative Rocks"


isabelles_ices.store_name = "Isabelle's Ices"

33
5.10 Attribute Functions Instructions

can_we_count_it = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]

for element in can_we_count_it:


if hasattr(element, "count"):
print(str(type(element)) + " has the count attribute!")
else:
print(str(type(element)) + " does not have the count attribute :(")

5.11 Self Instructions

class Circle:
pi = 3.5
def __init__(self, diameter):
print("Creating circle with diameter {d}".format(d=diameter))
# Add assignment for self.radius here:

self.radius = diameter / 2

def circumference(self):
return 2 * self.pi * self.radius

medium_pizza = Circle(3)

34
teaching_table = Circle(36)
round_room = Circle(1560)

print(medium_pizza.circumference())
print(teaching_table.circumference())
print(round_room.circumference())

5.12 Everything is an Object Instructions

print(dir(5))

def this_function_is_an_object(num):
return "Cheese is {} times better than everything else".format(num)

print(dir(this_function_is_an_object))

5.13 String Representation Instructions

class Circle:
pi = 3.5

def __init__(self, diameter):


self.radius = diameter / 2

35
def area(self):
return self.pi * self.radius ** 2

def circumference(self):
return self.pi * 2 * self.radius

def __repr__(self):
return "Circle with radius {radius}".format(radius=self.radius)

medium_pizza = Circle(3)
teaching_table = Circle(36)
round_room = Circle(1560)

print(medium_pizza)
print(teaching_table)
print(round_room)

5.14 Review Instructions

class Student:
def __init__(self, name, year):
self.name = name
self.year = year

36
self.grades = []

def add_grade(self, grade):


if type(grade) is Grade:
self.grades.append(grade)

class Grade:
minimum_passing = 65

def __init__(self, score):


self.score = score

roger = Student("Roger van der Weyden", 1)


sandro = Student("Sandro Botticelli", 3)
pieter = Student("Pieter Bruegel the Elder", 8)
pieter.add_grade(Grade(10))

__________________________________________
5. Quiz

1. What would be printed from the following code?


class User:
def __init__(self, name):
self.name = name

37
def __repr__(self):
return "Hiya {}!".format(self.name)

devorah = User("Devorah")
print(devorah)
a) Hiya devorah!
b) devorah
c) Devorah
d) Hiya Devorah!

2. How would we create an instance of the following class?


class NiceClass:
neat_attribute = "neat"
a) nice_instance = NiceClass()
b) nice_instance = NiceClass
c) nice_instance = new NiceClass

3. What does the hasattr() function call in the last line here evaluate to?
class HoldsFive:
five = 5

five_holder = HoldsFive()

hasattr(five_holder, 'five')
a) True
b) False
c) 5

4. Which method, defined within a class, provides instructions on what to assign


to a new instance when it is created?
38
a) __create__
b) __new__
c) __init__
d) init

5. What is the first argument of a method?


a) The class itself. We usually refer to it as self.
b) The context in which the object is created. We usually name the
parameter this.
c) The instance of the object itself. We usually refer to it as self.

6. What does the type() function do in Python?


a) Returns the class that an object implements.
b) Returns an implementation of a class.
c) Returns a type object that contains some metadata about the class.
d) Returns a string that’s the name of the class.

7. What keyword is used to indicate the start of a class definition?


a) type
b) __init__
c) def
d) class

__________________________________________
Project-3

Basta Fazoolin'

39
class Menu:
def __init__(self, name, items, start_time, end_time):
self.name = name
self.items = items
self.start_time = start_time
self.end_time = end_time

def __repr__(self):
return '{} menu available from {} to {}'.format(self.name, self.start_time,
self.end_time)

def calculate_bill(self, purchased_items):


total_price = 0
for item in purchased_items:
if item in self.items:
total_price += self.items[item]
return total_price

brunch_items = {
'pancakes': 7.50,
'waffles': 9.00,
'burger': 11.00,
'home fries': 4.50,
'coffee': 1.50,
'espresso': 3.00,
40
'tea': 1.00,
'mimosa': 1.50,
'orange juice': 3.50
}
brunch = Menu('brunch', brunch_items, '11am', '4pm')

early_bird_items = {
'salumeria plate': 8.00,
'salad and breadsticks (serves 2, no refills)': 5.00,
'pizza with quattro formaggi': 9.00,
'duck ragu': 17.50,
'mushroom ravioli (vegan)': 13.50,
'coffee': 1.50,
'espresso': 3.00,
}
early_bird = Menu('early_bird', early_bird_items, '3pm', '6pm')

dinner_items = {
'crostini with eggplant caponata': 13.00,
'caesar salad': 16.00,
'pizza with quattro formaggi': 11.00,
'duck ragu': 19.50,
'mushroom ravioli (vegan)': 13.50,
'coffee': 2.00,

41
'espresso': 3.00,
}
dinner = Menu('dinner', dinner_items, '5pm', '11pm')

kids_items = {
'chicken nuggets': 6.50,
'fusilli with wild mushrooms': 3.00,
'apple juice': 3.00
}
kids = Menu('kids', kids_items, '11am', '9pm')

print(brunch)
print(brunch.calculate_bill(['pancakes', 'home fries', 'coffee']))
print(early_bird)
print(early_bird.calculate_bill(['salumeria plate', 'mushroom ravioli (vegan)']))

class Franchise:
def __init__(self, address, menus):
self.address = address
self.menus = menus

def __repr__(self):
return 'Address: {}'.format(self.address)

42
def available_menus(self, time):
available_menus = []
for menu in self.menus:
if time >= menu.start_time and time <= menu.end_time:
available_menus.append(menu)
return available_menus
arepas_menu = {
'arepa pabellon': 7.00,
'pernil arepa': 8.50,
'guayanes arepa': 8.00,
'jamon arepa': 7.50
}
arepas_place = Franchise("189 Fitzgerald Avenue", [Menu("Take a' Arepa",
arepas_menu, '1am', '8pm')])
# create flagship_store and new_installment franchises
flagship_store = Franchise("332 West End Road", [brunch, early_bird, dinner,
kids])
new_installment = Franchise("3 East Mulberry Street", [brunch, early_bird,
dinner, kids])

# print out the addresses of the franchises


print(flagship_store)
print(new_installment)

43
# test out the available_menus method
print(flagship_store.available_menus("3pm"))
print(flagship_store.available_menus("5pm"))

class Business:
def __init__(self, name, franchises):
self.name = name
self.franchises = franchises

basta_fazoolin = Business("Basta Fazoolin' with my Heart", [flagship_store,


new_installment, arepas_place])

44
JAVA
1. HELLO WORLD
1.2 Program of Hello Java File! Instructions
public class HelloYou {
public static void main(String[] args) {
System.out.println("Hello Vishva!");
}
}

1.3 Program of Print Statements Instructions


public class HideAndSeek {
public static void main(String[] args) {
System.out.println("Let's play hide and seek.");
System.out.print("Three...");
System.out.print("Two...");
System.out.println("One...");
System.out.println("Ready or not, here I come!");
}
}
1.4 Program of Commenting Code Instructions
public class Timeline {

45
public static void main(String[] args) {
System.out.println("Hello Java!");

System.out.println("You were born in 1995");

// Sun Microsystems announced the release of Java in 1995

System.out.println("You were created by James Gosling");


/*
James Gosling is a Canadian engineer who
created Java while working at Sun Microsystems.
His favorite number is the square root of 2!
*/
System.out.println("You are a fun language!");
}
}
1.5 Program of Semicolons and Whitespace
public class LanguageFacts {
public static void main(String[] args) {
// press enter or return on your keyboard after each semicolon!

System.out.println("Java is a class-based language.");


System.out.println("Java classes have a 'main' method.");
System.out.println("Java statements end with a semicolon.");

46
System.out.println("Programming is... fun!");
}
}
1.6 Program of Compilation: Catching Errors Instructions
public class Compiling {
public static void main(String[] args) {

System.out.println("Java is a class-based language.");


System.out.println("Java classes have a 'main' method.");
System.out.println("Java statements end with a semicolon.");

System.out.println("Programming is... fun!");

}
}
1.8 Program of Java Review: Putting It All Together Instructions
public class Review {
public static void main(String[] args) {
// The main method executes the tasks of the class
System.out.println("My first Java program from scratch!");
}
}

__________________________________________
47
1. Quiz
1. What is missing from this Java program?
public class LanguageFacts {

// Covers the history of the Java programming language

a) The curly braces that mark the scope of the class.


b) The main() method: public static void main(String[] args) {}
c) A single-line comment.
d) The line to compile code: javac LanguageFacts.java
2. What would the name of the file be if it contained the following code?
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
a) HelloWorld.java
b) There are no restrictions on file name in Java.
c) HelloWorld.class
3. The following code will run without an error.
public class LanguageFacts {
public static void main(String[] args) {
System.out.println("Java is a class-based language.");
System.out.println("Java classes have a 'main()' method.");
System.out.println("Java statements end with a semicolon.")
}
}
a) False.
b) True.
48
4. In Java, what is the purpose of leaving comments in code?
a) They provide human readable notes that clarify thinking.
b) They are how words are printed to the screen.
c) They provide checks that the compiler must pass.
d) They are only present in compiled code.
5. Java is a compiled language, meaning the code we write is translated by
another program into a language the computer understands.
a) True.
b) False.
6. What will the following code print to the screen?
public class HelloYou {
public static void main(String[] args) {
System.out.println("Hello Codey!");
}
}
a) This code contains an error.
b) “Hello Codey!”
c) Hello Codey!
7. Comment the code with the correct syntax.
public class Timeline {
public static void main(String[] args) {

____Sun Microsystems announced the release of Java in 1995

______
James Gosling is a Canadian engineer who created Java while
working at Sun Microsystems. His favorite number is the
square root of 2!
______

49
}
}
• //
• \*\
• */*
• /*
• \\
• */
Click or drag and drop to fill in the blank
ANS:
public class Timeline {
public static void main(String[] args) {

// Sun Microsystems announced the release of Java in 1995

/*
James Gosling is a Canadian engineer who created Java while
working at Sun Microsystems. His favorite number is the
square root of 2!
*/

}
}
__________________________________________
Project-1
Planting a Tree
// Define your tree class in this file!
50
public class Tree
{
public static void main(String args[])
{
//tree
System.out.println("I will be printed to the screen");
System.out.println(" * ");
System.out.println(" *** ");
System.out.println(" *** ");
System.out.println(" * ");
System.out.println(" * ");

}
}

OUTPUT
I will be printed to the screen
*
***
***
*
*

51
2. VARIABLES
2.1 Program of Introduction Instructions
public class Creator {
public static void main(String[] args) {
String name = "James Gosling";
int yearCreated = 1995;

System.out.println(name);
System.out.println(yearCreated);
}
}
2.2 Program of ints Instructions
//This is the class declaration:
public class CountComment {
//This is the main method that runs when you compile:
public static void main(String[] args) {
//This is where you will define your variable:
int numComments = 6;
//This is where you will print your variable:
System.out.println(numComments);
}
52
//This is the end of the class:
}

//This is outside the class


2.3 Program of doubles Instructions
public class MarketShare {
public static void main(String[] args) {
double androidShare = 81.7;
System.out.println(androidShare);
}
}
2.4 Program of booleans Instructions
public class Booleans {
public static void main(String[] args) {
boolean intsCanHoldDecimals = false;
System.out.println(intsCanHoldDecimals);
}
}
2.5 Program of char Instructions
public class Char {
public static void main(String[] args) {
char expectedGrade = 'A';
System.out.println(expectedGrade);

53
}
}
2.6 Program of String Instructions
public class Song {
public static void main(String[] args) {
String openingLyrics = "Yesterday, all my troubles seemed so far
away";

System.out.println(openingLyrics);

}
}
2.7 Program of Static Checking Instructions
public class Mess {
public static void main(String[] args) {
int year = 2001;
String title = "Shrek";
char genre = 'C';
double runtime = 1.58;
boolean isPG = true;
}
}
2.8 Program of Naming Instructions
public class BadNames {
public static void main(String[] args) {
54
String firstName = "Samira";
String lastName = "Smith";
String email = "[email protected]";
int salaryExpectation = 100000;
int yearOfBirth = 1955;

System.out.println("The program runs!");


}
}
2.9 Program of Review Instructions
public class MyProfile {
public static void main(String[] args) {
String name = "Laura";
int age = 25;
double desiredSalary = 80000.00;
char gender = 'f';
boolean lookingForJob = true;
}
}

__________________________________________
2. Quiz
1. What line of code declares a variable called numRabbits to store a whole
number?
a) numRabbits int;
b) number numRabbits;
55
c) int numRabbits;
d) numRabbits = int;
2. Which one of the following values is a valid char?
a) “a”
b) ‘ab’
c) 7
d) ‘F’
3. Which option is a valid variable name and follows the Java naming
conventions?
a) TimeUntilLaunch
b) 2ndPhoneNumber
c) second_phone_number
d) timeUntilLaunch
4. What value CANNOT be assigned to a variable with the datatype double.
a) 6.7
b) 5
c) -.2
d) “60”
5. Which of the following lines would throw a compilation error?
a) int balance = -30;
b) double isRaining = false;
c) String gradeOnTest = "A";
d) char grade_on_test = 'F';
6. Which line declares the variable bestProgrammingLanguage and initializes it to
be "Java"?
a) String bestProgrammingLanguage = "Java";
b) bestProgrammingLanguage = String "Java";
c) string bestProgrammingLanguage = "Java";
d) "Java" = String bestProgrammingLanguage;
7. What datatype can only be assigned one of two values?
56
a) double
b) int
c) boolean
d) char
8. What is the value of num?
int num = (10 - (4 + 3)) * 6;
a) 24
b) 18
c) -32
d) 20

__________________________________________
Project-2
Java Variables: Mad Libs
public class MadLibs {

/*

Author: Your name here

Date: Date here

*/

public static void main(String[] args){

String name1 = "Vishva";

String adjective1 = "excited";

String adjective2 = "fantastic";

String adjective3 = "perplexed";


57
String noun1 = "activists";

String noun2 = "art";

String verb1 = "chant";

String noun3 = "drums";

String noun4 = "spectators";

String noun5 = "slush";

String noun6 = "robots";

String name2 = "John";

String place1 = "Paris";

String number = "2050";

//The template for the story

String story = "This morning "+name1+" woke up feeling "+adjective1+". 'It is


going to be a "+adjective2+" day!' Outside, a bunch of "+noun1+" were protesting
to keep "+noun2+" in stores. They began to "+verb1+" to the rhythm of the
"+noun3+", which made all the "+noun4+" very "+adjective3+". Concerned,
"+name1+" texted "+name2+", who flew "+name1+" to "+place1+" and dropped
"+name1+" in a puddle of frozen "+noun5+". "+name1+" woke up in the year
"+number+", in a world where "+noun6+" ruled the world.";

//Printing the story to the console

System.out.println(story);

58
}
OUTPUT
This morning Vishva woke up feeling excited. 'It is going to be a fantastic day!'
Outside, a bunch of activists were protesting to keep art in stores. They began to
chant to the rhythm of the drums, which made all the spectators very perplexed.
Concerned, Vishva texted John, who flew Vishva to Paris and dropped Vishva in a
puddle of frozen slush. Vishva woke up in the year 2050, in a world where robots
ruled the world.

59
3.Manipulating Variables
3.1 Program of Introduction Instructions
public class GuessingGame {
public static void main(String[] args) {
int mystery1 = 8+6;
int mystery2 = 8-6;

System.out.println(mystery2);
}
}
3.2 Program of Addition and Subtraction Instructions
public class PlusAndMinus {
public static void main(String[] args) {
int zebrasInZoo = 8;
int giraffesInZoo = 4;

int animalsInZoo = zebrasInZoo + giraffesInZoo;


System.out.println(animalsInZoo);
int numZebrasAfterTrade = zebrasInZoo-2;
System.out.println(numZebrasAfterTrade);
}
}

60
3.3 Program of Multiplication and Division Instructions
public class MultAndDivide {
public static void main(String[] args) {
double subtotal = 30;
double tax = 0.0875;

double total = subtotal + subtotal*tax;

System.out.println(total);

double perPerson = total/4;

System.out.println(perPerson);
}
}
3.4 Program of Modulo Instructions
public class Modulo {
public static void main(String[] args) {
int students = 26;

int leftOut = 26%3;

System.out.println(leftOut);
}

61
}
3.5 Program of Compound Assignment Operators Instructions
public class BakeSale {
public static void main(String[] args) {
int numCookies = 17;
numCookies -= 3;
numCookies /= 2;

// Add your code above


System.out.println(numCookies);
}
}
3.6 Program of Order of Operations Instructions
public class Operations {
public static void main(String[] args) {

int expression1 = 5 % 2 - (4 * 2 - 1);


System.out.println(expression1);

int expression2 = (3 + (2 * 2 - 5)) + 6 - 5;


System.out.println(expression2);

int expression3 = 5 * 4 % 3 - 2 + 1;
System.out.println(expression3);

62
}
}
3.7 Program of Greater Than and Less Than Instructions
public class GreaterLessThan {
public static void main(String[] args) {
double creditsEarned = 176.5;
double creditsOfSeminar = 8;
double creditsToGraduate = 180;

System.out.println(creditsEarned > creditsToGraduate);

double creditsAfterSeminar = creditsEarned + creditsOfSeminar;

System.out.println(creditsToGraduate < creditsAfterSeminar);


}
}
3.8 Program of Equals and Not Equals Instructions
public class EqualNotEqual {
public static void main(String[] args) {
int songsA = 9;
int songsB = 9;
int albumLengthA = 41;
int albumLengthB = 53;

63
boolean sameNumberOfSongs = songsA == songsB;
boolean differentLength = albumLengthA != albumLengthB;
}
}
3.9 Program of Greater/Less Than or Equal To Instructions
public class GreaterThanEqualTo {
public static void main(String[] args){
double recommendedWaterIntake = 8;
double daysInChallenge = 30;
double yourWaterIntake = 235.5;

double totalRecommendedAmount = recommendedWaterIntake *


daysInChallenge;

boolean isChallengeComplete = yourWaterIntake >=


totalRecommendedAmount;

System.out.println(isChallengeComplete);
}
}
3.10 Program of .equals() Instructions
public class Song {
public static void main(String[] args){
String line1 = "Nah nah nah nah nah nah nah nah nah yeah";

64
String line2 = "Nah nah nah nah nah nah, nah nah nah, hey Jude";
String line3 = "Nah nah nah nah nah nah, nah nah nah, hey Jude";

System.out.println(line1.equals(line2));
System.out.println(line2.equals(line3));

}
}
3.11 Program of String Concatenation Instructions
public class Zoo {
public static void main(String[] args){
int animals = 12;
String species = "zebra";
String zooDescription = "Our zoo has " + animals + " " + species + "s!";

System.out.println(zooDescription);
}
}
3.12 Program of final Keyword Instructions
public class Final {
public static void main(String[] args) {
final double pi = 3.14;
System.out.println(pi);
}

65
}
3.13 Program of Review Instructions
public class BankAccount {
public static void main(String[] args){
double balance = 1000.75;
double amountToWithdraw = 250;

double updatedBalance = balance - amountToWithdraw;


double amountForEachFriend = updatedBalance/3;
boolean canPurchaseTicket = amountForEachFriend >= 250;
System.out.println(canPurchaseTicket);

System.out.println("I gave each friend "+amountForEachFriend+"...");


}
}

__________________________________________
3. Quiz
1. To what value does the following string concatenation evaluate?
"It's " + 5 + "pm"
a) "It's pm"
b) "It's 5pm"
c) Error
d) 11
2. True or False: The value of a variable declared with the final keyword can be
changed after its initial declaration.

66
a) True
b) False
3. How could we get a result of 10, given the following variable?
double a = 2;
a) a - 12
b) a % 10
c) a*5
d) a/2
4. What is the best way to tell if the following two Strings are equal?
String username1 = "teracoder";
String username2 = "gigacoder";
a) username1==username2
b) System.out.println(username1)
c) username1.isEqualTo(username2)
d) username1.equals(username2)
5. Which operator can be used to concatenate two Strings?
a) .equals()
b) -
c) +
d) *
6. The expression 5 != 6 will evaluate to what value?
a) true
b) 6
c) false
d) 5
7. After the following code is run, what value will the variable endpoint be
assigned to?
int endpoint = 11 % 3;
a) 2

67
b) 1
c) 11
d) 2.66
8. What will the following program output?
int num = 12;
num *= 2;
num -= 4;
num++;
System.out.println(num);
a) 20
b) 21
c) 9
d) 12
9. What does the following code do?
System.out.println(8 <= 8);

a) Prints true.
b) Prints 8.
c) Prints false.
d) Prints 0.
10. Are there any errors in this Java statement?
int status = 7 < 8;
a) There are no errors.
b) Yes, int should be boolean.
c) Yes, there should be no semicolon.
d) Yes, int should be char.

__________________________________________
Project-3
68
Math Magic
public class Magic {

public static void main(String[] args) {


// Step 1: Set the original number
int myNumber = 7;
// This is the original number

// Step 2: Multiply the original number by itself


int stepOne = myNumber * myNumber;

// Step 3: Add the original number to the result of step 2


int stepTwo = stepOne + myNumber;

// Step 4: Divide the result of step 3 by the original number


int stepThree = stepTwo / myNumber;

// Step 5: Add 17 to the result of step 4


int stepFour = stepThree + 17;

// Step 6: Subtract the original number from the result of step 5


int stepFive = stepFour - myNumber;

// Step 7: Divide the result of step 6 by 6


int stepSix = stepFive / 6;

69
// Print out the value of the last step
System.out.println(stepSix); // The output should be 3
}
}
OUTPUT
3

70

You might also like