# Initializing lists with input values
matrix = [] # Create an empty list
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter the number of columns: "))
for row in range(0, numberOfRows):
matrix.append([]) # Add an empty new row
for column in range(0, numberOfColumns):
value = eval(input("Enter an element and press Enter: "))
matrix[row].append(value)
print(matrix)
Enter the number of rows: 3 Enter the number of columns: 3 Enter an element and press Enter: 1 Enter an element and press Enter: 2 Enter an element and press Enter: 3 Enter an element and press Enter: 4 Enter an element and press Enter: 5 Enter an element and press Enter: 6 Enter an element and press Enter: 78 Enter an element and press Enter: 9 Enter an element and press Enter: 19 [[1, 2, 3], [4, 5, 6], [78, 9, 19]]
# Initializing lists with random values
import random
matrix = [] # Create an empty list
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter the number of columns: "))
for row in range(0, numberOfRows):
matrix.append([]) # Add an empty new row
for column in range(0, numberOfColumns):
matrix[row].append(random.randrange(0, 100))
print(matrix)
Enter the number of rows: 4 Enter the number of columns: 4 [[83, 76, 57, 3], [20, 11, 31, 81], [8, 45, 95, 76], [50, 46, 1, 49]]
# Printing lists
# matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Assume a list is given
for row in range(0, len(matrix)):
for column in range(0, len(matrix[row])):
print(matrix[row][column], end = " ")
print() # Print a newline
83 76 57 3 20 11 31 81 8 45 95 76 50 46 1 49
# Summing all elements
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Assume a list is given
total = 0
for row in range(0, len(matrix)):
for column in range(0, len(matrix[row])):
total += matrix[row][column]
print("Total is " + str(total)) # Print the total
Total is 45
# Summing elements by column
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Assume a list is given
total = 0
for column in range(0, len(matrix[0])):
for row in range(0, len(matrix)):
total += matrix[row][column]
print("Sum for column " + str(column) + " is " + str(total))
Sum for column 0 is 12 Sum for column 1 is 27 Sum for column 2 is 45
# Get the index of row with maximum sum of row
matrix = [[199, 2, 3], [4, 5, 6], [7, 8, 9]] # Assume a list is given
maxRow = sum(matrix[0]) # Get sum of the first row in maxRow
indexOfMaxRow = 0
for row in range(1, len(matrix)):
if sum(matrix[row]) > maxRow:
maxRow = sum(matrix[row])
indexOfMaxRow = row
print("Row " + str(indexOfMaxRow))
Row 0
# Random shuffling
import random
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Assume a list is given
for row in range(0, len(matrix)):
for column in range(0, len(matrix[row])):
i = random.randrange(0, len(matrix))
j = random.randrange(0, len(matrix[row]))
# Swap matrix[row][column] with matrix[i][j]
matrix[row][column], matrix[i][j] = \
matrix[i][j], matrix[row][column]
print(matrix)
[[2, 3, 1], [8, 7, 6], [4, 9, 5]]
# Passing 2-D lists to functions
def getMatrix():
matrix = [] # Create an empty list
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter the number of columns: "))
for row in range(numberOfRows):
matrix.append([]) # Add an empty new row
for column in range(numberOfColumns):
value = eval(input("Enter a value and press Enter: "))
matrix[row].append(value)
return matrix
def accumulate(m):
total = 0
for row in m:
total += sum(row)
return total
def main():
m = getMatrix() # Get an list
print(m)
# Display sum of elements
print("\nSum of all elements is", accumulate(m))
main() # Invoke main function
Enter the number of rows: 3 Enter the number of columns: 3 Enter a value and press Enter: 1 Enter a value and press Enter: 2 Enter a value and press Enter: 3 Enter a value and press Enter: 4 Enter a value and press Enter: 5 Enter a value and press Enter: 6 Enter a value and press Enter: 7 Enter a value and press Enter: 8 Enter a value and press Enter: 9 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Sum of all elements is 45
# Grading Multiple Choice Test Exam
def main():
# Students' answers to the questions
answers = [
['A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
['D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'],
['E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'],
['C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'],
['A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
['B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
['B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'],
['E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D']]
# Key to the questions
keys = ['D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D']
# Grade all answers
for i in range(len(answers)):
# Grade one student
correctCount = 0
for j in range(len(answers[i])):
if answers[i][j] == keys[j]:
correctCount += 1
print("Student", i, "'s correct count is", correctCount)
main() # Call the main function
Student 0 's correct count is 7 Student 1 's correct count is 6 Student 2 's correct count is 5 Student 3 's correct count is 4 Student 4 's correct count is 8 Student 5 's correct count is 7 Student 6 's correct count is 7 Student 7 's correct count is 7
# Compute the distance between two points (x1, y1) and (x2, y2)
def distance(x1, y1, x2, y2):
return ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) ** 0.5
def nearestPoints(points):
# p1 and p2 are the indices in the points list
p1, p2 = 0, 1 # Initial two points
shortestDistance = distance(points[p1][0], points[p1][1],
points[p2][0], points[p2][1]) # Initialize shortestDistance
# Compute distance for every two points
for i in range(len(points)):
for j in range(i + 1, len(points)):
d = distance(points[i][0], points[i][1],
points[j][0], points[j][1]) # Find distance
if shortestDistance > d:
p1, p2 = i, j # Update p1, p2
shortestDistance = d # New shortestDistance
return p1, p2
# Problem: Finding Two Points Nearest to Each Other
#import NearestPoints
def main():
numberOfPoints = eval(input("Enter the number of points: "))
# Create a list to store points
points = []
print("Enter", numberOfPoints, "points:", end = '')
for i in range(numberOfPoints):
point = 2 * [0]
point[0], point[1] = \
eval(input("Enter coordinates separated by a comma: "))
points.append(point)
# p1 and p2 are the indices in the points list
#p1, p2 = NearestPoints.nearestPoints(points)
p1, p2 = nearestPoints(points)
# Display result
print("The closest two points are (" +
str(points[p1][0]) + ", " + str(points[p1][1]) + ") and (" +
str(points[p2][0]) + ", " + str(points[p2][1]) + ")")
main() # Call the main function
Enter the number of points: 3 Enter 3 points:Enter coordinates separated by a comma: 1,2 Enter coordinates separated by a comma: 5,8 Enter coordinates separated by a comma: 4,4 The closest two points are (1, 2) and (4, 4)
# GUI: Finding Two Points Nearest to Each Other
#import NearestPoints
from tkinter import * # Import tkinter
RADIUS = 2 # Radius of the point
class NearestPointsGUI:
def __init__(self):
self.points = [] # Store self.points
window = Tk() # Create a window
window.title("Find Nearest Points") # Set title
self.canvas = Canvas(window, width = 400, height = 200)
self.canvas.pack()
self.canvas.bind("<Button-1>", self.addPoint)
window.mainloop() # Create an event loop
def addPoint(self, event):
if not self.isTooCloseToOtherPoints(event.x, event.y):
self.addThisPoint(event.x, event.y)
def addThisPoint(self, x, y):
# Display this point
self.canvas.create_oval(x - RADIUS, y - RADIUS,
x + RADIUS, y + RADIUS)
# Add this point to self.points list
self.points.append([x, y])
if len(self.points) > 2:
#p1, p2 = NearestPoints.nearestPoints(self.points)
p1, p2 = nearestPoints(self.points)
self.canvas.delete("line")
self.canvas.create_line(self.points[p1][0],
self.points[p1][1], self.points[p2][0],
self.points[p2][1], tags = "line")
def isTooCloseToOtherPoints(self, x, y):
for i in range(len(self.points)):
if distance(x, y,
self.points[i][0], self.points[i][1]) <= RADIUS + 2:
return True
return False
NearestPointsGUI() # Create GUI
<__main__.NearestPointsGUI at 0x28db51efb80>
# Check Sudoku
# Check whether a solution is valid
def isValid(grid):
for i in range(9):
for j in range(9):
if grid[i][j] < 1 or grid[i][j] > 9 \
or not isValidAt(i, j, grid):
return False
return True # The fixed cells are valid
# Check whether grid[i][j] is valid in the grid
def isValidAt(i, j, grid):
# Check whether grid[i][j] is valid at the i's row
for column in range(9):
if column != j and grid[i][column] == grid[i][j]:
return False
# Check whether grid[i][j] is valid at the j's column
for row in range(9):
if row != i and grid[row][j] == grid[i][j]:
return False
# Check whether grid[i][j] is valid in the 3 by 3 box
for row in range((i // 3) * 3, (i // 3) * 3 + 3):
for col in range((j // 3) * 3, (j // 3) * 3 + 3):
if row != i and col != j and \
grid[row][col] == grid[i][j]:
return False
return True # The current value at grid[i][j] is valid
#from CheckSudokuSolution import isValid
def main():
# Read a Sudoku solution
grid = readASolution()
if isValid(grid):
print("Valid solution")
else:
print("Invalid solution")
# Read a Sudoku solution from the console
def readASolution():
print("Enter a Sudoku puzzle solution:")
grid = []
for i in range(9):
line = input().strip().split()
grid.append([eval(x) for x in line])
return grid
main() # Call the main function
from tkinter import * # Import tkinter
import tkinter.messagebox # Import tkinter.messagebox
#from CheckSudokuSolution import isValid # Defined in Listing 11.7
class SudokuGUI:
def __init__(self):
window = Tk() # Create a window
window.title("Check Sudoku Solution") # Set title
frame = Frame(window) # Hold entries
frame.pack()
self.cells = [] # A list of variables tied to entries
for i in range(9):
self.cells.append([])
for j in range(9):
self.cells[i].append(StringVar())
for i in range(9):
for j in range(9):
Entry(frame, width = 2, justify = RIGHT,
textvariable = self.cells[i][j]).grid(
row = i, column = j)
Button(window, text = "Validate",
command = self.validate).pack()
window.mainloop() # Create an event loop
# Check if the numbers entered form a valid solution
def validate(self):
# Get the numbers from the entries
values = [[eval(x.get())
for x in self.cells[i]] for i in range(9)]
if isValid(values):
tkinter.messagebox.showinfo("Check Sudoku Solution",
"The solution is valid")
else:
tkinter.messagebox.showwarning("Check Sudoku Solution",
"The solution is invalid")
SudokuGUI() # Create GUI
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\sakyo\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__ return self.func(*args) File "C:\Users\sakyo\AppData\Local\Temp\ipykernel_21372\640133421.py", line 33, in validate values = [[eval(x.get()) File "C:\Users\sakyo\AppData\Local\Temp\ipykernel_21372\640133421.py", line 33, in <listcomp> values = [[eval(x.get()) File "C:\Users\sakyo\AppData\Local\Temp\ipykernel_21372\640133421.py", line 33, in <listcomp> values = [[eval(x.get()) File "<string>", line 0 SyntaxError: unexpected EOF while parsing
<__main__.SudokuGUI at 0x2ccf5888c40>
# weather.txt
# Suppose a meteorology station records the temperature and humidity at each hour of every day and
# stores the data for the past ten days in a text file named weather.txt.
# Each line of the file consists of four numbers that indicate
# the day, hour, temperature, and humidity.
# Your task is to write a program that
# calculates the average daily temperature and humidity for the 10 days
1 1 76.4 0.92
1 2 77.7 0.93
1 3 77.7 0.93
1 4 77.7 0.93
1 5 77.7 0.93
1 6 77.7 0.93
1 7 77.7 0.93
1 8 77.7 0.93
1 9 77.7 0.93
1 10 77.7 0.93
1 11 77.7 0.93
1 12 77.7 0.93
1 13 79.7 0.93
1 14 77.7 0.93
1 15 77.7 0.93
1 16 77.7 0.93
1 17 77.7 0.93
1 18 77.7 0.93
1 19 77.7 0.93
1 20 77.7 0.93
1 21 77.7 0.93
1 22 78.7 0.93
1 23 77.7 0.93
1 24 77.7 0.93
2 1 76.4 0.92
2 2 77.7 0.93
2 3 77.7 0.93
2 4 74.7 0.93
2 5 77.7 0.93
2 6 77.7 0.93
2 7 72.7 0.93
2 8 77.7 0.93
2 9 77.7 0.93
2 10 77.7 0.93
2 11 77.7 0.93
2 12 77.7 0.93
2 13 77.7 0.93
2 14 77.7 0.93
2 15 77.7 0.93
2 16 77.7 0.93
2 17 77.7 0.93
2 18 77.7 0.93
2 19 77.7 0.93
2 20 77.7 0.93
2 21 77.7 0.93
2 22 77.7 0.93
2 23 77.7 0.93
2 24 77.7 0.93
3 1 76.4 0.92
3 2 77.7 0.93
3 3 77.7 0.93
3 4 77.7 0.93
3 5 77.7 0.93
3 6 77.7 0.93
3 7 77.7 0.93
3 8 77.7 0.93
3 9 77.7 0.93
3 10 77.7 0.93
3 11 77.7 0.93
3 12 77.7 0.93
3 13 77.7 0.93
3 14 77.7 0.93
3 15 77.7 0.93
3 16 77.7 0.93
3 17 77.7 0.93
3 18 77.7 0.93
3 19 77.7 0.93
3 20 77.7 0.93
3 21 77.7 0.93
3 22 77.7 0.93
3 23 77.7 0.93
3 24 77.7 0.93
4 1 76.4 0.92
4 2 77.7 0.93
4 3 77.7 0.93
4 4 77.7 0.93
4 5 77.7 0.93
4 6 77.7 0.93
4 7 77.7 0.93
4 8 77.7 0.93
4 9 77.7 0.93
4 10 77.7 0.93
4 11 77.7 0.93
4 12 77.7 0.93
4 13 77.7 0.93
4 14 77.7 0.93
4 15 77.7 0.93
4 16 77.7 0.93
4 17 77.7 0.93
4 18 77.7 0.93
4 19 77.7 0.93
4 20 77.7 0.93
4 21 77.7 0.93
4 22 77.7 0.93
4 23 77.7 0.93
4 24 77.7 0.93
5 1 76.4 0.92
5 2 77.7 0.93
5 3 77.7 0.93
5 4 77.7 0.93
5 5 77.7 0.93
5 6 77.7 0.93
5 7 77.7 0.93
5 8 77.7 0.93
5 9 77.7 0.93
5 10 77.7 0.93
5 11 77.7 0.93
5 12 77.7 0.93
5 13 77.7 0.93
5 14 77.7 0.93
5 15 77.7 0.93
5 16 77.7 0.93
5 17 77.7 0.93
5 18 77.7 0.93
5 19 77.7 0.93
5 20 77.7 0.93
5 21 77.7 0.93
5 22 77.7 0.93
5 23 77.7 0.93
5 24 77.7 0.93
6 1 76.4 0.92
6 2 77.7 0.93
6 3 77.7 0.93
6 4 77.7 0.93
6 5 77.7 0.93
6 6 77.7 0.93
6 7 77.7 0.93
6 8 77.7 0.93
6 9 77.7 0.93
6 10 77.7 0.93
6 11 77.7 0.93
6 12 77.7 0.93
6 13 77.7 0.93
6 14 77.7 0.93
6 15 77.7 0.93
6 16 77.7 0.93
6 17 77.7 0.93
6 18 77.7 0.93
6 19 77.7 0.93
6 20 77.7 0.93
6 21 77.7 0.93
6 22 77.7 0.93
6 23 77.7 0.93
6 24 77.7 0.93
7 1 76.4 0.92
7 2 77.7 0.93
7 3 77.7 0.93
7 4 77.7 0.93
7 5 77.7 0.93
7 6 77.7 0.93
7 7 77.7 0.93
7 8 77.7 0.93
7 9 77.7 0.93
7 10 77.7 0.93
7 11 77.7 0.93
7 12 77.7 0.93
7 13 77.7 0.93
7 14 77.7 0.93
7 15 77.7 0.93
7 16 77.7 0.93
7 17 77.7 0.93
7 18 77.7 0.93
7 19 77.7 0.93
7 20 77.7 0.93
7 21 77.7 0.93
7 22 77.7 0.93
7 23 77.7 0.93
7 24 77.7 0.93
8 1 76.4 0.92
8 2 77.7 0.93
8 3 77.7 0.93
8 4 77.7 0.93
8 5 77.7 0.93
8 6 78.7 0.93
8 7 77.7 0.93
8 8 77.7 0.93
8 9 77.7 0.93
8 10 77.7 0.93
8 11 77.7 0.93
8 12 77.7 0.93
8 13 77.7 0.93
8 14 77.7 0.93
8 15 77.7 0.93
8 16 77.7 0.93
8 17 77.7 0.93
8 18 77.7 0.93
8 19 77.7 0.93
8 20 77.7 0.93
8 21 77.7 0.93
8 22 77.7 0.93
8 23 77.7 0.93
8 24 77.7 0.93
9 1 76.4 0.92
9 2 77.7 0.93
9 3 77.7 0.93
9 4 77.7 0.93
9 5 77.7 0.93
9 6 77.7 0.93
9 7 77.7 0.93
9 8 77.7 0.93
9 9 77.7 0.93
9 10 77.7 0.93
9 11 77.7 0.93
9 12 77.7 0.93
9 13 77.7 0.93
9 14 77.7 0.93
9 15 77.7 0.93
9 16 77.7 0.93
9 17 77.7 0.93
9 18 77.7 0.93
9 19 77.7 0.93
9 20 77.7 0.93
9 21 77.7 0.93
9 22 77.7 0.93
9 23 77.7 0.93
9 24 77.7 0.93
10 1 76.4 0.92
10 2 77.7 0.93
10 3 77.7 0.93
10 4 77.7 0.93
10 5 77.7 0.93
10 6 77.7 0.93
10 7 77.7 0.93
10 8 77.7 0.93
10 9 77.7 0.93
10 10 77.7 0.93
10 11 77.7 0.93
10 12 77.7 0.93
10 13 77.7 0.93
10 14 77.7 0.93
10 15 77.7 0.93
10 16 77.7 0.93
10 17 77.7 0.93
10 18 77.7 0.93
10 19 77.7 0.93
10 20 77.7 0.93
10 21 77.7 0.93
10 22 77.7 0.93
10 23 97.7 0.71
10 24 98.7 0.74
def main():
NUMBER_OF_DAYS = 10
NUMBER_OF_HOURS = 24
# Initialize data
data = []
for i in range(NUMBER_OF_DAYS):
data.append([])
for j in range(NUMBER_OF_HOURS):
data[i].append([])
data[i][j].append(0) # Temperature value
data[i][j].append(0) # Humidity value
# Read input using input redirection from a file
for k in range(NUMBER_OF_DAYS * NUMBER_OF_HOURS):
line = input().strip().split()
day = eval(line[0])
hour = eval(line[1])
temperature = eval(line[2])
humidity = eval(line[3])
data[day - 1][hour - 1][0] = temperature
data[day - 1][hour - 1][1] = humidity
# Find the average daily temperature and humidity
for i in range(NUMBER_OF_DAYS):
dailyTemperatureTotal = 0
dailyHumidityTotal = 0
for j in range(NUMBER_OF_HOURS):
dailyTemperatureTotal += data[i][j][0]
dailyHumidityTotal += data[i][j][1]
# Display result
print("Day" + str(i) + "'s average temperature is "
+ str(dailyTemperatureTotal / NUMBER_OF_HOURS))
print("Day " + str(i) + "'s average humidity is "
+ str(dailyHumidityTotal / NUMBER_OF_HOURS))
main() # Call the main function
# Guessing Birth day
def main():
day = 0 # Day to be determined
dates = [
[[ 1, 3, 5, 7],
[ 9, 11, 13, 15],
[17, 19, 21, 23],
[25, 27, 29, 31]],
[[ 2, 3, 6, 7],
[10, 11, 14, 15],
[18, 19, 22, 23],
[26, 27, 30, 31]],
[[ 4, 5, 6, 7],
[12, 13, 14, 15],
[20, 21, 22, 23],
[28, 29, 30, 31]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15],
[24, 25, 26, 27],
[28, 29, 30, 31]],
[[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]]]
for i in range(5):
print("Is your birthday in Set" + str(i + 1) + "?")
for j in range(4):
for k in range(4):
print(format(dates[i][j][k], '4d'), end = " ")
print()
answer = eval(input("Enter 0 for No and 1 for Yes: "))
if answer == 1:
day += dates[i][0][0]
print("Your birth day is " + str(day))
main() # Call the main function
Is your birthday in Set1? 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 Enter 0 for No and 1 for Yes: 0 Is your birthday in Set2? 2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31 Enter 0 for No and 1 for Yes: 1 Is your birthday in Set3? 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31 Enter 0 for No and 1 for Yes: 0 Is your birthday in Set4? 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31 Enter 0 for No and 1 for Yes: 0 Is your birthday in Set5? 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Enter 0 for No and 1 for Yes: 0 Your birth day is 2
class GeometricObject:
def __init__(self, color = "green", filled = True):
self.__color = color
self.__filled = filled
def getColor(self):
return self.__color
def setColor(self, color):
self.__color = color
def isFilled(self):
return self.__filled
def setFilled(self, filled):
self.__filled = filled
def __str__(self):
return "color: " + self.__color + \
" and filled: " + str(self.__filled)
# from GeometricObject import GeometricObject
import math
class Circle(GeometricObject):
def __init__(self, radius):
super().__init__()
self.__radius = radius
def getRadius(self):
return self.__radius
def setRadius(self, radius):
self.__radius = radius
def getArea(self):
return self.__radius * self.__radius * math.pi
def getDiameter(self):
return 2 * self.__radius
def getPerimeter(self):
return 2 * self.__radius * math.pi
def printCircle(self):
print(self.__str__() + " radius: " + str(self.__radius))
#from GeometricObject import GeometricObject
class Rectangle(GeometricObject):
def __init__(self, width = 1, height = 1):
super().__init__()
self.__width = width
self.__height = height
def getWidth(self):
return self.__width
def setWidth(self, width):
self.__width = width
def getHeight(self):
return self.__height
def setHeight(self, height):
self.__height = self.__height
def getArea(self):
return self.__width * self.__height
def getPerimeter(self):
return 2 * (self.__width + self.__height)
def __str__(self):
return super().__str__() + " width=" + str(self.__width) + " height=" + str(self.__height)
def __eq__(self,rect):
pass
#from CircleFromGeometricObject import Circle
#from RectangleFromGeometricObject import Rectangle
def main():
circle = Circle(1.5)
print("A circle", circle)
print("The radius is", circle.getRadius())
print("The area is", circle.getArea())
print("The diameter is", circle.getDiameter())
rectangle = Rectangle(2, 4)
print("\nA rectangle", rectangle)
print("The area is", rectangle.getArea())
print("The perimeter is", rectangle.getPerimeter())
main() # Call the main function
A circle color: green and filled: True The radius is 1.5 The area is 7.0685834705770345 The diameter is 3.0 A rectangle color: green and filled: True The area is 8 The perimeter is 12
r2 = Rectangle(5,8)
r2.getColor()
'green'
print(r2)
color: green and filled: True width=5 height=8
#from CircleFromGeometricObject import Circle
#from RectangleFromGeometricObject import Rectangle
def main():
# Display circle and rectangle properties
c = Circle(4)
r = Rectangle(1, 3)
displayObject(c)
displayObject(r)
print("Are the circle and rectangle the same size?",
isSameArea(c, r))
# Display geometric object properties
def displayObject(g):
print(g.__str__())
# Compare the areas of two geometric objects
def isSameArea(g1, g2):
return g1.getArea() == g2.getArea()
main() # Call the main function
color: green and filled: True color: green and filled: True width=1 height=3 Are the circle and rectangle the same size? False
def main():
# Display circle and rectangle properties
c = Circle(4)
r = Rectangle(1, 3)
print("Circle...")
displayObject(c)
print("Rectangle...")
displayObject(r)
# Display geometric object properties
def displayObject(g):
print("Area is", g.getArea())
print("Perimeter is", g.getPerimeter())
if isinstance(g, Circle):
print("Diameter is", g.getDiameter())
elif isinstance(g, Rectangle):
print("Width is", g.getWidth())
print("Height is", g.getHeight())
main() # Call the main function
Circle... Area is 50.26548245743669 Perimeter is 25.132741228718345 Diameter is 8 Rectangle... Area is 3 Perimeter is 8 Width is 1 Height is 3
from tkinter import * # Import tkinter
import math
from datetime import datetime
class StillClock(Canvas):
def __init__(self, container):
super().__init__(container)
self.setCurrentTime()
def getHour(self):
return self.__hour
def setHour(self, hour):
self.__hour = hour
self.delete("clock")
self.drawClock()
def getMinute(self):
return self.__minute
def setMinute(self, minute):
self.__minute = minute
self.delete("clock")
self.drawClock()
def getSecond(self):
return self.__second
def setSecond(self, second):
self.__second = second
self.delete("clock")
self.drawClock()
def setCurrentTime(self):
d = datetime.now()
self.__hour = d.hour
self.__minute = d.minute
self.__second = d.second
self.delete("clock")
self.drawClock()
def drawClock(self):
width = float(self["width"])
height = float(self["height"])
radius = min(width, height) / 2.4
secondHandLength = radius * 0.8
minuteHandLength = radius * 0.65
hourHandLength = radius * 0.5
self.create_oval(width / 2 - radius, height / 2 - radius,
width / 2 + radius, height / 2 + radius, tags = "clock")
self.create_text(width / 2 - radius + 5, height / 2,
text = "9", tags = "clock")
self.create_text(width / 2 + radius - 5, height / 2,
text = "3", tags = "clock")
self.create_text(width / 2, height / 2 - radius + 5,
text = "12", tags = "clock")
self.create_text(width / 2, height / 2 + radius - 5,
text = "6", tags = "clock")
xCenter = width / 2
yCenter = height / 2
second = self.__second
xSecond = xCenter + secondHandLength \
* math.sin(second * (2 * math.pi / 60))
ySecond = yCenter - secondHandLength \
* math.cos(second * (2 * math.pi / 60))
self.create_line(xCenter, yCenter, xSecond, ySecond,
fill = "red", tags = "clock")
minute = self.__minute
xMinute = xCenter + \
minuteHandLength * math.sin(minute * (2 * math.pi / 60))
yMinute = yCenter - \
minuteHandLength * math.cos(minute * (2 * math.pi / 60))
self.create_line(xCenter, yCenter, xMinute, yMinute,
fill = "blue", tags = "clock")
hour = self.__hour % 12
xHour = xCenter + hourHandLength * \
math.sin((hour + minute / 60) * (2 * math.pi / 12))
yHour = yCenter - hourHandLength * \
math.cos((hour + minute / 60) * (2 * math.pi / 12))
self.create_line(xCenter, yCenter, xHour, yHour,
fill = "green", tags = "clock")
timestr = str(hour) + ":" + str(minute) + ":" + str(second)
self.create_text(width / 2, height / 2 + radius + 10,
text = timestr, tags = "clock")
from tkinter import * # Import tkinter
#from StillClock import StillClock
class DisplayClock:
def __init__(self):
window = Tk() # Create a window
window.title("Change Clock Time") # Set title
self.clock = StillClock(window) # Create a clock
self.clock.pack()
frame = Frame(window)
frame.pack()
Label(frame, text = "Hour: ").pack(side = LEFT)
self.hour = IntVar()
self.hour.set(self.clock.getHour())
Entry(frame, textvariable = self.hour,
width = 2).pack(side = LEFT)
Label(frame, text = "Minute: ").pack(side = LEFT)
self.minute = IntVar()
self.minute.set(self.clock.getMinute())
Entry(frame, textvariable = self.minute,
width = 2).pack(side = LEFT)
Label(frame, text = "Second: ").pack(side = LEFT)
self.second = IntVar()
self.second.set(self.clock.getMinute())
Entry(frame, textvariable = self.second,
width = 2).pack(side = LEFT)
Button(frame, text = "Set New Time",
command = self.setNewTime).pack(side = LEFT)
window.mainloop() # Create an event loop
def setNewTime(self):
self.clock.setHour(self.hour.get())
self.clock.setMinute(self.minute.get())
self.clock.setSecond(self.second.get())
DisplayClock() # Create GUI
<__main__.DisplayClock at 0x1e9dfd2c370>
class Course:
def __init__(self, courseName):
self.__courseName = courseName
self.__students = []
def addStudent(self, student):
self.__students.append(student)
def getStudents(self):
return self.__students
def getNumberOfStudents(self):
return len(self.__students)
def getCourseName(self):
return self.__courseName
def dropStudent(student):
print("Left as an exercise")
#from Course import Course
def main():
course1 = Course("Data Structures")
course2 = Course("Database Systems")
course1.addStudent("Peter Jones")
course1.addStudent("Brian Smith")
course1.addStudent("Anne Kennedy")
course2.addStudent("Peter Jones")
course2.addStudent("Steve Smith")
print("Number of students in course1:",
course1.getNumberOfStudents())
students = course1.getStudents()
for student in students:
print(student, end = ", ")
print("\nNumber of students in course2:",
course2.getNumberOfStudents())
main() # Call the main function
Number of students in course1: 3 Peter Jones, Brian Smith, Anne Kennedy, Number of students in course2: 2
class Stack:
def __init__(self):
self.__elements = []
# Return true if the tack is empty
def isEmpty(self):
return len(self.__elements) == 0
# Returns the element at the top of the stack
# without removing it from the stack.
def peek(self):
if self.isEmpty():
return None
else:
return self.__elements[len(elements) - 1]
# Stores an element into the top of the stack
def push(self, value):
self.__elements.append(value)
# Removes the element at the top of the stack and returns it
def pop(self):
if self.isEmpty():
return None
else:
return self.__elements.pop()
# Return the size of the stack
def getSize(self):
return len(self.__elements)
#from Stack import Stack
stack = Stack()
for i in range(10):
stack.push(i)
while not stack.isEmpty():
print(stack.pop(), end = " ")
9 8 7 6 5 4 3 2 1 0
from tkinter import * # Import tkinter
class FigureCanvas(Canvas):
def __init__(self, container, figureType, filled = False,
width = 100, height = 100):
super().__init__(container,
width = width, height = height)
self.__figureType = figureType
self.__filled = filled
self.drawFigure()
def getFigureType(self):
return self.__figureType
def getFilled(self):
return self.__filled
def setFigureType(self, figureType):
self.__figureType = figureType
self.drawFigure()
def setFilled(self, filled):
self.__filled = filled
self.drawFigure()
def drawFigure(self):
if self.__figureType == "line":
self.line()
elif self.__figureType == "rectangle":
self.rectangle()
elif self.__figureType == "oval":
self.oval()
elif self.__figureType == "arc":
self.arc()
def line(self):
width = int(self["width"])
height = int(self["height"])
self.create_line(10, 10, width - 10, height - 10)
self.create_line(width - 10, 10, 10, height - 10)
def rectangle(self):
width = int(self["width"])
height = int(self["height"])
if self.__filled:
self.create_rectangle(10, 10, width - 10, height - 10,
fill = "red")
else:
self.create_rectangle(10, 10, width - 10, height - 10)
def oval(self):
width = int(self["width"])
height = int(self["height"])
if self.__filled:
self.create_oval(10, 10, width - 10, height - 10,
fill = "red")
else:
self.create_oval(10, 10, width - 10, height - 10)
def arc(self):
width = int(self["width"])
height = int(self["height"])
if self.__filled:
self.create_arc(10, 10, width - 10, height - 10,
start = 0, extent = 145, fill = "red")
else:
self.create_arc(10, 10, width - 10, height - 10,
start = 0, extent = 145)
from tkinter import * # Import tkinter
#from FigureCanvas import FigureCanvas
class DisplayFigures:
def __init__(self):
window = Tk() # Create a window
window.title("Display Figures") # Set title
figure1 = FigureCanvas(window, "line", width = 100, height = 100)
figure1.grid(row = 1, column = 1)
figure2 = FigureCanvas(window, "rectangle", False, 100, 100)
figure2.grid(row = 1, column = 2)
figure3 = FigureCanvas(window, "oval", False, 100, 100)
figure3.grid(row = 1, column = 3)
figure4 = FigureCanvas(window, "arc", False, 100, 100)
figure4.grid(row = 1, column = 4)
figure5 = FigureCanvas(window, "rectangle", True, 100, 100)
figure5.grid(row = 1, column = 5)
figure6 = FigureCanvas(window, "oval", True, 100, 100)
figure6.grid(row = 1, column = 6)
figure7 = FigureCanvas(window, "arc", True, 100, 100)
figure7.grid(row = 1, column = 7)
window.mainloop() # Create an event loop
DisplayFigures() # Create GUI
<__main__.DisplayFigures at 0x1e9e2a75e20>
def main():
# Open file for output
outfile = open("USPresidents.txt", "w")
# Write data to the file
outfile.write("Bill Clinton\n")
outfile.write("George Bush\n")
outfile.write("Barack Obama")
outfile.close() # Close the output file
main() # Call the main function
def main():
# Open file for input
infile = open("USPresidents.txt", "r")
print("(1) Using read(): ")
print(infile.read())
infile.close() # Close the input file
# Open file for input
infile = open("USPresidents.txt", "r")
print("\n(2) Using read(number): ")
s1 = infile.read(4)
print(s1)
s2 = infile.read(10)
print(repr(s2))
infile.close() # Close the input file
# Open file for input
infile = open("USPresidents.txt", "r")
print("\n(3) Using readline(): ")
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
line4 = infile.readline()
print(repr(line1))
print(repr(line2))
print(repr(line3))
print(repr(line4))
infile.close() # Close the input file
# Open file for input
infile = open("USPresidents.txt", "r")
print("\n(4) Using readlines(): ")
print(infile.readlines())
infile.close() # Close the input file
main() # Call the main function
(1) Using read(): Bill Clinton George Bush Barack Obama (2) Using read(number): Bill ' Clinton\nG' (3) Using readline(): 'Bill Clinton\n' 'George Bush\n' 'Barack Obama' '' (4) Using readlines(): ['Bill Clinton\n', 'George Bush\n', 'Barack Obama']
def main():
# Open file for appending data
outfile = open("Info.txt", "a")
outfile.write("\nPython is interpreted\n")
outfile.close() # Close the input file
main() # Call the main function
from random import randint
def main():
# Open file for writing data
outfile = open("MyNumbers.txt", "w")
for i in range(10):
outfile.write(str(randint(0, 9)) + " ")
outfile.close() # Close the file
# Open file for reading data
infile = open("MyNumbers.txt", "r")
s = infile.read()
numbers = [eval(x) for x in s.split()]
for number in numbers:
print(number, end = " ")
infile.close() # Close the file
main() # Call the main function
9 6 0 1 3 0 1 6 3 2
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
class FileEditor:
def __init__(self):
window = Tk()
window.title("Simple Text Editor")
# Create a menu bar
menubar = Menu(window)
window.config(menu = menubar) # Display the menu bar
# create a pulldown menu, and add it to the menu bar
operationMenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "File", menu = operationMenu)
operationMenu.add_command(label = "Open",
command = self.openFile)
operationMenu.add_command(label = "Save",
command = self.saveFile)
# Add a tool bar frame
frame0 = Frame(window) # Create and add a frame to window
frame0.grid(row = 1, column = 1, sticky = W)
# Create images
opneImage = PhotoImage(file = "image/open.gif")
saveImage = PhotoImage(file = "image/save.gif")
Button(frame0, image = opneImage, command =
self.openFile).grid(row = 1, column = 1, sticky = W)
Button(frame0, image = saveImage,
command = self.saveFile).grid(row = 1, column = 2)
frame1 = Frame(window) # Hold editor pane
frame1.grid(row = 2, column = 1)
scrollbar = Scrollbar(frame1)
scrollbar.pack(side = RIGHT, fill = Y)
self.text = Text(frame1, width = 40, height = 20,
wrap = WORD, yscrollcommand = scrollbar.set)
self.text.pack()
scrollbar.config(command = self.text.yview)
window.mainloop() # Create an event loop
def openFile(self):
filenameforReading = askopenfilename()
infile = open(filenameforReading, "r")
self.text.insert(END, infile.read()) # Read all from the file
infile.close() # Close the input file
def saveFile(self):
filenameforWriting = asksaveasfilename()
outfile = open(filenameforWriting, "w")
# Write to the file
outfile.write(self.text.get(1.0, END))
outfile.close() # Close the output file
FileEditor() # Create GUI
<__main__.FileEditor at 0x1e9e0e57f70>
def main():
filename = input("Enter a filename: ").strip()
infile = open(filename, "r") # Open the file
counts = 26 * [0] # Create and initialize counts
print(counts)
for line in infile:
# Invoke the countLetters function to count each letter
countLetters(line.lower(), counts)
print(counts)
# Display results
for i in range(len(counts)):
if counts[i] != 0:
print(chr(ord('a') + i) + " appears " + str(counts[i])
+ (" time" if counts[i] == 1 else " times"))
infile.close() # Close file
# Count each letter in the string
def countLetters(line, counts):
for ch in line:
if ch.isalpha():
counts[ord(ch) - ord('a')] += 1
main() # Call the main function
Enter a filename: USPresidents.txt [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [4, 4, 2, 0, 2, 0, 2, 1, 2, 0, 1, 3, 1, 2, 3, 0, 0, 2, 1, 1, 1, 0, 0, 0, 0, 0] a appears 4 times b appears 4 times c appears 2 times e appears 2 times g appears 2 times h appears 1 time i appears 2 times k appears 1 time l appears 3 times m appears 1 time n appears 2 times o appears 3 times r appears 2 times s appears 1 time t appears 1 time u appears 1 time
import urllib.request
def main():
url = input("Enter an URL for a file: ").strip()
infile = urllib.request.urlopen(url)
s = infile.read().decode() # Read the content as string
print(s)
counts = countLetters(s.lower())
# Display results
for i in range(len(counts)):
if counts[i] != 0:
print(chr(ord('a') + i) + " appears " + str(counts[i])
+ (" time" if counts[i] == 1 else " times"))
# Count each letter in the string
def countLetters(s):
counts = 255 * [0] # Create and initialize counts
for ch in s:
if ch.isalpha():
counts[ord(ch) - ord('a')] += 1
return counts
main() # Call the main function
Enter an URL for a file: http://www.akyokus.com <!doctype html> <html> <head> <meta content="width=device-width, initial-scale=1" name="viewport" /> <meta charset="utf-8" /> <title>Professor Selim Akyokuş</title> <!-- Latest compiled and minified CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script> <link href="css/font-awesome.css" rel="stylesheet"> <link href="css/bootstrap-social.css" rel="stylesheet" /> <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon"> <link href="/favicon.ico" rel="icon" type="image/x-icon"> <link href="/apple-touch-icon.png" rel="apple-touch-icon" sizes="180x180"> <link href="/favicon-32x32.png" rel="icon" sizes="32x32" type="image/png"> <link href="/favicon-16x16.png" rel="icon" sizes="16x16" type="image/png"> <style type="text/css"> .auto-style1 { border-width: 0px; } </style> </head> <body> <br \="" /> <div class="container"> <div class="page-header"> <div class="row"> <div class="col-sm-7"> <h1>Professor Dr. Selim Akyokuş</h1> <table> <tr> <td><a href="http://www.medipol.edu.tr"> <img alt="school-logo" class="auto-style1" height="120" src="images/Medipol_UNV_mavi_zeminli_arma.jpg" width="120" /></a> </td> <td><br /> <p style="font-size: medium">Computer Engineering Department <br /> School of Engineering and Natural Sciences<br /> Istanbul Medipol University</p> </td> </tr> </table> </div> <div class="col-sm-3"> <br /> <h3><span class="float-md-left">Contact Info:</span></h3> <p><span class="float-md-right">Email: <a href="mailto:sakyokus@medipol.edu.tr">sakyokus@medipol.edu.tr</a><br /> Office: C Blok, No: 320 <br /> Phone: 444-8544<br /> Office Hours: In times announced in classes or by appointment</span></p> <span class="float-md-left"><br /> <a class="btn btn-social-icon btn-linkedin" href="https://tr.linkedin.com/in/selimakyokus"> <span class="fa fa-linkedin"></span></a> <a class="btn btn-social-icon btn-twitter" href="https://twitter.com/sakyokus"> <span class="fa fa-twitter"></span></a> <a class="btn btn-social-icon btn-github" href="https://github.com/sakyokus"> <span class="fa fa-github"></span></a> <br /> </span></div> <div class="col-sm-2" style="left: 0px; top: 0px"> <br /> <img alt="Professor Image" class="rounded" height="242" src="images/sa-foto2.jpg" width="190" /> </div> </div> </div> <div class="row"> <h3>Current Courses (Spring 2022): </h3> <div class="col-sm-12"> - <a href="fall2022/pl/index.html">Principles of Programming Languages (COE1212508 )</a><br> - <a href="fall2022/ip/index.html">Introduction to Programming (COE1213180, BME1213180, EEE1213180, IND1213180, CEE1213180) </a> <br /> <a href="spring2019/co/lectures.html"> </a> </div> </div> <div class="row"> <h3>Reseach Interests</h3> <div class="col-sm-12"> <p class="text-justify">My current research interests include Data Science, Data Mining, Text Mining, Machine Learning, Time-Series Prediction, Database Systems, Information Retrival Systems, Social Network Analysis, Sentiment Analysis, Programming Languages and Web Technologies. .</p> </div> <h3>Education</h3> <div class="col-sm-12"> <table> <tr> <td> <ul> <li>BS in Computer Engineering, Middle East Technical University </li> <li>MS in Computer Engineering, Middle East Technical University </li> <li>PhD in Computer Science, Syracuse University </li> </ul> </td> </tr> </table> </div> <h3>Quick Links: </h3> <div class="col-sm-12"> <a href="courses.html">Courses</a> | <a href="publications.html">Publications</a> | <a href="curriculumvitea.html">Curriculum Vitae</a> </div> <br \="" /> </div> </div> </body> </html> a appears 183 times b appears 60 times c appears 145 times d appears 90 times e appears 216 times f appears 55 times g appears 50 times h appears 82 times i appears 212 times j appears 14 times k appears 29 times l appears 148 times m appears 91 times n appears 165 times o appears 144 times p appears 108 times q appears 3 times r appears 146 times s appears 235 times t appears 200 times u appears 62 times v appears 39 times w appears 18 times x appears 20 times y appears 38 times z appears 5 times ş appears 2 times
def main():
try:
number1, number2 = eval(
input("Enter two numbers, separated by a comma: "))
result = number1 / number2
print("Result is " + str(result))
except ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the input")
except:
print("Something wrong in the input")
else:
print("No exceptions")
finally:
print("The finally clause is executed")
main()
Enter two numbers, separated by a comma: 4,2 Result is 2.0 No exceptions The finally clause is executed
def main():
try:
number1, number2 = eval(
input("Enter two numbers, separated by a comma: "))
result = number1 / number2
print("Result is " + str(result))
except ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the input")
except:
print("Something wrong in the input")
else:
print("No exceptions")
finally:
print("The finally clause is executed")
main()
Enter two numbers, separated by a comma: 4,0 Division by zero! The finally clause is executed
def main():
try:
number1, number2 = eval(
input("Enter two numbers, separated by a comma: "))
result = number1 / number2
print("Result is " + str(result))
except ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the input")
except:
print("Something wrong in the input")
else:
print("No exceptions")
finally:
print("The finally clause is executed")
main()
Enter two numbers, separated by a comma: 2 ; 4 A comma may be missing in the input The finally clause is executed
def main():
try:
number1, number2 = eval(
input("Enter two numbers, separated by a comma: "))
result = number1 / number2
print("Result is " + str(result))
except ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the input")
except:
print("Something wrong in the input")
else:
print("No exceptions")
finally:
print("The finally clause is executed")
main()
Enter two numbers, separated by a comma: a,b Something wrong in the input The finally clause is executed
def getArea(radius):
if radius < 0:
raise RuntimeError("Negative radius")
return radius * radius * 3.1415
try:
print(getArea(5))
print(getArea(-5))
except RuntimeError:
print("Invalid radius")
78.53750000000001 Invalid radius
try:
number = eval(input("Enter a number: "))
print("The number entered is", number)
except NameError as ex:
print("Exception:", ex)
Enter a number: 111 The number entered is 111
try:
number = eval(input("Enter a number: "))
print("The number entered is", number)
except NameError as ex:
print("Exception:", ex)
Enter a number: ali Exception: name 'ali' is not defined
class InvalidRadiusException(RuntimeError):
def __init__(self, radius):
super().__init__()
self.radius = radius
#from GeometricObject import GeometricObject
#from InvalidRadiusException import InvalidRadiusException
import math
class Circle(GeometricObject):
def __init__(self, radius):
super().__init__()
self.setRadius(radius)
def getRadius(self):
return self.__radius
def setRadius(self, radius):
if radius >= 0:
self.__radius = radius
else:
raise InvalidRadiusException(radius)
def getArea(self):
return self.__radius * self.__radius * math.pi
def getDiameter(self):
return 2 * self.__radius
def getPerimeter(self):
return 2 * self.__radius * math.pi
def printCircle(self):
print(self.__str__(), "radius:", self.__radius)
#from CircleWithCustomException import Circle
#from InvalidRadiusException import InvalidRadiusException
try:
c1 = Circle(5)
print("c1's area is", c1.getArea())
c2 = Circle(-5)
print("c2's area is", c2.getArea())
c3 = Circle(0)
print("c3's area is", c3.getArea())
except InvalidRadiusException as ex:
print("The radius", ex.radius, "is invalid")
except Exception:
print("Something is wrong")
c1's area is 78.53981633974483 The radius -5 is invalid
import pickle
def main():
# Open file for writing binary
outfile = open("Mypickle.dat", "wb")
pickle.dump(45, outfile)
pickle.dump(56.6, outfile)
pickle.dump("Programming is fun", outfile)
pickle.dump([1, 2, 3, 4], outfile)
outfile.close() # Close the output file
# Open file for reading binary
infile = open("Mypickle.dat", "rb")
print(pickle.load(infile))
print(pickle.load(infile))
print(pickle.load(infile))
print(pickle.load(infile))
infile.close() # Close the input file
main() # Call the main function
45 56.6 Programming is fun [1, 2, 3, 4]
import pickle
def main():
# Open file for writing binary
outfile = open("Mynumbers.dat", "wb")
data = eval(input("Enter an integer (the input exits " +
"if the input is 0): "))
while data != 0:
pickle.dump(data, outfile)
data = eval(input("Enter an integer (the input exits " +
"if the input is 0): "))
outfile.close() # Close the output file
# Open file for reading binary
infile = open("Mynumbers.dat", "rb")
end_of_file = False
while not end_of_file:
try:
print(pickle.load(infile), end = " ")
except EOFError:
end_of_file = True
infile.close() # Close the input file
print("\nAll objects are read")
main() # Call the main function
Enter an integer (the input exits if the input is 0): 5 Enter an integer (the input exits if the input is 0): 8 Enter an integer (the input exits if the input is 0): 3 Enter an integer (the input exits if the input is 0): 8 Enter an integer (the input exits if the input is 0): 1 Enter an integer (the input exits if the input is 0): 0 5 8 3 8 1 All objects are read
import pickle
import os.path
from tkinter import * # Import tkinter
import tkinter.messagebox
class Address:
def __init__(self, name, street, city, state, zip):
self.name = name
self.street = street
self.city = city
self.state = state
self.zip = zip
class AddressBook:
def __init__(self):
window = Tk() # Create a window
window.title("AddressBook") # Set title
self.nameVar = StringVar()
self.streetVar = StringVar()
self.cityVar = StringVar()
self.stateVar = StringVar()
self.zipVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "Name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.nameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Street").grid(row = 1,
column = 1, sticky = W)
Entry(frame2, textvariable = self.streetVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Label(frame3, text = "City", width = 5).grid(row = 1,
column = 1, sticky = W)
Entry(frame3,
textvariable = self.cityVar).grid(row = 1, column = 2)
Label(frame3, text = "State").grid(row = 1,
column = 3, sticky = W)
Entry(frame3, textvariable = self.stateVar,
width = 5).grid(row = 1, column = 4)
Label(frame3, text = "ZIP").grid(row = 1,
column = 5, sticky = W)
Entry(frame3, textvariable = self.zipVar,
width = 5).grid(row = 1, column = 6)
frame4 = Frame(window)
frame4.pack()
Button(frame4, text = "Add",
command = self.processAdd).grid(row = 1, column = 1)
btFirst = Button(frame4, text = "First",
command = self.processFirst).grid(row = 1, column = 2)
btNext = Button(frame4, text = "Next",
command = self.processNext).grid(row = 1, column = 3)
btPrevious = Button(frame4, text = "Previous", command =
self.processPrevious).grid(row = 1, column = 4)
btLast = Button(frame4, text = "Last",
command = self.processLast).grid(row = 1, column = 5)
self.addressList = self.loadAddress()
self.current = 0
if len(self.addressList) > 0:
self.setAddress()
window.mainloop() # Create an event loop
def saveAddress(self):
outfile = open("address.dat", "wb")
pickle.dump(self.addressList, outfile)
tkinter.messagebox.showinfo(
"Address saved", "A new address is saved")
outfile.close()
def loadAddress(self):
if not os.path.isfile("address.dat"):
return [] # Return an empty list
try:
infile = open("address.dat", "rb")
addressList = pickle.load(infile)
except EOFError:
addressList = []
infile.close()
return addressList
def processAdd(self):
address = Address(self.nameVar.get(),
self.streetVar.get(), self.cityVar.get(),
self.stateVar.get(), self.zipVar.get())
self.addressList.append(address)
self.saveAddress()
def processFirst(self):
self.current = 0
self.setAddress()
def processNext(self):
if self.current < len(self.addressList) - 1:
self.current += 1
self.setAddress()
def processPrevious(self):
pass # Left as exercise
def processLast(self):
pass # Left as exercise
def setAddress(self):
self.nameVar.set(self.addressList[self.current].name)
self.streetVar.set(self.addressList[self.current].street)
self.cityVar.set(self.addressList[self.current].city)
self.stateVar.set(self.addressList[self.current].state)
self.zipVar.set(self.addressList[self.current].zip)
AddressBook() # Create GUI
<__main__.AddressBook at 0x1e9e0e631c0>