Brandon Nguyen
Brandon Nguyen

Reputation: 1

How to get Python to stop at a certain number while showing "iterations"

My assignment is to write a Python script that uses random to generate a random number inside a loop, and that loop keeps running until it generates a 4.00 gpa. I was able to see a demo of what the final assignment is suppose to look like.

Right now I am stuck with

while True:
   x = random.uniform(1,4)
   print(x)
   if x ==(4):
       break

When I run my code, it looks nothing like the demo the professor shows enter image description here

Upvotes: 0

Views: 2304

Answers (3)

Guy
Guy

Reputation: 50899

You can convert the number to two decimals with `ro

iterations = 0
while True:
    iterations += 1
    x = round(random.uniform(1, 4), 2)
    print(x)
    if x == 4.0:
        break

print(f'Iterations: {iterations}')

Upvotes: 0

luigigi
luigigi

Reputation: 4215

You may use:

import random
iteration_count = 0
while True:
    iteration_count += 1
    x = round(random.uniform(1,4), 2)
    print(x)
    if x == 4:
        print('Iteration count: %i' % iteration_count )
        break

Your Code is very unlikely to ever end since you are generating floats which are unlikely to be exactly 4. So you should round the values like your prof did.

Upvotes: 1

kosist
kosist

Reputation: 3057

import random

i = 0
while True:
   x = random.uniform(1,4)
   print(i)
   i+=1
   print(x)
   if x == (4):
       break

where i - is counter of iterations

Upvotes: 0

Related Questions