just starting my journey with python. I would like to create a simple program that will take the input from the user and then do smth with it. But I am wondering what would happen if they put too many words. The error comes up and I cant get around with it.
name, surname = input("Full name: ").split()
try:
print("Hello", name)
print("Your login is:", surname "ing")
except ValueError:
print("Please type your Full name only!") #user type 3 words instead of 2
CodePudding user response:
You have to put the assignment inside the try
, since that's where the execption is raised.
try:
name, surname = input("Full name: ").split()
print("Hello", name)
print("Your login is:", surname "ing")
except ValueError:
print("Please type your Full name only!") #user type 3 words instead of 2
CodePudding user response:
I would suggest that you not use an exception in this way. I would check your input explicitly. Here's a way to do that:
while True:
user_input = input("Full name: ").split()
if len(user_input) == 2:
break
print("Please type your Full name only!") #user type 3 words instead of 2
name, surname = user_input
print("Hello", name)
print("Your login is:", surname "ing")
Result:
Full name: Joe
Please type your Full name only!
Full name: Joe Blow a b c
Please type your Full name only!
Full name: Joe Blow
Hello Joe
Your login is: Blowing
Process finished with exit code 0
CodePudding user response:
You could ask for each value on its own like:
name = input("blabla")
surname = input("blabla")
or you could add it inside of the try/except which should also handle this error.
try:
name, surname = input("Full name: ").split()
print("Hello", name)
print("Your login is:", surname "ing")
except ValueError:
print("Please type your Full name only!") #user type 3 words instead of 2