2.1. Ch 3 Practice: Statements and Variables#

Choose Social Media Platform: Reddit | Discord | Bluesky

This Python Notebook is a chance for you to try out the programming concepts we have covered thus far.

As we mentioned previously in the first bot demo (2.3.8), in order to run the code, you can look for the rocket button at the top which will give you an option to “launch binder”

screenshot of this page in the online textbook, with the launch binder link highlighted under the rocket button at the top.

If you launch binder, it will take a while to load, but eventually show you a version of this page Jupyter Notebook in a code editor called Jupyter Lab

a screenshot of this page viewed in jupyter_lab, with menus and options above the editable page

In Jupyter Lab you can double click any section to edit it, and you can press the triangle “run” button to run the code (or display the text).

a screenshot of this page viewed in jupyter_lab,with the triangle "run" button circled. Next to it are a square "interrupt the kernal" button and other options

When the code runs, the little number to the left of the code block should change. There might also be some output from your action displyed below the code block.

So now you can go through the rest of this page and try out the practice exercises for yourself!

2.1.1. Variables#

You will first practice saving values into variables. Remember, the way we save a value into a variable is like this:

variable_name = value

First, save the piece of text “I am writing a computer program!” into a variable called my_progress

my_progress = "I am writing a computer program!"# TODO: enter your code here

Viewing variables in the debugger#

Before we continue, we are going to show you how to open the debugger so you can see what is being saved in your variables.

On the tp right of this tab, press the small bug icon to “enable debugging”:

screenshot of this tab in jupyterhub, with the "enable debugging" icon circled at the top right (after the "git" option and before the "Python 3 (ipykernel)" option)

Then, if you did the step above correctly, you should see the variable my_progress with the value “I am writing a computer program!” next to it:

screenshot of this tab in jupyterhub, with the debugger tab opened on the right. The top section of that tab is variables, which has "special variables" then "function variables" then "my_progress:I am writing a computer program"

Practice number variables#

First, write and run a line of code to save the value 5 into a variable named number_of_pies

number_of_pies = 5

Now, save the value 12.5 into a variable named cost_per_pie

cost_per_pie = 12.5

Now make a new variable called total_pie_cost and save into the value of the number_of_pies multiplied by the cost_per_pie.

Note: In python (and many programming languages), the symbol for multiply is *

total_pie_cost = number_of_pies * cost_per_pie

Now use the display function to display what is saved in total_pie_cost

display(total_pie_cost)
62.5

More variable practice#

Now, make a new variable called first_name and assign your first name to it

first_name = "Kyle"

Now, make a variable calles last_name and save your last name to it

last_name = "Thayer"

Create a variable called age and assign your age to it.

age = 38

~ A year goes by ~

Increase the age variable by 1.

age = age + 1

Now write three lines of code, with each line using display to show what is saved in first_name, last_name, and `age

display(first_name)
display(last_name)
display(age)
'Kyle'
'Thayer'
39

2.1.2. Sleep#

In order to use sleep, we must first import it from the time library

from time import sleep

Now try displaying 5 messages of your choosing, with some pauses between each one:

display("message 1")
sleep(.01) #I am making these pauses small to make the book build faster
display("message 2")
sleep(.02)
display("message 3")
sleep(.01)
display("message 4")
sleep(0.05)
display("message 5")
'message 1'
'message 2'
'message 3'
'message 4'
'message 5'

2.1.3. Discord Bot Practice#

Now lets try a Discord bot with variables and sleep!

Load Discord Library#

First, we need to load the discord library

# Load some code called "discord" that will help us work with Discord
import discord

# Load another library that helps the bot work in Jupyter Noteboook
import nest_asyncio
nest_asyncio.apply()

(Optional) Step 1b: Make a fake discord connection with the fake_discord library#

For testing purposes, we’ve added this line of code, which loads a fake version of discord, so it wont actually connect to Discord. If you want to try to actually connect to Discord, don’t run this line of code.

%run ../../fake_apis/fake_discord.ipynb
Fake discord is replacing the discord.py library. Fake discord doesn't need real passwords, and prevents you from accessing real discord

Step 2: Set up your Discord connection#

To use this on your real Discord account, copy your discord token into the code below, replacing our fake passwords.

# Set up your Discord connection
# TODO: put the discord token for your bot below
discord_token = "m#5@_fake_discord_token_$%Ds"
client = discord.Client(intents=discord.Intents.default())
Fake discord is pretending to set up a client connection

Practice 1: Define and run a bot that will post to Discord#

These are the steps your bot will take when it loads (get the channel, post a message, and shut down). If you want to post on an actual Discord channel you will have to replace the fake channel_id below with your real channel id (see the making bot instructions)

Where the code says: # TODO: put the message you want to post to discord below, put code to post your message there with something like: channel.send("This post was made by a computer program!")

# Provide instructions for what your discord bot should do once it has logged in
@client.event
async def on_ready():
    # Load the discord channel you want to post to
    # TODO: put the discord channel id number below
    channel_id = 123456789
    channel = client.get_channel(channel_id)

    # Post a message to your discord channel
    channel.send("I found a way to solve the practice problem from the answer key!")
   

    # Tell your bot to stop running
    await client.close()
    
# Now that we've defined how the bot should work, start running your bot
client.run(discord_token)
Fake discord bot is fake logging in and starting to run
C:\Users\kmthayer\AppData\Local\Temp\ipykernel_40768\2351957123.py:10: RuntimeWarning: coroutine 'FakeDiscordChannel.send' was never awaited
  channel.send("I found a way to solve the practice problem from the answer key!")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Fake discord bot is shutting down

Practice 2: Define and run a bot that will post from a variable#

Now try saving a piece of text in a variable for the title, and another for the content of a post, and then submitting a post of whatever you saved in the variables.

To do this, save text in a variable (with a line of code like: post_variable = "This message is stored in a variable").

Then copy below that the code from Practice 1, but instead of making the posting code like await channel.send("This post was made by a computer program!"), instead use the variable like await channel.send(post_variable)

(note, you can call your variable whatever you want instead of post_variable, just make sure you call it the exact same thing in every place you use it)

post_variable = "I can store a message in a variable and use that"

# Provide instructions for what your discord bot should do once it has logged in
@client.event
async def on_ready():
    # Load the discord channel you want to post to
    # TODO: put the discord channel id number below
    channel_id = 123456789
    channel = client.get_channel(channel_id)

    # Post a message to your discord channel
    await channel.send(post_variable)
   

    # Tell your bot to stop running
    await client.close()
    
# Now that we've defined how the bot should work, start running your bot
client.run(discord_token)
Fake discord bot is fake logging in and starting to run
Fake Discord is pretending to post:
I can store a message in a variable and use that
Fake discord bot is shutting down

Submit multiple posts#

Next try submitting 3 posts, but use sleep to add pauses between each one (note that discord might limit how often you post, so you can sleep for 60 seconds or more before posting again).

To do this, copy the code from Practice 1, but instead of one line with await channel.send(...), make multiple lines with await channel.send() and add some lines with sleep in between.

# Provide instructions for what your discord bot should do once it has logged in
@client.event
async def on_ready():
    # Load the discord channel you want to post to
    # TODO: put the discord channel id number below
    channel_id = 123456789
    channel = client.get_channel(channel_id)

    # Post messages to your discord channel
    await channel.send("This is the first message")
    
    sleep(.01) #note: I am using short times since these pauses slow down compiling the book
    
    await channel.send("This is the second message")
    
    sleep(.02)
    
    await channel.send("This is the third message")

    # Tell your bot to stop running
    await client.close()
    
# Now that we've defined how the bot should work, start running your bot
client.run(discord_token)
Fake discord bot is fake logging in and starting to run
Fake Discord is pretending to post:
This is the first message
Fake Discord is pretending to post:
This is the second message
Fake Discord is pretending to post:
This is the third message
Fake discord bot is shutting down