Exercises
Let's try integrating what you've learned so far and implementing some fun programs! Before you try these exercises, make sure you've read through all the specified chapters. Don't forget to try implementing them yourselves before reading our solutions!
Exercise 1: Trump's Tweets
Prerequisites: variables, functions, datatypes, operations, and conditionals.
US President Donald Trump is known for, among other things, publishing hilarious messages on Twitter and having great hair.
In this exercise, we want to write a function that allows the user to input a question and randomly returns a Trump tweet in response.
To do so, we'll be introducing two new functions: input()
and the random
library.
input()
is used in Python to obtain a response from the user through the command line.
What we put between the brackets gets printed to the console, and what we type afterwards will be read into Python.
Run the following code and test it out! Enter your name into the dialogue box that appears in your browser.
The random
library in Python is used to generate random values.
This is very useful in game design and probability tests.
For our purposes, it will be useful in imitating how President Trump acts online, i.e. with seemingly no predictability whatsoever.
To use it, you'll have to include the line import random
at the top of your code.
This allows us to access the library.
Below is a function that randomly prints a number between 1 and 10.
Run it a few times to see that it does indeed randomly print a number!
Armed with these two functions, we are now ready to complete this exercise.
First, let's write the function tweet()
that does not take in any arguments and simply randomly returns a tweet.
You can search online to find some of Trump's famous tweets--copy 5 of them and try completing this function!
Next, write the function provoke_the_orange()
that first prints out a short description of what this exercise is about,
then asks the user to write a question for President Trump, and lastly calls our tweet()
function to generate a response.
Take some time to think about how you want to approach this before moving on, and remember that you can test your code in VS Code.