简体   繁体   中英

How do I get this loop to quit once it has displayed the same letter three times?

So I have this totally screwed program. What I want to do is cut the loop off once it has displayed three of the same letters. So far what I have got is:

#Declaring letter variable
letters = str('AEIOU')

A = 0
E = 0
I = 0
O = 0
U = 0

for i in range(0, 9):
    print(random.choice(letters))
    if (random.choice(letters)) == ('A'):
        A + 1
        print(random.choice(letters))
        if A > 3:
            quit()

The range is arbitrary. Just for testing purposes. I also tried using a while loop but I couldn't figure out how to kill it either. It just looped infinitely:

A = 0
import random
   while A < 3:
    print(random.choice(letters))
    if (random.choice(letters)) == ('A'):
        A + 1
        print(random.choice(letters))
        if A > 3:
            quit()

Any suggestions? Please don't hate too much...

You need to save the random character for comparison, and save the incremented counter:

import random
A = 0
while A < 3:
    a = random.choice(letters)
    if a == 'A':
        A += 1
        print(a)

If you want to keep track of all the letters, use a dictionary:

import random
letters = 'AEIOU'
d = {'A':0, 'E':0, 'I':0, 'O':0, 'U':0}
while 1:
    letter = random.choice(letters)
    d[letter] += 1
    if d[letter] > 2:
        break

You have to count the letters somehow - a dictionary is a good fit for this purpose, as TigerhawkT3 has shown. I am using a defaultdict here, which has a default value for all entries - since I am using an int as default value, the default value is zero. This is somewhat more tricky, but saves us from initializing the array, which can be annoying if the amount of values is unknown in advance or large.

If you want to exit a loop use "break" - which breaks the current level of the loop - so for nested loops you would need mulitple breaks.

import collections
import random
letters = str('AEIOU')
printed = collections.defaultdict(int)

while True:
    letter = random.choice(letters)
    print(letter)
    printed[letter] += 1
    if printed[letter] > 2:
        break

Using Counter from python collections library,

import random
from collections import Counter
letters = str('AEIOU')

counter = Counter()
limit = 3
while 1:
    letter = random.choice(letters)
    print(letter)
    counter[letter] += 1
    if counter[letter] >= limit:
        break

Reference for Counter: https://docs.python.org/2/library/collections.html#collections.Counter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM