Header Ads Widget

Ticker

6/random

Python User Input

Python User Input


In Python, the `input()` function is used to get user input from the console. 

Here's an explanation with examples:


1. Basic Input:


```python

user_input = input("Enter something: ")

print("You entered:", user_input)

```


The `input()` function displays the prompt provided as an argument and waits for the user to enter something. The entered value is then stored in the variable `user_input`.


2. Converting Input to Int or Float:


```python

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

height = float(input("Enter your height in meters: "))


print("You are", age, "years old.")

print("Your height is", height, "meters.")

```


You can use `int()` or `float()` to convert the user input to an integer or a float, respectively.


3. Using Input in a Calculation:


```python

radius = float(input("Enter the radius of a circle: "))

area = 3.14 * radius**2


print("The area of the circle is:", area)

```


User input can be used in calculations. Here, the user enters the radius, and the program calculates the area of a circle.


4. Handling User Input as Strings:


```python

name = input("Enter your name: ")

if name.lower() == "alice":

    print("Hello, Alice!")

else:

    print(f"Hello, {name}!")

```


User input is treated as a string by default. Here, the program checks if the entered name is "Alice" (case-insensitive) and responds accordingly.


5. Using a While Loop for Valid Input:


```python

while True:

    try:

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

        break # Exit the loop if input is successfully converted to an integer

    except ValueError:

        print("Invalid input. Please enter a valid integer.")


print("You entered:", age)

```


A `while` loop is used to repeatedly prompt the user for input until a valid integer is entered. The `try-except` block catches `ValueError` if the input cannot be converted to an integer.


6. Handling Multiple Inputs:


```python

name, age = input("Enter your name and age (separated by a space): ").split()

age = int(age)


print("Name:", name)

print("Age:", age)

```


The `split()` function is used to separate multiple inputs entered on a single line. Here, the user is prompted to enter name and age separated by a space.


User input is a fundamental way to make Python programs interactive, allowing them to respond to user-specific data or instructions.

Post a Comment

0 Comments