Fetching console data in Python Video

Fetching console data in Python

Jeremiah Taguta (BSc in Computer Science, Masters in Information Systems)
Published on 13-05-2023
Fetching Different Types of Data from Console in Python: A Comprehensive Guide


Python is a popular programming language for a wide range of applications, including data science and machine learning, as well as web development and scripting. The ability to connect with users via the console is a vital feature of any programming language. This blog post will go over how to get numerous types of data from the console in Python, such as texts, integers, and floats. I will also showcase how we can derive other data types from a fetched string input. I assume you know how to do type casting; if not, see my type casting article.

Programs need to be receptive to user input and thus operate within the user's environment. Rarely do programmers know all the values a user might need to use in a program, so the program needs to be flexible and operate with users' data and not programmer data.

I must also stress that for practice purposes, we are using the terminal or console as the user interface but there are many interfaces which can be used to interact with the program including GUI and Python can build such interfaces. Whether GUI or console, the business logic remains the same hence the algorithms are the same.

We shall look at how to use the input() function to get data from the console. By default, the input() function fetches a string from the console. It can display a prompt or message if such is provided in parentheses.

1. Fetching Strings

As I said earlier on, the input function fetches a string from the console. See below example

1 name = input()
2 print("Hello " + name)
In the previous example, the users does not know what to do, when the program runs, all they see is a blank screen on the console. This is not good practice, as the program may need to receive input or the desired input. This raises the need for prompting the user to use the inbuilt printing feature of the input function.

I must stress that the prompt needs only one value so formatting might be necessary to create a single value, probably a string, but we will do that later.

In the next example, we will fetch a name through with a prompt in line 1. The user will see a prompt "Enter your name: " thus they are directed to act.

1 user_name = input("Enter your name : ")
2 print("Hello " + user_name)
2. Fetching Integers

To fetch an integer using the input () function is not possible. We have to fetch a string number, then we cast it explicitly to an integer using the int() function. In the example below, line 2 output shows that input is string class while after conversion object type will be int in line 4. If the input fetched can't be cast to an integer, an error will be generated.

Take a look at the type of fetched value in the next example. The input fetched from line 1 can't be used for age calculation as we can't do arithmetic operations with strings hence the need to convert it to an integer.

We shall use an age calculator for this example, fetching the user's year of birth (line 1), converting it to an integer (line 3), fetching the current year (line 6) and subtracting the year of birth (from the current year (line 6)) from the age and displaying the result (line 7)

1 year_of_birth = input("Enter your year of birth : ")  #  fetch string age value
2 print("Type fetched :", type(year_of_birth))
3 year_of_birth = int(year_of_birth)  # convert string value in age to int
4 print("After conversion value :", type(year_of_birth))
5 current_year = int(input("Enter current year : "))  # fetch current year and immediately convert to string
6 age = current_year - year_of_birth
7 print("You are", age, "years old")
3 Fetching Floats

A string input from the console can be cast to a float using the float() function. If the user input is not a number an error will be generated.

We are going to redo the temperature convertor program but this time using user-defined Fahrenheit temperature values. The temperature takes continuous values so the float is a suitable object or data type. In line 2, we are fetching a string with a temperature value and immediately casting it to float. We then convert the temperature to Celsius.

1 multiplier = 5/9
2 temp_fahren1 = float(input("Enter the Fahrenheit temperature :"))
3 temp_celc1 = (temp_fahren1 - 32) * multiplier
4 print(temp_fahren1,"°F = ", temp_celc1,"°C")

4. Fetching more than one value

In Python, we can fetch more than one value as a string with substrings separated by a seperator.

a. Separated by space

In the example below, the user input should be a string of animals separated by space. The space may be used as a separator when creating a list of substrings using the string split() method.

The split method returns a list with substrings as separated by separator being list elements. In the parenthesis, the separator should be put. In our case, the separator is space so we don't put anything as a split method argument.

In line 2, we see the type as a string but after using the split method on the string, data becomes a list type as seen on line 5 and the list is shown as output in line 6 below.

1 animals = input("Enter animals names separated by space :") # space is separate
2 print("Input type :",type(animals))
3 print("User input :", animals)
4 animal_list = animals.split()
5 print("Type after split :",type(animal_list))
6 print("Animal list :", animal_list)

b. Separated by #

In the below example, we are using # as the separator, try using a separator of your choice. Anything not separated by # becomes a single element of the returned list.

The separator to be used by the user on input is a string '#' thus we have to put a string, '#', in our split method as an argument as seen in line 3 below,

1 cities = input("Enter names of cities separated by # :")
2 cities_list = cities.split("#")
3 print("Cities list :", cities_list)

5. Fetching a Set

Because the string split method returns a list, if you want a set or tuple you may cast as discussed in the previous casting article. Now, let's fetch a string of numbers separated by ",". We have to cast the returned list to set as shown in line 3 below. The type before casting is a string in line 2 and after casting is a set in line 4 outputs.

Take note, it's still a set of substrings or numbers in quotes. To individually convert the set or list elements is beyond the scope of this article. We shall do that in future articles.

1 nums= input("Enter nums sep by , :")
2 print("input type :", type(nums))
3 nums_set = set(nums.split(","))
4 print("Type after conversion :", type(nums_set))
5 print("The set :", nums_set)

We have now covered the principles of retrieving various forms of data, such as texts, integers, and floats, from the terminal in Python. This understanding can be applied to the creation of interactive terminal programs that can fetch and manage a variety of user input.

Thanks for reading. If you have any questions, feel free to ask in the comments section, I'll gladly help. Check out my programming tutorials on YouTube and don't forget to subscribe, comment, like, and share on both YouTube and on this Blog. Lets code together!!!

201 Like

Drop your comment

© Copyright 2023 Jeremiah Taguta. All Rights Reserved.

Product of ‌

Jeremiah Taguta T/A Charis Technologies