python - while loop for user input doesn't exit -
the code have below isn't stopping when enter exitcode, , other problem elif line detecting every character entered number.
counter = 0 exitcode = 'x' wantstoexit = false while counter < 6 , wantstoexit == false: candyname = str(input('enter candy\'s code/name ({0} exit): '.format(exitcode))) if candyname == "{0}".format(exitcode): wantstoexit == true print("you have chosen exit.") elif candyname.isdigit: print("please enter letters.")
there several problems code.
as dzarafata mentioned,
- you testing value of
counter@ top ofwhileloop never change value in loop. elif candyname.isdigit:doesn't test if stringcandynameconsists of digits. that, need call method, this:elif candyname.isdigit().
however, not test want, since doesn't catch strings contain non-letters aren't digits, eg, punctuation marks.
fwiw, if candyname.isdigit: tests truth value of candyname.isdigit method itself. in python method object , object isn't equivalent 0, false, none, or other null object empty string, list, tuple, set, dict, etc, considered true.
if candyname.isdigit: print("stuff") will always print stuff, no matter string in candyname.
a 3rd problem code doesn't exit while loop when gets correct data.
a minor flaw in code str(input(stuff)). python 3 input() function always returns string, there's no need convert output string str(). if you're using python 2 should avoid using input() , use raw_input() instead, python 2 input() can dangerous things untrusted input.
here's modified version of code. i've changed candyname candy_name comply usual python naming convention. i've modified logic use break statements, no longer need wantstoexit flag.
exitcode = 'x' prompt = "enter candy's code/name ({0} exit): ".format(exitcode) #make upto 6 attempts correct input candy_name = none counter in range(1, 7): data = input("{0}: {1}".format(counter, prompt)) if data == exitcode: print("you have chosen exit.") break elif not data.isalpha(): print("please enter letters.") else: candy_name = data break if candy_name none: print("no valid candy name entered") else: print("candy name: '{0}'".format(candy_name)) note use data store user input string, , copy candy_name once we've made sure it's valid name. version prints current value of counter @ start of prompt.
Comments
Post a Comment