Python input function in Detail- interesting usecases

by | May 14, 2024 | Python | 0 comments

The input() function in Python is primarily used to take input from the user through the command line. While its most common use is to receive text input, it can be used creatively for various purposes. Here are some interesting uses of the input() function along with examples:

User Authentication:


You can use input() to prompt the user for a username and password, then validate them against a predefined set.

username = input(“Enter your username: “)
password = input(“Enter your password: “)

if username == “admin” and password == “password”:
print(“Welcome, admin!”)
else:
print(“Invalid username or password.”)


Interactive Menu:


Create an interactive menu where the user can select different options using input().

print(“Menu:”)

print(“1. Option 1”)

print(“2. Option 2”)

print(“3. Option 3”)

choice = input(“Enter your choice: “)

if choice == “1”:

    print(“You selected Option 1”)

elif choice == “2”:

    print(“You selected Option 2”)

elif choice == “3”:

    print(“You selected Option 3”)

else:

    print(“Invalid choice”)


You can prompt the user for numeric input and validate it.

while True:
try:
age = int(input(“Enter your age: “))
break
except ValueError:
print(“Invalid input. Please enter a number.”)

print(“Your age is:”, age)


File Input/Output:


Use input() to prompt the user for a filename and then read or write data to that file.

filename = input(“Enter filename: “)

with open(filename, ‘r’) as file:

    data = file.read()

    print(“File content:”, data)


Dynamic Program Behavior:


Allow the user to input parameters to control the behavior of your program.

radius = float(input(“Enter the radius of the circle: “))
area = 3.14 * radius ** 2
print(“Area of the circle:”, area)


Loop Control:


Use user input to control the flow of a loop.

while True:

    user_input = input(“Do you want to continue? (yes/no): “)

    if user_input.lower() == “no”:

        break

    elif user_input.lower() != “yes”:

        print(“Invalid input. Please enter ‘yes’ or ‘no’.”)


Guessing Games:


Create interactive games where the user has to guess a number or word.

import random

number = random.randint(1, 100)

guess = None

while guess != number:

    guess = int(input(“Guess the number (1-100): “))

    if guess < number:

        print(“Too low!”)

    elif guess > number:

        print(“Too high!”)

    else:

        print(“Congratulations! You guessed it right!”)

A tuple, a dictionary, or a list from string input

You can collect a tuple, a dictionary, or a list from string input by parsing the input string and converting it into the desired data structure using Python’s built-in functions and methods. Here’s how you can do it for each data structure:

Collecting a Tuple from String Input:

String input format: “(item1, item2, item3, …)”

input_string = input("Enter a tuple (in the format '(item1, item2, item3, …)'): ")

Remove parentheses and split by comma

items = input_string.strip('()').split(',')

Convert items to desired data types and create a tuple

my_tuple = tuple(map(str.strip, items))
print("Tuple:", my_tuple)


Collecting a Dictionary from String Input:

String input format: “{key1: value1, key2: value2, key3: value3, …}”

input_string = input("Enter a dictionary (in the format '{key1: value1, key2: value2, …}'): ")

Remove braces, split by comma, then split each key-value pair by colon

pairs = [pair.split(':') for pair in input_string.strip('{}').split(',')]

Remove leading and trailing spaces from keys and values, then create dictionary

my_dict = {key.strip(): value.strip() for key, value in pairs}
print("Dictionary:", my_dict)


Collecting a List from String Input:

String input format: “[item1, item2, item3, …]”

input_string = input("Enter a list (in the format '[item1, item2, item3, …]'): ")

Remove brackets and split by comma

items = input_string.strip('[]').split(',')

Convert items to desired data types and create a list

my_list = list(map(str.strip, items))
print("List:", my_list)


These examples assume a specific format for the input string (e.g., for tuples, dictionaries, and lists). You may need to adjust the parsing logic according to your specific input format. Additionally, error handling for invalid input should be added as needed to ensure the robustness of your code.

Written by HintsToday Team

Related Posts

Python Strings Interview Questions

Python Programming Strings Interview Questions Write a Python program to remove a Specific character from string? Here's a Python program to remove a specific character from a string: def remove_char(text, char): """ Removes a specific character from a string. Args:...

read more

Python Dictionary in detail

What is Dictionary in Python? First of All it is not sequential like List. It is an non-sequential, unordered, redundant and mutable collection as key:value pairs. Keys are always unique but values need not be unique. You use the key to access the corresponding value....

read more

Get the latest news

Subscribe to our Newsletter

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *