0

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

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.