SAY WHAT? Diving deeper into Input

--Originally published at Coding The Future

Image via GIPHY

Sometimes people say things I don't understand. However, when programming, understanding what a user is telling you is vital in order for a program to work.

In my last post, I talked briefly about the general syntax in Python 3, but this time I wanted to focus especially on user input, because I left this information incomplete last time. Let's get going!

Basic user input

Let's recall what we learned last time. When we ask a user for input, we can ask for several times of input. The most common ones are strings, which is just text; integers, which are numbers with no decimals, and floats, which are numbers with decimals.

Strings

When asking a user for input, the first thing that needs to be done is to declare a variable where the input will be stored. In the code below, a new variable called userName is declared, and then the input class is called. The text inside of the bracket is the prompt for the user to enter their name.

userName = input("What's your name? ")

Integers and Floats

Some times, input may include numbers, and even though they can be inputed as a string, they cannot be "treated" like numbers in that situation. In other words, let's say you are asking the user for their age and it will be stored in a variable called userAge, and then you want to add 10 to the value inputed. If the user input is stored in a string-type variable, you will not be able to add text to a number. For this reason, we have to specify that the input will be of type integer. To do this, you need call the int class and insert the input class within it.

userAge = int(input("How old are ? "))
userAgeInTenYears = userAge + 10

In another example, let's say you want to ask the user to enter a number that include decimals. To do this, you need call the float class and do the same we did for integers.

userMath = float(input("How much is 5 / 2? ")

Deciding what type of input you need depends just on what you want to do with it. If all you need is to print, don't complicate yourself and just use the input class.

Last, but not least, I want to thank Jared, because I learned how to declare int and float type input thanks to his awesome blog post. Please go show him some love and check out his blog!

That's all for today. Until next time!
@emamex98