Python Input and Output Functions

 Python Input and Output Functions

In Python, you can use various input and output (I/O) functions to interact with the user, read from and write to files, and handle data. Here are some commonly used input and output functions in Python:


Input Functions:


1. `input(prompt)`:

   - This function allows you to take user input from the keyboard.

   - The `prompt` is an optional string that is displayed to the user as a message or question.

   - The function returns a string containing the user's input.


   ```python

   name = input("Enter your name: ")

   print("Hello, " + name + "!")

   ```


2. `int(input(prompt))`:

   - This function is used to read an integer input from the user.

   - The `prompt` is an optional message displayed to the user.

   - It returns an integer based on the user's input.


   ```python

   age = int(input("Enter your age: "))

   ```


3. `float(input(prompt))`:

   - Similar to `int(input(prompt))`, this function is used to read a floating-point number input from the user.

   - It returns a float based on the user's input.


   ```python

   temperature = float(input("Enter the temperature in Celsius: "))

   ```


Output Functions:


1. `print(...)`:

   - The `print` function is used to display output to the console.

   - You can pass one or more values separated by commas to `print`.

   - By default, `print` adds a newline character at the end, but you can change this behavior using the `end` parameter.


   ```python

   print("Hello, World!")

   ```


2. `formatted strings`:

   - You can use formatted strings to display variables and values in a specific format.

   - The f-string (formatted string literal) allows you to embed expressions inside string literals, denoted by an 'f' or 'F' before the string.


   ```python

   name = "Alice"

   age = 30

   print(f"My name is {name} and I am {age} years old.")

   ```


3. File I/O:

   - Python provides functions for reading from and writing to files, such as `open()`, `read()`, `write()`, and `close()`.

   - You can use `open()` to open a file, `read()` to read its contents, `write()` to write data to it, and `close()` to close the file.


   ```python

   # Writing to a file

   with open("my_file.txt", "w") as file:

       file.write("Hello, file!")


   # Reading from a file

   with open("my_file.txt", "r") as file:

       content = file.read()

   print(content)

   ```


These are some of the basic input and output functions in Python. You can use them to interact with users, display information, and work with files. Python offers more advanced I/O capabilities, such as reading and writing in different modes (text mode and binary mode), handling exceptions, and working with structured data formats like JSON and CSV.


Comments