Making my While loop terminate with the input of
Making my While loop terminate with the input of "Done"
I am currently writing a program for my Intro to Programming class. The requirements are to have a user input a list of celebrity names, add them to a list, print out how many celebrities were entered, and then to print the list of the celebrities that were entered. I must use a loop, so I employed a while loop; however I cannot make it end when the user inputs Done
to the names input field.
Below is the code, and my attempt at using an if else statement to control the loop.
def main(): celebs = [] again = 'y' while again == 'y': name = input('Enter a name: ') if name == 'Done': again == 'n' else: again == 'y' celebs.append(name) print('You entered ',len(celebs), 'celebrities to the list') print(' ') print('The ',len(celebs),'celebrities you entered were: ') for name in celebs: print(name) main()
Answer by Ben for Making my While loop terminate with the input of "Done"
Change the double equals to a single equals in the statements inside the if/else. You need to assign a value to 'again', but the double equals is just comparing instead.
Alternatively, you could look up the use of the 'break' statement.
Answer by Leistungsabfall for Making my While loop terminate with the input of "Done"
Use ==
for comparisons and =
for assignments. That should do the trick.
Answer by Derek Kurth for Making my While loop terminate with the input of "Done"
If name == "Done", you should do:
again = 'n' # not again == 'n'
(Similarly for setting again = 'y', although I think that line is unnecessary, since again is already equal to 'y'.)
Answer by user2626431 for Making my While loop terminate with the input of "Done"
You have a comparison operator in your code instead of assignment.
Change again == 'n'
to again = 'n'
and again == 'y'
to again = 'y'
Answer by m.wasowski for Making my While loop terminate with the input of "Done"
To avoid adding 'Done' to your list, skip to next iteration:
while again == 'y': name = input('Enter a name: ') if name == 'Done': again = 'n' continue else: again = 'y' celebs.append(name)
which can be simplified to:
while again == 'y': name = input('Enter a name: ') if name == 'Done': again = 'n' continue celebs.append(name)
it is also better to use bool
value here:
again = True while again: name = input('Enter a name: ') if name == 'Done': again = False continue celebs.append(name)
or you can just use break
:
while True: name = input('Enter a name: ') if name.strip() == 'Done': break celebs.append(name)
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment