Python Basics: 06 taking user input

Basic taking user input

Suwes Muhammad Hafiz
2 min readMar 5, 2022

Taking user input is usually used for command-line interface (CLI) based programs, and graphical user interfaces (GUI), which function to retrieve data that is user input.

Retrieving user input data in python is basically very easy.
The syntax used is also not too complicated

let’s try to take the user input data in our program.
Create a program containing

data = input(“Enter data = “)
print(“data contains = “,data)

this syntax, we can retrieve data from user input into data variables

but there is one problem, let’s add this line of code below it
print(“This data type is = “,type(data))

Then we will see the data type of the data variable, namely str or string. Then what if we want to take user input in the form of numbers?

How to casting the user input

data_number = int(input(“Enter number =”)
print(“Enter number of data is = “, data_number)

and print(“This data type is = “,type(data_number))

Then we will see that the data_number variable will have an integer data type. The same goes for retrieving data in float type.

Then what about boolean?

To retrieve the boolean data type is slightly different from other data types, because boolean only has an output of true or false. let’s pay attention when we want to take user input of type boolean data

data_bool = bool(input(“Enter a boolean value = “))
print(“data = “ , data_bool)

Run it, when we enter data for example the number 1, the output will be true, when we enter the number 0, which should be false is still true. Then how so that this data_bool can produce false output?

The trick is to cast user input into an integer first so that it can read the value 0 from the integer data.

data_bool = bool(int(input(“Enter a boolean value = “)))
print(“data = “ , data_bool)

Then run it, when we enter the number 1 it will output true, now we try to enter the number 0, then now the data_bool the variable will produce the value false. This happens because we have cast the data that the user input into an integer.

--

--