0

hi I am new to programming I just want to know how can I exit this program using just the enter? Can't use the if not due to the split.

while True:
    try:
        Student.id, Student.name, Student.degree = input("give id,name and degree or hit enter to exit").split(",")
1
  • Move the split call later, if input was provided; otherwise exit. Commented Feb 19, 2022 at 12:49

3 Answers 3

1

If user hit enter, it sends an empty string. So you can check to see if it is empty string or not. using walrus operator:

while inp := input("give id,name and degree or hit enter to exit"):
    Student.id, Student.name, Student.degree = inp.split(",")

without :=:

while True:
    inp = input("give id,name and degree or hit enter to exit")
    if not inp:
        break
    Student.id, Student.name, Student.degree = inp.split(",")
Sign up to request clarification or add additional context in comments.

Comments

0

Just remove the try. The program will exit with an exception if the user just presses enter.

while True:
    Student.id, Student.name, Student.degree = input("give id,name and degree or hit enter to exit").split(",")

Comments

0

I would recommend you split this up into a number of steps to make it clearer and give you greater control over what is happening. For example:

while True:
    values = input("give id,name and degree or hit enter to exit: ")

    if values:
        values = values.split(',')
        
        if len(values) == 3:
            id, name, degree = values
            print(f"ID: {id}  Name: {name}  Degree: {degree}")
        else:
            print("Please enter the correct number of arguments")
    else:
        break  # just enter was pressed

This approach has the benefit of being able to spot when the user has entered an incorrect number of arguments.

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.