Python for Beginners 06: Basic User Input

Having looked in more detail at output, we are going to focus on user input this time. Basically, it is a revision of what we have applied in previous lessons already.

If you want the user to assign a value to a variable, you have to write

  1. the name of the variable
  2. the symbol for assigning a value to it (=)
  3. the function input()

You could leave the brackets of the input function empty, but this way, the user would not know what to enter. It makes more sense to write an instruction to let the user know what should be entered. Remember that when writing text, the data type is character or string and needs to be inside quotation marks “”.

When following this instruction, Python will consider the input to be a string. This means, that you cannot do any mathematical calculations with it even if the user enters numbers. If you do not want the data type to be string, you need to let Python know what data type you want using the functions for data type. For this, you have to change step 3 of the previous instruction: Instead, you write the data type’s function first, for example int() for integer, and then you put the input function inside the brackets of the data type’s function.

Now it’s time to practice:

Write a program that will prompt the user for a temperature in Fahrenheit and then convert it to Celsius. You may recall that the formula is C = 5 ∗ (F − 32)/9. Make sure that the resulting temperature is rounded to two decimals (Hint: Remember the last lesson).

The result may look like this:

#mastery06

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s