Astronomy Hour of Code

Activity 4: Getting user input


In this activity, we are going to learn how to ask the user a question and assign their answer to a variable. After we put a value in the variable, we will output the contents of the variable to the output window. This requires two lines of code. In the first line, create a text variable called telescope and then use the input function to ask the user a question. A function in a programming language is like a "mini program" that accepts a value from your program and then returns a value to your program after it runs. The value that your program provides to the function is called a parameter and it must be inside parenthesis.

In this case, the input function will accept a text value from your program and then create a dialog box on the user's screen with your programs text value, a box for the user to type some value and buttons for "OK" and "cancel". When the user clicks the "OK" button, the value that she typed in the box is returned to your program.

Remember to use quotation marks around your text inside the parenthesis so that the computer knows you are sending a text value to the function.

In our program we will assign the value returned from the input function to a text variable called telescope like this:

text telescope = input("What telescope would you like to use?")

On the next line, use the output command to display the user's answer like usual:

output telescope

Now you are ready to select the green Run Program button below the editor on the right (second in the tab order).

Exploration Challenge (Optional):

Modify your output statement so that the computer outputs a more user-friendly response. You can do this by inserting a text string in your statement and then adding the telescope variable with a + sign similar to the previous Exploration Challenge. For example, if the user answered the input question with the telescope Yerkes-41, make the computer output the line: You have selected the telescope Yerkes-41.

Next Tutorial

In the next tutorial, we will discuss Astronomy Hour of Code | Activity 0, which describes Accessible astronomy themed Hour of Code.