Input & Output Function, Import Function
Sure! Let’s dive deeper into the input, output, and import functions in Python.
Input Function
The input()
function is used to take input from the user. It reads a line from the input and returns it as a string. Here are some detailed examples:
Basic Input:
name = input("Enter your name: ") print("Hello, " + name + "!")
Input with Type Conversion:
- You can convert the input to other data types using functions like
int()
,float()
, etc.
age = int(input("Enter your age: ")) print("You are", age, "years old.")
- You can convert the input to other data types using functions like
Handling Multiple Inputs:
- You can take multiple inputs in a single line and split them.
x, y = input("Enter two numbers separated by space: ").split() print("First number:", x) print("Second number:", y)
Output Function
The print()
function is used to display output to the console. It can print strings, variables, and other data types. Here are some detailed examples:
Basic Output:
print("Hello, World!")
Printing Variables:
age = 25 print("I am", age, "years old.")
Formatted Output:
- You can format the output using f-strings (formatted string literals) or the
str.format()
method.
name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.") print("My name is {} and I am {} years old.".format(name, age))
- You can format the output using f-strings (formatted string literals) or the
Using
sep
andend
Parameters:- The
sep
parameter specifies the separator between multiple objects, and theend
parameter specifies what to print at the end.
print("Hello", "World", sep=", ", end="!\n")
- The
Import Function
The import
statement is used to include the definitions from a module into your current script. This allows you to use the module’s functionality without having to write it yourself.
Importing a Module:
import math print(math.sqrt(16)) # Output: 4.0
Importing Specific Functions:
from math import sqrt, pi print(sqrt(25)) # Output: 5.0 print(pi) # Output: 3.141592653589793
Using Aliases:
import numpy as np array = np.array([1, 2, 3]) print(array) # Output: [1 2 3]
Importing All Functions:
- You can import all functions from a module using the
*
operator, but it’s generally not recommended as it can lead to conflicts.
from math import * print(sqrt(16)) # Output: 4.0 print(pi) # Output: 3.141592653589793
- You can import all functions from a module using the
Comments
Post a Comment