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(",")
CodePudding user response:
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(",")
CodePudding user response:
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(",")
CodePudding user response:
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.