简体   繁体   中英

Using the while loop statement to divide, count, and multiply in Python 3.x

I'm fairly novice to Python (3.x) and I am given this task of E.coli bacteria.

Here are the key points I have listed from the task:

• Number of E.coli bacteria doubles every 20 minutes

• User enters a target number of bacteria and is told the time it will take a single E.coli to divide into the target number of bacteria, to the nearest 20 minutes

• The program must make use of the while loop

• The program should reject non-numeric inputs or a target number over 130,000

Therefore, am I right in speaking that... Targetnumber / 2, count each time it halves until number gets to 1, number of count * 20 mins

So far in my code I have the user input of the target number (under 130,000) and validation if it's not numeric:

while True:
    try:
        targetnumber = int(input('Enter the target number of E.coli under 130000: '))
        if 130000 >= targetnumber:
            break
    except ValueError:
        print("Please enter a numerical target number input under 130000.")
        continue
    else:
        print("Target number must be under 130000.")

However I am finding it difficult to implement targetnumber / 2, count each time it halves until number gets to 1, number of count * 20 mins in my code using a while loop.

If you could help and ELI5 that would be much appreciated. Many thanks

Instead of dividing the target number of bacteria by 2, you can use a variable with initial value of 1 and then keep multiplying it by 2 until it becomes equal to or bigger than the target bacteria.

target_limit = 130000

while True:
    try:
        target_number = int(input('Enter the target number of E.coli: '))
        if target_number > target_limit:
            print('Target E.coli must be under ' + str(target_limit))
        else:
            break
    except ValueError:
        print('Enter a numeric input')

n_bact = 1
time_elapsed = 0

while n_bact < target_number:
    n_bact *= 2
    time_elapsed += 20

print(time_elapsed)

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