Astronomy Hour of Code

Activity 11: Creating a number variable from user input


There is another type of numeric variable with decimal places called a number. A number variable can hold a positive or negative numeric value or zero which can have decimal places. We can ask a user for a decimal number and cast the answer to a number variable in the same way we did with an integer previously by using the cast command, like this:

number seconds = cast(number, input("How many seconds: "))

On the next line, use the output command to display the variable's value:

output seconds

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

Exploration Challenge (Optional):

Notice that a number variable always displays at least one decimal point in an output statement. If you want to display the whole number without any decimal places, use cast to change the type of a number to an integer. Try different values when you run your program to see the result. Notice that the computer cuts off the decimal places, it does not round the number up, so 2.9 becomes 2 if you cast it to integer. (Hint: if you try to assign the cast variable back to a number variable, it will cut the decimal points off, but still display the number with zero in an output statement.

Next Tutorial

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