Input() function

1. The print() function sends data to the console, while the input() function gets data from the console.

2. The input() function comes with an optional parameter: the prompt string. It allows you to write a message before the user input, e.g.:

 

3. When the input() function is called, the program’s flow is stopped, the prompt symbol keeps blinking (it prompts the user to take action when the console is switched to input mode) until the user has entered an input and/or pressed the Enter key.

 

NOTE

The input() function can be used to prompt the user to end a program. Look at the code below:


 

4. The result of the input() function is a string. You can add strings to each other using the concatenation (+) operator. Check out this code:

 

5. You can also multiply (* ‒ replication) strings, e.g.:

Type casting

Python offers two simple functions to specify a type of data and solve this problem – here they are:

and

Their names are self-commenting:

  • the int() function takes one argument (e.g., a string: int(string)) and tries to convert it into an integer; if it fails, the whole program will fail too (there is a workaround for this situation, but we’ll show you this a little later);
  • the float() function takes one argument (e.g., a string: float(string)) and tries to convert it into a float (the rest is the same).

Type conversion: str()

This type of conversion is not a one-way street. You can also convert a number into a string, which is way easier and safer ‒ this kind of operation is always possible.

A function capable of doing that is called str():


 

Exercise 1

What is the output of the following snippet?

55

 

Exercise 2

What is the expected output of the following snippet?

<class 'str'>