Monday, August 25, 2025

๐ŸUSER INPUTS

Python User Input

Learn how to interact with your program by taking input from the user.

Introduction

A program becomes more powerful when it can interact with users. Python provides the input() function to let users type something, and your program can then use that value.

Basic Usage of input()

name = input("Enter your name: ")
print("Hello,", name)

Example interaction:


Enter your name: Alice
Hello, Alice

Important: Input is Always a String

By default, input() returns text (string). If you want numbers, you must convert them using int() or float().

age = input("Enter your age: ")
print(age + 5)   # ❌ This gives an error

Error:


TypeError: can only concatenate str (not "int") to str

✅ Correct way:

age = int(input("Enter your age: "))
print(age + 5)   # Works fine

Common Mistakes

  • Forgetting quotes in the prompt:
    name = input(Enter your name:)   # ❌ Wrong
    SyntaxError: invalid syntax
    ✅ Correct:
    name = input("Enter your name: ")
  • Forgetting type conversion when dealing with numbers:
    num1 = input("Enter a number: ")
    num2 = input("Enter another number: ")
    print(num1 + num2)   # ❌ This joins the numbers as strings

    Example:

    
    Enter a number: 10
    Enter another number: 20
    1020   # (joined, not added)
    
    ✅ Correct:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    print(num1 + num2)   # 30

๐Ÿ’ก Try It Yourself

  1. Ask the user for their favorite color and print a message like Your favorite color is blue!.
  2. Take two numbers as input and print their sum, difference, and product.
  3. Write a small program that asks for someone’s name and age, and prints: Hello Alice, you are 25 years old.

What’s Next?

Now that you know how to take input from users, let’s learn how to use operators to perform calculations and logical operations.

➡️ Next: Basic Operators in Python

⬅️ Back to main page

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??