Monday, August 25, 2025

🐍INPUT AND OUTPUT BUILT-IN FUNCTIONS

Python provides built-in functions to get input from users and display output on the screen, as well as interact with files.

1) Displaying Output with print()

The print() function is used to display values or messages on the screen.


# Simple print
print("Hello, Python!")

# Multiple values
name = "Alice"
age = 25
print(name, "is", age, "years old")

# Using separator and end
print("Python", "is", "fun", sep="-", end="!\n")  # Output: Python-is-fun!

Common Mistakes:

  • Capitalizing function name: Print()NameError
  • Forgetting parentheses: print → does not display output
  • Passing variables that are undefined → NameError

2) Getting Input with input()

The input() function reads data from the user as a string.


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

print("Hello", name, "! You are", age, "years old.")
print("Type of age variable:", type(age))  # Always str

# Convert input to integer
age = int(age)
print("Next year, you will be", age + 1)

Common Mistakes:

  • Forgetting parentheses: input → does not work
  • Trying arithmetic without converting to int/float → TypeError
  • Passing wrong prompt type (must be string) → TypeError

3) Basic File Input/Output

You can read from and write to files using open(), read(), write(), and close().


# Writing to a file
f = open("example.txt", "w")
f.write("Hello, Python!\n")
f.write("This is a file.")
f.close()

# Reading from a file
f = open("example.txt", "r")
content = f.read()
print(content)
f.close()

Tips: You can also use with to handle files automatically:


with open("example.txt", "r") as f:
    content = f.read()
    print(content)

Common Mistakes:

  • Forgetting to close the file → can lock the file
  • Trying to read a file that doesn’t exist → FileNotFoundError
  • Using wrong mode ('r', 'w', 'a', 'rb', etc.) → errors or unexpected behavior

💡 Try It Yourself

  1. Print a welcome message with your name using print().
  2. Ask user input for their favorite number and display it.
  3. Convert user input to integer or float and perform a calculation.
  4. Create a text file and write a few lines of text into it.
  5. Read the text file and print its content to the screen.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??