SiddarthComputerScienceProject (1)
SiddarthComputerScienceProject (1)
submitted by
CLASS XI
CHENNAI
Page 1 of 37
TABLE OF CONTENTS
1 OVERVIEW OF PYTHON 3
2 ABSTRACT 4
3 REQUIREMENTS 5
4 MODULES 6
7 OUTPUT 32-34
8 Future Plans 35
9 CONCLUSION 36
10 REFERENCES 37
Page 2 of 37
OVERVIEW
PYTHON
Python was invented by Guido van Rossum in 1991 during his work at
Centrum Wiskunde & Informatica (CWI) in theNetherlands, aiming to create
a language that was easy tolearn yet powerful enough for professional use.
Inspired byABC, a teaching language, Python emphasized simplicity
andreadability while correcting some of ABC’s shortcomings. Thename
"Python" was chosen not from the snake but after thecomedy group "Monty
Python," reflecting Guido's love for their humor.
Python reduces the need to write everything from scratch. Its ecosystem
includes powerful third-party libraries, such as NumPy and pandas for data
analysis, TensorFlow and PyTorch for machine learning, and Flask and
Django for web development. This makes Python a top choice in industries
like data science, web development, and artificial intelligence. Its integration
capabilities with other languages and platforms further enhance its utility,
despite the trade-off of being slower compared to compiled languages
Page 3 of 37
ABSTRACT
Sudoku Game:
A memory game that tests the user’s ability to recall and replicate a
sequence of flashing buttons. The game increases in complexity with each
level, providing visual feedback for correctness.
Weather App:
A graphical application that fetches real-time weather data for a given city
using the OpenWeather API.The app displays temperature, a weather-related
emoji, and a description of the current conditions.
Page 4 of 37
REQUIREMENTS
Software Requirements:
Python 3.x
Pygame library for graphics and input handling
Text editor or IDE (e.g., Visual Studio Code, PyCharm)
Hardware Requirements:
Functional Requirements:
Sudoku Game:
o Interactive grid layout with number input
o Highlighting selected cells
Sequence Memory Test:
o Button flashing and user input tracking
o Feedback for correct or incorrect sequences
Weather App:
o Fetching and displaying weather data from an API
o Responsive interface
Specific Requirements:
Food Chart:
o The food chart program must be stored in a folder with a
separate data file, and a joblib file in order for the code to be
executed successfully.
Page 5 of 37
Modules
PyQt
PyQt is a set of Python bindings for the Qt application framework,
used for creating cross-platform GUI (Graphical User Interface)
applications.
sys
Provides access to variables and functions that interact with the
Python runtime environment
requests
Simplifies HTTP requests to interact with web services and APIs.
tkinter
Python's standard library for creating simple GUI applications.
random
Implements pseudo-random number generators and related
functionality.
pygame
A library for creating 2D games and multimedia applications
joblib
A Python library for saving and loading machine learning models or
other Python objects efficiently using serialization.
pandas
A powerful library for data analysis and manipulation, providing
flexible data structures like DataFrames for handling structured data.
Page 6 of 37
BUILT-IN FUNCTIONS
range()
len()
random.randint()
lambda
list.append()
Adds elements (e.g., row and column values) to the sequence list
and user input list.
str()
str.format()
Page 7 of 37
requests.get()
response.json()
Converts the API response to JSON format for easy access to data
fields.
match
try / except
int()
staticmethod
round()
Page 8 of 37
QApplication.exec_()
dict.get()
len()
range()
str()
all()
Ensures all conditions (like valid row, column, and subgrid values)
are satisfied.
any()
set()
Page 9 of 37
map()
filter()
re.fullmatch()
Validates user input in the grid to ensure only numbers (1-9) are
allowed.
list.append()
Page 10 of 37
Source Code
Sequence Memory Test:
import tkinter as tk
import random
class SequenceMemoryTest:
self.root = root
self.root.config(bg="royalblue")
frame.pack(pady=20)
for i in range(3):
row = []
for j in range(3):
Page 11 of 37
state="disabled", command=lambda r=i, c=j:
self.user_click(r, c))
row.append(button)
self.buttons.append(row)
# Instructions Label
self.label.pack(pady=10)
self.start_game()
def start_game(self):
self.level = 0
self.sequence = []
self.user_sequence = []
self.label.config(text="Get ready!")
self.root.after(1000, self.next_level)
def next_level(self):
self.level += 1
self.label.config(text=f"Level {self.level}")
Page 12 of 37
self.sequence.append((random.randint(0, 2), random.randint(0, 2))) #
Add random button to sequence
self.user_sequence = []
self.root.after(1000, self.show_sequence)
def show_sequence(self):
self.flash_buttons(0)
else:
"""Reset button color after flash and proceed to the next in sequence."""
Page 13 of 37
self.buttons[row][col].config(bg="lightblue")
self.user_sequence.append((row, col))
if self.user_sequence == self.sequence[:len(self.user_sequence)]:
self.flash_grid(correct=True)
else:
self.flash_grid(correct=False)
button.config(bg=color)
def reset_grid_to_lightblue(self):
Page 14 of 37
"""Reset grid color and go to the next level."""
button.config(bg="lightblue")
self.next_level()
def show_game_over(self):
button.config(bg="lightblue")
self.start_game()
if __name__ == "__main__":
root = tk.Tk()
game = SequenceMemoryTest(root)
root.mainloop()
Weather App:
import sys
import requests
Page 15 of 37
class WeatherApp(QWidget):
def __init__(self):
super().__init__()
self.city_input = QLineEdit(self)
self.temperature_label = QLabel(self)
self.emoji_label = QLabel(self)
self.description_label = QLabel(self)
self.initUI()
def initUI(self):
self.setWindowTitle("Weather App")
vbox = QVBoxLayout()
vbox.addWidget(self.city_label)
vbox.addWidget(self.city_input)
vbox.addWidget(self.get_weather_button)
vbox.addWidget(self.temperature_label)
vbox.addWidget(self.emoji_label)
vbox.addWidget(self.description_label)
self.setLayout(vbox)
Page 16 of 37
self.city_label.setAlignment(Qt.AlignCenter)
self.city_input.setAlignment(Qt.AlignCenter)
self.temperature_label.setAlignment(Qt.AlignCenter)
self.emoji_label.setAlignment(Qt.AlignCenter)
self.description_label.setAlignment(Qt.AlignCenter)
self.city_label.setObjectName("city_label")
self.city_input.setObjectName("city_input")
self.get_weather_button.setObjectName("get_weather_button")
self.temperature_label.setObjectName("temperature_label")
self.emoji_label.setObjectName("emoji_label")
self.description_label.setObjectName("description_label")
self.setStyleSheet("""
QLabel, QPushButton{
font-family: calibri;
QLabel#city_label{
font-size: 40px;
font-style: italic;
QLineEdit#city_input{
font-size: 40px;
QPushButton#get_weather_button{
Page 17 of 37
font-size: 30px;
font-weight: bold;
QLabel#temperature_label{
font-size: 75px;
QLabel#emoji_label{
font-size: 100px;
QLabel#description_label{
font-size: 50px;
""")
self.get_weather_button.clicked.connect(self.get_weather)
def get_weather(self):
city = self.city_input.text()
url =
f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_k
ey}"
try:
Page 18 of 37
response = requests.get(url)
response.raise_for_status()
data = response.json()
if data["cod"] == 200:
self.display_weather(data)
match response.status_code:
case 400:
case 401:
case 403:
self.display_error("Forbidden:\nAccess is denied")
case 404:
case 500:
case 502:
case 503:
case 504:
Page 19 of 37
self.display_error("Gateway Timeout:\nNo response from the
server")
case _:
except requests.exceptions.ConnectionError:
except requests.exceptions.Timeout:
except requests.exceptions.TooManyRedirects:
self.display_error(f"Request Error:\n{req_error}")
self.temperature_label.setStyleSheet("font-size: 30px;")
self.temperature_label.setText(message)
self.emoji_label.clear()
self.description_label.clear()
self.temperature_label.setStyleSheet("font-size: 75px;")
temperature_k = data["main"]["temp"]
Page 20 of 37
weather_id = data["weather"][0]["id"]
weather_description = data["weather"][0]["description"]
self.temperature_label.setText(f"{temperature_f:.0f}°F")
self.emoji_label.setText(self.get_weather_emoji(weather_id))
self.description_label.setText(weather_description)
@staticmethod
def get_weather_emoji(weather_id):
return "⛈"
return "⛈"
return "⛈"
return "❄"
return "⛈"
return "⛈"
return "⛈"
Page 21 of 37
return "⛈"
return "☀"
return "☁"
else:
return ""
if __name__ == "__main__":
app = QApplication(sys.argv)
weather_app = WeatherApp()
weather_app.show()
sys.exit(app.exec_())
Sudoku:
import pygame
pygame.font.init()
# Screen settings
WINDOW_SIZE = 500
GRID_SIZE = 9
Page 22 of 37
screen = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE + 100))
# Extra space for instructions
pygame.display.set_caption("Sudoku Game")
pygame.display.set_icon(icon)
sudoku_board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
Page 23 of 37
# Selected cell coordinates
def select_cell(position):
def highlight_cell():
pygame.draw.rect(
def draw_grid():
Page 24 of 37
for col in range(GRID_SIZE):
if sudoku_board[row][col] != 0:
pygame.draw.rect(
def show_instructions():
Page 25 of 37
screen.blit(input_text, (20, WINDOW_SIZE + 50))
def reset_board():
global sudoku_board
sudoku_board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
running = True
while running:
# White background
Page 26 of 37
# Event handling
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_position = pygame.mouse.get_pos()
select_cell(mouse_position)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
reset_board()
sudoku_board[selected_row][selected_col] = int(event.unicode)
# Draw everything
draw_grid()
highlight_cell()
show_instructions()
Page 27 of 37
# Update the display
pygame.display.update()
pygame.quit()
Food Chart:
import joblib
import warnings
import tkinter as tk
warnings.filterwarnings('ignore')
model = joblib.load("food_model.joblib")
frame = tk.Tk()
frame.title("User Form")
frame.geometry("500x300+370+200")
age = tk.StringVar()
gender = tk.StringVar()
occupation = tk.StringVar()
def pie_chart_func(prediction):
plt.title("Food Chart")
prediction_list = list(prediction)[0]
Page 28 of 37
plt.pie(prediction_list, labels=labels, wedgeprops={"edgecolor": "black"},
autopct="%1.1f%%")
plt.show()
age.set("")
gender.set("")
occupation.set("")
def prediction_func():
global user_gender
try:
int(age.get())
except:
age.set("")
return
user_occupation = occupation.get()
user_age = int(age.get())
age.set("")
gender.set("")
occupation.set("")
return
if gender.get() == "Male":
Page 29 of 37
user_gender = 1
user_gender = 0
pie_chart_func(prediction)
occupation_integers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
frame.mainloop()
import pandas as pd
Page 30 of 37
from sklearn.tree import DecisionTreeClassifier
import joblib
food_data = pd.read_csv("food_data.csv")
X = food_data.drop(columns=food_list)
y = food_data.drop(columns=input_set)
model = DecisionTreeClassifier()
model.fit(X, y)
joblib.dump(model, "food_model.joblib")
plt.title("Food Chart")
plt.show()
Page 31 of 37
Output
Page 32 of 37
Page 33 of 37
Page 34 of 37
Future Outlook
Resizable UI:
Implement support for resizable widgets using grid or pack layouts with
weights, ensuring the interface adapts to different screen sizes.
Air Quality Index (AQI): Show the air quality of the selected city.Weather
Alerts: Notify users of severe weather conditions like storms, heatwaves, or
floods
Offline Functionality:
Basic Functionality: Allow the app to function partially (e.g., saved cities and
data) when not connected to the internet.
Implement a timer and scoring system. Timer tracks how long the user takes
to solve the puzzle. Score decreases with incorrect entries or hints used. It
adds a competitive element and tracks player performance.
Page 35 of 37
CONCLUSION
Page 36 of 37
REFERENCES
1. Official Documentation:
Page 37 of 37