Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to loop 100 times but not print 100 times in the loop (Python)

for lp in range(100):
    if guess == number:
        break
    if guess < number:
        print "Nah m8, Higher."
    else:
        print "Nah m8, lower."

This is some basic code that I was told to make for a basic computing class. My aim is to make a simple 'game' where the user has to guess a random number that the computer has picked (1-100) This is a small section of the code where I want to continue checking if the guess is equal to, lower or higher than the number; but if I put a print statement below, it will print the text 100 times. How can I remove this problem?

Thanks in advance.

like image 737
Orishmark4 Avatar asked Jun 11 '13 17:06

Orishmark4


People also ask

How do you make a for loop run for a specific number of times in Python?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

How do I limit a while loop in Python?

The structure of the while loop WHILE is followed by a Python statement. The loop is executed as long as the statement evaluates to boolean True . The body of the loop contains the lines to be executed for each loop iteration. The while loop has a default limit of 10000 iterations to avoid accidental infinite loops.


1 Answers

It seems like you're omitting the guessing stage. Where is the program asking the user for input?

Ask them at the beginning of the loop!

for lp in range(100):
    guess = int(input('Guess number {0}:'.format(lp + 1)))
    ...
like image 75
forivall Avatar answered Nov 14 '22 22:11

forivall