Reputation: 11
Im new to coding in python, and is trying to make this work.
if input from user is "name age" it works just fine. But I want it to work if user inputs either (name+age) or (name+lastname+age). If I input 3 values I get ValueError: too many values to unpack (expected 2)
and if add name, lastname, age, =map(str, sys.stdin.readline().split()) to the code. I get a not enough values error when user input name+lastname+age
Hopefully someone can help me :)
name, age, =map(str, sys.stdin.readline().split())
age = int(age)
if "Paul" in (name):
result1 = (age*2)
print("Answer is", + result1)
Upvotes: 0
Views: 96
Reputation: 4744
Here's a possibility - read the input line without the map, parse it, and then differentiate the input based on the number of elements in the resulting list,
import sys
entry = sys.stdin.readline()
entry = entry.strip().split()
if len(entry) == 2:
# Name + age
name = entry[0]
age = int(entry[1])
print(name, age)
elif len(entry) == 3:
# Name + last name + age
name = entry[0]
last_name = entry[1]
age = int(entry[2])
print(name, last_name, age)
else:
raise ValueError('Wrong input arguments')
if "Paul" in (name):
result1 = (age*2)
print("Answer is", + result1)
If the input is nothing of the expected, this code raises an exception. You can instead keep prompting the user until they enter the right values. If you decide to keep the exception approach, consider using a more informative exception message.
Upvotes: 1
Reputation: 71454
Instead of trying to unpack the result of split()
into two variables, you can use join()
combined with list slicing to join everything but the last value into one (the name
):
user = input().split()
age = int(user[-1])
name = ' '.join(user[:-1])
if "Paul" in name:
print(f"Answer is {age*2}")
This works regardless of how many "words" are in the name:
Paul McCartney 42
Answer is 84
Pauline 42
Answer is 84
Paul W. S. Anderson 42
Answer is 84
Upvotes: 0
Reputation: 11060
You can't split something into a dynamic number of variables this way.
Instead you need to capture the input and then work out how many fields were passed in. Something like:
user = map(str, sys.stdin.readline().split())
lastname = ''
name = user[0]
age = user[1]
if len(user) == 3:
lastname = user[1]
age = user[2]
Upvotes: 0