vendredi 24 novembre 2017

How to connect random number generation to item to print in python

As answered in

http://ift.tt/2jYy1o1

I am using this code to generate a random number. If the number generated is less than 9, I want it to print a name along with it, if the number is 9 or 10, I want the loop to break.

import random
class Stack:
    def __init__(self):
        self.container = []  

    def isEmpty(self):
        return self.size() == 0   

    def push(self, item):
        self.container.append(item)  

    def peek(self) :
        if self.size()>0 :
            return self.container[-1]
        else :
            return None

    def pop(self):
        return self.container.pop()  

    def size(self):
        return len(self.container)

    def printItem(self, run):
        print(self.container[run]) # Prints last item/name



import random

while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
   break




Names = Stack()

Names.push('Mary')
Names.push('Peter')
Names.push('Bob')
Names.push('John')
Names.push('Kim')

run = -1

while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
    break
elif rand < 9:
    # Calls printItem with run as parameter
    Names.printItem(run)
    run-=1 # Subtracts one from run
    # Sets run to -1 again if all names have been printed
    if run<(-1*Names.size()):
        run = -1'

When answered in the link above, I changed elif rand == 3: to elif rand < 9: but it still does not print a name with every number less than 9. A sample output it gave was

5 8 10 4 Kim 7 John 1 Bob 2 Peter 7 Mary 2 Kim 10

and another

9 3 Kim 7 John 1 Bob 6 Peter 10

did not exit when it was 9 or 10

Please help




Aucun commentaire:

Enregistrer un commentaire