Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Input and Output

Take input in one line and split into variables - Python Program

Example 1:
name, age = input("Enter name and age: ").split() print("Name:", name) print("Age:", age)

Output

 
OUTPUT  :
Enter name and age: Ronnie 22
Name: Ronnie
Age: 22

To take input in one line and split it into multiple variables in Python, the input() function is combined with the split() method.

1. Splitting by Whitespace (Default):

If the input values are separated by spaces, the split() method without any arguments can be used.

 

Example 2:
# Prompt the user for input user_input = input("Enter multiple values separated by spaces: ") # Split the input string into a list of strings values = user_input.split() # Assign the elements of the list to individual variables # This assumes you know the number of values expected if len(values) >= 3: # Example: expecting at least 3 values var1, var2, var3 = values[0], values[1], values[2] print(f"Variable 1: {var1}") print(f"Variable 2: {var2}") print(f"Variable 3: {var3}") else: print("Not enough values entered.")

Output

 
OUTPUT  :
Enter multiple values separated by spaces: India is Great
Variable 1: India
Variable 2: is
Variable 3: Great

2. Splitting by a Specific Delimiter:

If the input values are separated by a character other than whitespace (e.g., comma, semicolon), the delimiter can be passed as an argument to the split() method.

 

Example 3:
# Prompt the user for input with a specific delimiter user_input = input("Enter values separated by commas (e.g., apple,banana,orange): ") # Split the input string using the comma as the delimiter values = user_input.split(',') # Assign the elements to variables if len(values) >= 2: # Example: expecting at least 2 values item1, item2 = values[0], values[1] print(f"Item 1: {item1}") print(f"Item 2: {item2}") else: print("Not enough items entered.")

Output

 
OUTPUT  :
Enter values separated by commas (e.g., apple,banana,orange): Apple,Banana,Orange
Item 1: Apple
Item 2: Banana

3. Converting to Different Data Types:

If the input values need to be converted to numerical types (integers, floats), the map() function can be used in conjunction with split().

 

Example 4:
# Prompt the user for numerical input user_input = input("Enter two numbers separated by spaces: ") # Split the input and convert to integers using map() try: num1, num2 = map(int, user_input.split()) print(f"First number (integer): {num1}") print(f"Second number (integer): {num2}") except ValueError: print("Invalid input: Please enter valid numbers.")

Output

 
OUTPUT  :
Enter two numbers separated by spaces: 12 15
First number (integer): 12
Second number (integer): 15