# Basic Input, Output in Python

For a program to be useful, it usually needs to communicate with the outside world by obtaining input data from the user and displaying result data back to the user. In this tutorial, you’ll learn about Python input and output.

Input may come from the user directly through the keyboard or from external sources like files or databases. Output can be displayed directly to the console or IDE, to the screen through a Graphical User Interface (GUI), or again to an external source.

### Reading Input From the Keyboard <a href="#reading-input-from-the-keyboard" id="reading-input-from-the-keyboard"></a>

To read input from the keyboard in Python, you can use the `input()` function. This function prompts the user to enter a value and returns it as a string.

Here's an example:

```python
name = input("Enter your name: ")
print("Hello, " + name + "!")

age = input("Enter your age: ")
print("You are " + age + " years old.")
```

In the above code, the `input()` function is used to capture the user's name and age. The entered values are then printed back to the console using the `print()` function.

When running this code, the program will display the respective prompts, wait for the user to enter their input, and then print out the provided values.

> **Note** that the `input()` function always returns a string, so if you want to use the input as a different data type (e.g., integer or float), you will need to cast it accordingly.

The statement `input()` always returns a string means that when you use the `input()` function to capture user input, the value returned will be in the form of a string data type.

If you require the user's input to be treated as a numeric type (such as an integer, float, or complex number), you need to convert the string to the appropriate type using the built-in functions `int()`, `float()`, or `complex()`.

Here's an example to illustrate this:

```python
age = input("Enter your age: ")
print("You entered:", age)
print("Data type of age variable:", type(age))

age_int = int(age)
print("Converted to integer:", age_int)
print("Data type of age_int variable:", type(age_int))

age_float = float(age)
print("Converted to float:", age_float)
print("Data type of age_float variable:", type(age_float))
```

In the code above, the user is prompted to enter their age using `input()`. The value entered by the user is stored as a string in the `age` variable. The program then prints the original value and its data type.

To convert the string `age` to an integer, the `int()` function is used, and the result is stored in the `age_int` variable. The program prints the converted value and its data type.

Similarly, the `float()` function is used to convert `age` to a floating-point number, which is stored in the `age_float` variable. Again, the program prints the converted value and its data type.

By using these conversion functions, you can ensure that the user's input is treated as the desired numeric type.

> **Note:** When working with Python 2.x code, there is a slight difference in the input functions compared to Python 3.
>
> In Python 2, `raw_input()` is used to read input from the keyboard and behaves like Python 3's `input()`.
>
> Python 2 also has a function called `input()`, which reads input, evaluates it as a Python expression, and returns the result.
>
> In Python 3, there is no direct equivalent to Python 2's `input()`. You can achieve a similar effect with `eval(input())`, but this poses a security risk as it allows users to run potentially harmful code.

#### `raw_input()` function in Python 2

In Python 2, the `raw_input()` function is used to read input from the user as a string. It behaves similarly to Python 3's `input()` function.

Here's an example to demonstrate its usage:

```python
name = raw_input("Enter your name: ")
print("Hello, " + name + "!")
```

In the above code, the `raw_input()` function prompts the user to enter their name. The entered value is stored as a string in the `name` variable. The program then prints a greeting message using the entered name.

Note that in Python 2, `raw_input()` always returns a string, regardless of the user's input. If you need to perform operations on the input as a numeric type, you will need to convert it using functions like `int()` or `float()`.

#### `input()` function in Python 2

In Python 2, the `input()` function reads input from the user, evaluates it as a Python expression, and returns the resulting value.

Here's an example to illustrate this:

```python
num = input("Enter a number: ")
result = num * 2
print("The result is:", result)
```

In the above code, the user is prompted to enter a number using `input()`. The entered value is then treated as a Python expression and evaluated. The resulting value is stored in the `num` variable.

Next, the program multiplies `num` by 2 and assigns the result to the `result` variable. Finally, the program prints the value of `result`.

Note that in Python 2, the `input()` function expects the user to enter a valid Python expression. So if the user enters `4 + 5`, the program will evaluate it as `9` and store that in the `num` variable.

#### `eval()` function in Python 3

In Python 3, the `eval()` function is a built-in function that evaluates a string as a Python expression and returns the result. It allows you to dynamically execute code that is represented as a string. Here's an example to illustrate its usage:

```python
expression = input("Enter a mathematical expression: ")
result = eval(expression)
print("The result is:", result)
```

In the above code, the `eval()` function is used to evaluate the user's input as a mathematical expression. The input is stored in the `expression` variable using the `input()` function. The `eval()` function then evaluates the expression and returns the result, which is stored in the `result` variable. Finally, the program prints the result.

It's important to note that using `eval()` can be a security risk if the input is not properly validated. This is because it allows the execution of arbitrary code. It is recommended to only use `eval()` with trusted input or in controlled environments.

When you use `input()`, you can gather information from the users of your program. However, what if you need to show them the results of calculations that your program has performed? In the next section, we will show you how to display the output of your program to the users in the console.

### Displaying Program Output in the Console

In addition to obtaining data from the user, a program will also usually need to present data back to the user. You can display program data to the console in Python with `print()`.

To display objects to the console, pass them as a comma-separated list of arguments to `print()`.

```python
print(<obj>, ..., <obj>)
```

By default, `print()` separates objects by a single space and appends a newline to the end of the output:

```python
first_name = "Ali Abdullah"
last_name = "Nasiri"

print("Name:", first_name, last_name)
```

When you run this script, it will output:

```makefile
Name: Ali Abdullah Nasiri
```

### Printing With Advanced Features

`print()` takes a few additional arguments that provide modest control over the format of the output. Each of these is a special type of argument called a **keyword argument**.

For now, though, here’s what you need to know:

* Keyword arguments have the form `<keyword>=<value>`.
* Any keyword arguments passed to `print()` must come at the end, after the list of objects to display.

In the following sections, you’ll see how these keyword arguments affect console output produced by `print()`.

#### Separating Printed Values

Adding the keyword argument `sep=<str>` causes Python to separate objects by `<str>` instead of by the default single space:

```python
print("foo", 42, "bar")
print("foo", 42, "bar", sep="/")
print("foo", 42, "bar", sep="...")
```

When you run this script, it will output:

```
foo 42 bar
foo/42/bar
foo...42...bar
foo -> 1
bar -> 2
baz -> 3
```

To squish objects together without any space between them, specify an empty string (`""`) as the separator:

```python
print("foo", 42, "bar", sep="")
```

When you run this script, it will output:

```
foo42bar
```

You can use the `sep` keyword to specify any arbitrary string as the separator.

#### Controlling the Newline Character

The keyword argument `end=<str>` causes output to be terminated by `<str>` instead of by the default newline:

```python
print("Ali", end=" ")
print("Abdullah", end=" ")
print("Nasiri", end="")
```

When you run this script, it will output:

```
Ali Abdullah Nasiri
```

#### Sending Output to a Stream

`print()` accepts two additional keyword arguments, both of which affect how the function handles the output stream:

1. **`file=<stream>`:** By default, `print()` sends its output to a default stream called `sys.stdout`, which is usually equivalent to the console. The `file=<stream>` argument causes `print()` to send the output to an alternate stream designated by `<stream>` instead.
2. **`flush=True`:** Ordinarily, `print()` buffers its output and only writes to the output stream intermittently. `flush=True` specifies that Python forcibly flushes the output stream with each call to `print()`.

These two keyword arguments are presented here for the sake of completeness. You probably don’t need to be too concerned about output streams at this point of your learning journey.

### Conclusion <a href="#python-input-and-output-conclusion" id="python-input-and-output-conclusion"></a>

In this tutorial, you learned about input and output in Python and how your Python program can communicate with the user. You’ve also explored some of the arguments you can work with to add a message to the input prompt or customize how Python displays the output back to your users.

**You’ve learned how to:**

* Take user input from the keyboard with the built-in function **`input()`**
* Display output to the console with the built-in function **`print()`**

In the following tutorial of this introductory series, you’ll learn about another string formatting technique, and you’ll dive deeper into using f-strings.
