Python Guessing Game Tutorial
Part 1: Hello, World!
Concept: Every programming journey begins with a simple message. The print() function displays text to the user.
print("Hello, World!")
Your Turn: Replace “Hello, World!” with a greeting for your game. Run your code to see what happens!
# Your code here:
print("Welcome to the Number Guessing Game!")
Part 2: Variables and User Input
Concept: Variables store information that your program can use later. The input() function collects information from the user.
Example:
name = "Alex"
print("Hello, " + name + "!")
Your Turn: Use the input() function to ask for the player’s name, then store it in a variable and greet them.
# Your code here:
player_name = input("What is your name? ")
print("Hello, " + player_name + "! Let's play a guessing game.")
Part 3: Importing Libraries and Random Numbers
Concept: Python has many libraries that provide extra functionality. The random library can generate random numbers, which are perfect for our game!
Example:
import random
random_number = random.randint(1, 10)
print("A random number between 1 and 10:", random_number)
Your Turn: Import the random library and create a secret number between 1 and 100 for your game.
# Your code here:
import random
secret_number = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100...")
Part 4: Converting Data Types
Concept: The input() function returns text (a string), but we need a number to compare with our secret number. We need to convert the input to an integer using int().
Example:
age_text = input("How old are you? ")
age_number = int(age_text)
print("Next year, you will be", age_number + 1)
Your Turn: Create a variable called guess that gets a number from the player and converts it to an integer.
# Your code here:
guess_text = input("Enter your guess (1-100): ")
guess = int(guess_text)
Part 5: Conditional Statements
Concept: Conditional statements (if, elif, else) let your program make decisions based on certain conditions.
Example:
temperature = 75
if temperature > 80:
print("It's hot today!")
elif temperature < 60:
print("It's cold today!")
else:
print("The weather is perfect!")
Your Turn: Write conditions to tell the player if their guess is too high, too low, or correct.
# Your code here:
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("You got it! The number was " + str(secret_number))
Part 6: While Loops
Concept: While loops repeat code as long as a condition is true. This is perfect for letting the player keep guessing until they get it right.
count = 1
while count <= 5:
print("Count is:", count)
count = count + 1
print("Loop finished!")
Your Turn: Create a while loop that lets the player keep guessing until they reach the maximum number of attempts.
# Your code here:
attempts = 0
max_attempts = 10
while attempts < max_attempts:
guess_text = input("Enter your guess (1-100): ")
guess = int(guess_text)
attempts = attempts + 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("You got it in " + str(attempts) + " attempts! The number was " + str(secret_number))
break
if attempts >= max_attempts:
print("Sorry, you've used all " + str(max_attempts) + " attempts. The number was " + str(secret_number) + ".")
Part 7: F-Strings (Formatted Strings)
Concept: F-strings provide an easier way to combine text and variables. They start with the letter f before the opening quotation mark, and variables go inside curly braces {}.
Example:
name = "Taylor"
age = 15
print(f"{name} is {age} years old.")
Your Turn: Update your code to use f-strings instead of string concatenation.
# Your code here:
# Find these lines in your code and replace them:
print(f"Hello, {player_name}! Let's play a guessing game.")
print(f"You got it in {attempts} attempts! The number was {secret_number}")
print(f"Sorry, you've used all {max_attempts} attempts. The number was {secret_number}.")
Part 8: Putting It All Together
Now, let’s combine everything we’ve learned into one complete game. Copy and paste this complete example, then try running it:
import random
# Welcome the player
print("Welcome to the Number Guessing Game!")
player_name = input("What is your name? ")
print(f"Hello, {player_name}! Let's play a guessing game.")
# Set up the game
secret_number = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100...")
# Game loop
attempts = 0
max_attempts = 10
while attempts < max_attempts:
# Get player's guess
try:
guess_text = input("Enter your guess (1-100): ")
guess = int(guess_text)
attempts += 1 # This is shorthand for attempts = attempts + 1
# Check the guess
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"You got it in {attempts} attempts! The number was {secret_number}")
break
except ValueError:
print("Please enter a valid number!")
# Game over message
if attempts >= max_attempts:
print(f"Sorry, you've used all {max_attempts} attempts. The number was {secret_number}.")
Your Turn: Run the complete game and try to guess the number!
Challenge Extensions
If you finish early, try adding these enhancements to your game:
- Add difficulty levels that change the range of possible numbers
- Keep track of the player’s high score (lowest number of attempts)
- Give hints about how close the guess is (like “very close” or “way off”)
- Add colored text using the
coloramalibrary - Create a two-player version where one player enters the number
What You’ve Learned
Congratulations! You’ve learned several fundamental Python concepts:
- Variables and data types
- User input and output
- Importing libraries
- Random number generation
- Type conversion
- Conditional statements
- While loops
- String formatting
- Basic error handling
Motion Simulation – VPython and Physics with Coding
Today we will be exploring VPython and motion simulation.
INTRODUCTION TO VPYTHON
PowerPoint Presentation
SETTING UP TRINKET
Trinket is a free software we can use to write and run our code.
CODING IN VPYTHON
Introduction
VPython is a Python library that allows you to create 3D animations and simulations. Today, we will learn how to move an object using VPython.
Objectives
– Understand the basics of creating objects in VPython.
– Learn how to move objects using loops and updating their positions.
Starter Code
Click below to access the starter code on Glowscript.
Copy and paste the starter code from Glowscript into your Trinket account. When you run the code, you should see different shapes.
Now, complete the following exercises to learn more about VPython and it’s uses.
Basic Exercises
1. Creating a Basic Object
ball = sphere(pos=vector(0,0,0), radius = 0.5, color=color.red)
2. Moving the Object
To move the object, you will update its position in a loop. Here’s an example where the sphere moves along the x-axis:
while ball.pos.x < 5:
rate(10) # This slows down the loop to 10 iterations per second
ball.pos.x += 0.1 # Move the sphere by 0.1 units along the x-axis
Further Exercises
Exercise 1: Vertical Movement
Modify the code to make the sphere move vertically (along the y-axis) instead of horizontally.
Exercise 2: Diagonal Movement
Change the code so that the sphere moves diagonally. You can achieve this by updating both the x and y positions of the sphere.
Exercise 3: Bouncing Ball
Create a bouncing ball effect where the sphere moves up and down between two points on the y-axis.
Exercise 4: Controlled Movement
Use keyboard inputs to control the movement of the sphere. You can use the `scene.kb.getkey()` function to detect key presses.
Exercise 5: Create Movement Movies
Let’s create a short film that tells a story using everything that you have learnt so far.
INTRODUCTION TO MOTION SIMULATION
We will now create a physics simulation that simulates projectile motion. From a real world perspective, this is essentially creating a simulation to make predictions about where an object such as a shell or a missile will land.
Step 1:
Open a new VPython Project. Use your new knowledge from yesterday to create a ground, cannon, cannonball, and a target object.
Step 2:
Add the code for the movement of the cannonball. The sample code below shows an example of movement. However, it has the added component of a force being applied in the x-direction. When we think about a projectile though, the force will be in the y-direction because gravity will be the force acting upon it.
# This code moves a box on a surface under a constant force in the x-direction
from vpython import *
# Create a surface and a box
surface = box(pos=vector(0, -1, 0), size=vector(20, 0.1, 10), color=color.green)
moving_box = box(pos=vector(-5, 0, 0), size=vector(1, 1, 1), color=color.red)
# Initial velocity and acceleration
velocity = vector(0, 0, 0)
force_x = 2 # Constant force in the x-direction
mass = 1 # Mass of the box
acceleration_x = force_x / mass
# Time step
dt = 0.01
# Simulation loop
while moving_box.pos.x < 5:
rate(100)
velocity.x += acceleration_x * dt
moving_box.pos += velocity * dt
# Task: Adapt this code to move the cannonball with initial velocity components and gravity acting in the y-direction
Step 3:
We want to be able to follow the path of the projectile and so want to be able to leave behind a trail to show us how it flew. Use the below code to create that trail:
# This code moves a sphere in a line and leaves behind trail markers
from vpython import *
# Create a sphere
moving_sphere = sphere(pos=vector(-5, 0, 0), radius=0.2, color=color.red)
# Set initial velocity
velocity = vector(1, 0, 0)
dt = 0.1
# Simulation loop
for t in range(100):
rate(10)
moving_sphere.pos += velocity * dt
# Create a small sphere to mark the trail
trail_marker = sphere(pos=moving_sphere.pos, radius=0.05, color=color.yellow)
# Task: Adapt this code to leave behind a trail of the cannonball in projectile motion
Step 4:
We want the simulation to indicate when we have hit our target. Use the following code to create that in your projectile motion simulation:
# This code checks for a simple overlap between two objects
from vpython import *
# Create two objects
object1 = sphere(pos=vector(0, 0, 0), radius=0.5, color=color.red)
object2 = box(pos=vector(1, 0, 0), size=vector(1, 1, 1), color=color.blue)
# Check for collision (overlap) between object1 and object2
if abs(object1.pos.x - object2.pos.x) < (object1.radius + object2.size.x/2):
print("Overlap detected!")
# Task: Adapt this code to check for collisions between the cannonball and the target
Step 5:
Finally we want to create inputs so that we can ask the user to make decisions about the velocity and angle of launch for the projectile so that they have some control over its path. Use the following code as a basis for creating those inputs:
# This code asks for user input to control the movement of an object
angle = float(input("Enter the launch angle (in degrees): "))
power = float(input("Enter the power level (1-10): "))
print(f"Launching at {angle} degrees with power {power}")
# Task: Adapt this code to calculate the initial velocity components for the cannonball
Step 6:
Put all of the sections together to create your simulation of projectile motion.
Day 3: Arduino
INTRODUCTION TO ARDUINO
The Arduino is like a mini computer that we can program to power and control devices such as LEDs, motion sensors, and motors. The presentation below shows the basic equipment you will use with the Arduino.
PowerPoint Presentation
CHALLENGE 1: BUILDING YOUR FIRST CIRCUIT
Build a circuit that provides power to an LED lightbulb using the Arduino, a breadboard, an LED, and a resistor. Use the worksheet below to help you.
Arduino LED Worksheet
Bonus Challenge: Replace the single bulb LED with an RGB LED which includes a red, green, and blue bulb. Remember to update the code so that you can program all three colours.
CHALLENGE 2: CREATING A MORSE CODE MACHINE
Morse code is a system of communication that involves using dots (short pulses) and dashes (long pulses) to convey a message involving letters or numbers
Using the circuit you built in Challenge 1, program the LED to communicate a short message of your choice in Morse code.
You will need to create a function for dots (short pulse) and dashes (long pulse). Then, you can use the morse code alphabet in the Arduino LED worksheet (found on page 3) to help you communicate your message.
Arduino LED Worksheet
Bonus Challenge: Add a button to your breadboard circuit. When the button is pressed, the LED should start blinking the morse code message. Remember the button will require power, grounding, and a digital pin connection.
CHALLENGE 3: USING THE SERVO MOTOR
A servo motor is a small motor that can rotate at a specific angle. To set up the motor, follow the instructions in the worksheet below.
Arduino Servo Worksheet
Day 4: Data Visualisation
We will taking a quick journey through the world of data visualization to examine how coding can be applied to large data sets and used as a tool to answer different research questions. In the following presentation we talk briefly about data visualization:
CHALLENGE 1: POKéMON DATASET
Step 1: Setting up environment
We will be using a different online platform this time called Google Colab. Click below to open Google Colab.
In Google Colab, create a new notebook. Install the necessary libraries (pandas and matplotlib). Use the code below to help you.
# Install pandas and matplotlib
!pip install pandas matplotlib
# Define a function to greet the user
def greet(name):
return f"Hello, {name}!"
# Test the function
print(greet("Student"))
Step 2: Accessing the Dataset
In order to learn about data manipulation and visualization, we will examine a Pokémon dataset. Click below to download the dataset.
Step 3: Loading, Inspecting, and Cleaning
The first steps of working with a data set include loading, inspecting and cleaning. Firstly, load the Pokémon dataset into a DataFrame. Then, perform basic inspection and cleaning using the code below.
import pandas as pd
# Load the Pokémon dataset
# Note: Update this URL to point to your actual dataset location
df = pd.read_csv('Pokemon_Data.csv')
# Display the first few rows and basic statistics
print(df.head())
print(df.info())
print(df.describe())
Step 4: Data Manipulation
We want to be able to:
- Select and filter data.
- Handle missing values.
- Convert data types if necessary.
The following code demonstrates some of the basics we can do around data manipulation with some starter code demonstrating how it is done.
# Select specific columns (Name, HP, Attack, Defense, Speed)
df_selected = df[['Name', 'HP', 'Attack', 'Defense', 'Speed']]
print(df_selected.head())
# Filter Pokémon with HP greater than 100
df_high_hp = df_selected[df_selected['HP'] > 100]
print(df_high_hp.head())
# Handle missing values by dropping rows with any missing values
df_cleaned = df_selected.dropna()
print(df_cleaned.info())
# Convert 'HP' column to integer type if necessary
df_cleaned['HP'] = df_cleaned['HP'].astype(int)
print(df_cleaned.dtypes)
Challenge Time
Having developed some basic skills around manipulating and cleaning it is now time for some challenges.
Challenge 1:
- Select and display the ‘Name’ and ‘Weight_kg’ columns.
Challenge 2:
- Filter Pokémon with speed greater than 80.
Challenge 3:
- Convert the ‘attack’ column to integer type.
Step 5: Basic Analysis and Visualization
We will now look at some basic analysis like averages and then some initial visualizations of data using tools like histograms, bar charts, and scatter plots to communicate information about the data.
The following code helps lay the foundation for this type of analysis and communication.
import matplotlib.pyplot as plt
# Calculate the average HP, Attack, and Defense
avg_stats = df[['HP', 'Attack', 'Defense']].mean()
print(avg_stats)
# Create a histogram of the 'HP' column
plt.figure(figsize=(10, 6))
plt.hist(df['HP'], bins=20, edgecolor='k')
plt.title('Distribution of Pokémon HP')
plt.xlabel('HP')
plt.ylabel('Frequency')
plt.show()
# Create a bar chart of the top 10 Pokémon by 'Attack'
top_10_attack = df.nlargest(10, 'Attack')
plt.figure(figsize=(10, 6))
plt.bar(top_10_attack['Name'], top_10_attack['Attack'], color='skyblue')
plt.title('Top 10 Pokémon by Attack')
plt.xlabel('Pokémon')
plt.ylabel('Attack')
plt.xticks(rotation=45)
plt.show()
# Create a scatter plot of 'Attack' vs 'Defense'
plt.figure(figsize=(10, 6))
plt.scatter(df['Attack'], df['Defense'], alpha=0.5)
plt.title('Attack vs. Defense')
plt.xlabel('Attack')
plt.ylabel('Defense')
plt.show()
Challenge Time
Challenge 1:
- Calculate the average ‘speed’ of Pokémon.
Challenge 2:
- Create a histogram of the ‘attack’ column.
Challenge 3:
- Create a bar chart of the top 10 Pokémon by ‘defense’.
Challenge 4:
- Create a scatter plot of ‘speed’ vs ‘hp’.
CHALLENGE 2: MOVIES DATASET
Now, we want to take what you were doing in the previous section in relation in Pokémon and apply what you have learnt to a different data set. So for the movie data set which can be found here do the following:
Step 1: Setting up the Environment
Task 1: Upload the movie ratings dataset to Google Colab.
Task 2: Load the datasets into DataFrames.
Task 3: Inspect the DataFrames to understand the structure of the data.
Step 2: Data Manipulation and Cleaning
Task 1: Merge the ratings and movies DataFrames on the movieId column.
Task 2: Handle any missing values by dropping rows with missing data.
Task 3: Convert the rating column to float type if necessary.
Step 3: Analysis and Visualisation
Task 1: Calculate the average rating for each movie.
Task 2: Calculate the number of ratings for each movie.
Task 3: Create a histogram of the movie ratings.
Task 4: Create a bar chart of the top 10 movies by average rating.
Task 5: Create a bar chart of the top 10 movies by the number of ratings.
Step 4: Final Stretch Tasks
For the final task related to data visualization use the data set to answer and visualize a unique question that you are interested in investigating.
For example, maybe you want to investigate the realities of the “six degrees of Kevin Bacon” game through a network or investigate genre popularity over time or find the top actors as ranked by number of highly rated movies. Just think of a movie related question that can answered by the data set and the educators will help you to think about how you might investigate it.
Day 5: Data Visualization – Research Poster
Data Visualization Journey: From Kaggle to Graph A Self-Guided Worksheet Overview In thisactivity, you’ll select a dataset from Kaggle that interests you, download it, explore the data, performbasic cleaning, and create a meaningful visualization. This worksheet provides minimal guidance tohelp you develop your independent data analysis skills.
You can create your poster as one slide in this presentation, it has been formatted for the paper size we will be printing which is A3: Click here for poster document.
Part 1: Finding and Downloading a Dataset (10-15 minutes)
Visit Kaggle: Go to kaggle.com and create an account if you don’t have one. Browse
Available Datasets: Use the search bar or browse by topic. Some beginner-friendly dataset categories include: Sports, Entertainment, Social issues, Food and nutrition Environment.
Select a Dataset: Choose one that:
Has a clear description Isn’t too large (preferably under 10MB for this exercise) Has good reviews or many downloads. Contains at least one numerical column you can visualize.
Download the Dataset: Click the download button and save it to your working directory.
Identify Your Research Question: What specific aspect of this data do you want to visualize? Write it down.
# Import necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load your dataset (adjust the filename to match your downloaded file)
df = pd.read_csv('your_dataset.csv')
# Explore the structure of your data
# How many rows and columns?
print("Dataset shape:", df.shape)
# What columns are available?
print("\nColumns in the dataset:")
print(df.columns.tolist())
# View the first few rows
print("\nFirst 5 rows:")
print(df.head())
# Check data types and missing values
print("\nDataset information:")
df.info()
# Get summary statistics for numerical columns
print("\nSummary statistics:")
print(df.describe())
# Check for missing values
print("\nMissing values by column:")
print(df.isnull().sum())
# Now clean your data to prepare for visualization
# Create a working copy of your data
clean_df = df.copy()
# Rename any columns if needed for clarity
# Example: clean_df = clean_df.rename(columns={'old_name': 'new_name'})
# Handle missing values based on what makes sense for your data
# Option 1: Remove rows with missing values
# clean_df = clean_df.dropna(subset=['column_name'])
# Option 2: Fill missing values (with mean, median, or a specific value)
# clean_df['column_name'] = clean_df['column_name'].fillna(clean_df['column_name'].mean())
# Convert data types if needed
# Example: clean_df['column_name'] = pd.to_numeric(clean_df['column_name'], errors='coerce')
# Filter data if necessary (remove outliers or focus on a subset)
# Example: clean_df = clean_df[clean_df['column_name'] > 0]
# Check the results of your cleaning
print("Shape after cleaning:", clean_df.shape)
print("Missing values after cleaning:", clean_df.isnull().sum())
# Option A: Bar Chart
# Prepare your data (example: top 10 items by some measure)
# This is just an example - modify to fit your specific data
sorted_data = clean_df.sort_values('value_column', ascending=False)
top_data = sorted_data.head(10)
# Create the bar chart
plt.figure(figsize=(10, 6))
bars = plt.bar(top_data['category_column'], top_data['value_column'], color='skyblue')
# Add data labels on the bars
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.1,
f'{height:.1f}', ha='center', va='bottom')
# Add labels and title
plt.title('Your Title Here')
plt.xlabel('X-Axis Label')
plt.ylabel('Y-Axis Label')
plt.xticks(rotation=45, ha='right') # Rotate labels if needed
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
# Option B: Line Chart
# Prepare your data
# Assuming you have a column with dates and a value to plot
time_data = clean_df.sort_values('date_column')
# Create the line chart
plt.figure(figsize=(12, 6))
plt.plot(time_data['date_column'], time_data['value_column'], marker='o', linestyle='-')
# Add labels and title
plt.title('Your Title Here')
plt.xlabel('Time Period')
plt.ylabel('Value')
plt.grid(True, linestyle='--', alpha=0.7)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Option C: Scatter Plot
# Create the scatter plot
plt.figure(figsize=(10, 6))
plt.scatter(clean_df['x_variable'], clean_df['y_variable'], alpha=0.6)
# Add labels and title
plt.title('Relationship Between X and Y')
plt.xlabel('X Variable')
plt.ylabel('Y Variable')
plt.grid(True, linestyle='--', alpha=0.7)
# Optional: Add a trend line
# from scipy import stats
# slope, intercept, r_value, p_value, std_err = stats.linregress(clean_df['x_variable'], clean_df['y_variable'])
# x = clean_df['x_variable']
# plt.plot(x, intercept + slope*x, 'r', label=f'y={slope:.2f}x+{intercept:.2f}')
# plt.legend()
plt.tight_layout()
plt.show()
Option D: Your Custom Visualization
Feel free to create a different type of visualization that better suits your data and research question!
Analyzing Your Visualization
Now that you’ve created your visualization, analyze what it shows:
What is the main pattern or trend visible in your visualization?
Are there any outliers or surprising values?
What might explain them?
How does this visualization help answer your original research question?
What additional visualizations might provide further insights?
Bonus Challenge: Enhance Your Visualization
If you have time, try one or more of these enhancements:
Add a second data series to compare two related measures
Create a subplot with multiple related visualizations
Use color to represent an additional dimension of data
Add annotations to highlight key points in your visualization
Create an interactive visualization using a library like Plotly