User Input in Python with GUVI Codekata — A Competitive Programming Guide

Like every other programming language be it C, C++, or Java we start our journey in programming with a simple “Hello World!”. This statement is often used to illustrate the basic syntax of a programming language. Moving forward, we learn how to create interactive programs which would be able to modify the results based on user requirements. This process of interaction is crucial for a program to be capable of solving problems. In this blog, we would learn the basics of user-program interaction and how we can accomplish that in terms of Competitive Programming.

Source: Tyler Lastovich from Pexels

Competitive Programming is a type of “Mind Sport” involving participants trying to program according to some provided specifications and constraints. Competitive Programming generally involves the host presenting a set of logical or mathematical problems to the contestants, and the contestants are required to write computer programs capable of solving these problems. Programmers require a multitude of skills to successfully tackle these problems like:

  • Reading the Data — User Input**
  • Basic Maths
  • Algorithms and Analysis
  • Typing and Formatting

** In this blog, we shall focus solely on how we take various tyops of inputs in Python Programming using Pythons inbuilt function input()

GUVI — Codekata

Codekata — An exercise in programming which helps programmers hone their skills through practice and repetition. GUVI provides the platform of CODEKATA containing a series of programs curated by experts from the industry. The platform provides a wide variety of sections to start working on your programming skills and rinse and repeat the basics. Practicing with Codekata will take your coding skills to the next level. GUVI helps you become a better programmer working on Codekata and solving problems.

User Input in Python

Being able to read input is a major part of any competitive programming problem. User inputs make the program interactive and able to work with any variation of the incoming data. Every programming language has its unique implementation of the input function. C has scanf(), C++ has cin >>, Java has Scanner, and Python being the simple user-friendly language has the function input().

For this guide, we will look into Python’s input() function and work with some diversified examples of its use case. Here, we’ll go through the various forms in which inputs are required in a program and how to obtain these required formats.

Input() Function — Python

Source: Giphy

Syntax

input([prompt])

The syntax for taking an input is fairly simple in python. With just input(), we are able to interact with our program. The syntax for input specifies an optional argument ‘prompt’ which can be used to display a message on the screen at the time of taking input. If the prompt argument is present, it is written to standard output without a trailing newline.

The following code snippet shows how an Input with Prompt displays the message before taking input from the user.

Note — An Input with or without prompt will work in exactly the same manner.

According to Python’s documentation of input(), the function reads a line from the input, converts it to a string (stripping a trailing newline), and returns that. This basically means that whenever we input anything from our keyboards to the input() function, Python converts it to string and returns the result as a string. This can be confirmed by using type() function in python.

This shows that even when we are trying to enter an integer value ‘20’, we still get a string by using input(). So the question is, How are we supposed to take different kinds of input when all Python does is return a string!? Well, let us look further into the different use cases of the input()function in python.

Integer and Float Input

Python does not provide a different input method to take in values like Integers and Floats. Rather, Python wants us to specify and convert the input as we wish using a method called Type-Conversion. Type Conversion basically involves the programmer explicitly stating the type in which the input should be converted on its arrival. Looking at the code snippet below, we can see how using functions like int() and float() can change how Python looks at the input.

We can see how the same input ‘10’ changes with the programmer explicitly specifying the type for the input. Whereas the default input still returns a string.

Multiple Input Values in a Single Line

Now that we know how to use input() in Python to read the User Input, we want to figure out a way to make our code compact so that we can read multiple values of input by using just a single instance of the input() function. We know that input stops reading the intake from the user when we press the Enter key. But what if the user wants to provides the complete input in a single line? Let us take an example:

If a user wants to enter their First Name and Last Name in a program and they give the input as “Divyansh Chaudhary” now if we try to read it with what we know so far, we might program it like:

In the above snippet, the user enters the complete name in one go. A program cannot understand whats it's not meant to understand, and therefore creates a single string of the complete name. The requirement of the problem was to have Python input the string in such a manner that we are able to gather the First Name in the variable first_name and the Last Name in the variable last_name. For this purpose, Python provides a simple solution — The function str.split(sep=None, maxsplit=-1).

The split() function returns a list of words in a string, using sep as the delimiter string. With the use of split() , we are able to take multivalue inputs in a single line:

Note — By default, str.split() splits a string on whitespaces. In Python, Lists, Tuples, Range, Set, and Dictionary can be split into different variables by assigning them to an equal number of variables.

List as an Input

It can happen that sometimes the programmer is not aware of the number of input values that a user might provide. In such cases, using Lists, the program is able to read an undefined number of input values. Now how do we implement Lists in our input function?

In case of String Input:

With a string input, we can again use the split() function to create a list of words. For Example, If the user wants to create a list of alphabets, they may write the code as:

Creating a “Python List” from a list of space-separated words can be useful in case we want to create an iterable to iterate over or we want to assign each value to a different variable as we did in our previous example.

In case of Integer Input:

Reading a list of space-separated Integers requires us to utilize another function of Python called map(function, iterable, ...). “Map” is an extremely useful function in Competitive Programming. It returns an iterator that applies the function to every item of iterable, yielding the results. This means that when we provide any function to the ‘function’ argument inside map, it creates an iterator ( a process of looping ) to continuously apply that ‘function’ over every element present inside the iterable ( Generally a Python List ). Let us take an example:

Suppose we want to find the sum of each number entered by the user. Without applying map() function, someone might write the code as:

This will output a TypeError because if we check the variable num_list by printing its value using print(num_list) we will find that the list of numbers is actually a list of strings ['1', '2', '3']. The function sum() cannot be applied over a list of strings. Therefore, we require a way to convert these strings to integers. One might think, we could just append int() while taking the input, let us see what happens then:

Here, again a TypeError is thrown saying that we cannot apply the function int() directly to a Python List. Instead, we need to use the map() function to be able to convert our numbers correctly like:

Here, map() is able to perform type-conversion on each string value present inside the list and return them as integers. The same method can be used to convert string values to float or to apply any other pre-defined or user-defined functions to a list or sequence of values.

Note — The use of list() in the above example. map() by itself returns a “map object” which needs to be converted back to Python List.

Multi-Line Input

Lastly, we might want to read an input that is provided using an undefined set of lines. Now, a multi-line input cannot be read by input() function directly because as soon as the user will press the Enter Key, the input will end and Python will only read the first line as input.

To create a program that can read a set of lines in a go, we use an infinite loop that terminates on a blank entry. To create an infinite loop, we can use while True:. For example, we want to create a list of States in India but we don’t know how many States the user wants to enter. We could use this method if the user wants to input a multi-line input:

Here, you will notice a few things:

  • The use of while True: The use of a while loop helps us create an infinite loop to iterate over the contents of the loop infinite times.
  • No prompt in input — Having a prompt inside an infinite loop will also cause the prompt to be displayed again and again, therefore to avoid that, we have used a separate print statement for the prompt.
  • if state: This statement checks if the variable that we used ( in this case state ) contains a value or is empty. If the variable has a value, then if statement is True otherwise, the is statement is False ( in this case when we pass an empty line i.e. press the Enter Key without an input ).
  • An empty line in the Output — The empty line > in the output marks the “end of input” from the user. This is where the break statement inside the else is executed and the loop ends.

Finally, the list of States is displayed to the user.

Source: Giphy

This blog provides an insight into the INPUT() function of Python. The guide describes the usage of different aspects of the INPUT() function. This is a guideline for anyone starting their journey in Competitive Programming or Python Programming. It is recommended to read more about the Built-in Functions of Python and other amazing things that Python can achieve.

Thanks for reading.
Don’t forget to click on 👏!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Divyansh Chaudhary

Divyansh Chaudhary

Machine Learning and Python Student. Coding Enthusiast. Pursuing Bachelors in Computer Science.