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:

  1. Basic Input:

    name = input("Enter your name: ")
    print("Hello, " + name + "!")
    
  2. 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.")
    
  3. 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:

  1. Basic Output:

    print("Hello, World!")
    
  2. Printing Variables:

    age = 25
    print("I am", age, "years old.")
    
  3. 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))
    
  4. Using sep and end Parameters:

    • The sep parameter specifies the separator between multiple objects, and the end parameter specifies what to print at the end.
    print("Hello", "World", sep=", ", end="!\n")
    



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.

  1. Importing a Module:

    import math
    print(math.sqrt(16))  # Output: 4.0
    
  2. Importing Specific Functions:

    from math import sqrt, pi
    print(sqrt(25))  # Output: 5.0
    print(pi)        # Output: 3.141592653589793
    
  3. Using Aliases:

    import numpy as np
    array = np.array([1, 2, 3])
    print(array)  # Output: [1 2 3]
    
  4. 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
    


Comments

Popular posts from this blog

Keyword , Identifier, Indentation, Comments & Documentation

DSA Lab 8 program

DSA Lab 7 Program