简体   繁体   English

在 Python 3.x 中使用 while 循环语句进行除法、计数和乘法

[英]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.我对 Python (3.x) 还是个新手,我被赋予了 E.coli 细菌的这项任务。

Here are the key points I have listed from the task:以下是我从任务中列出的要点:

• Number of E.coli bacteria doubles every 20 minutes • 大肠杆菌数量每 20 分钟翻一番

• 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 • 用户输入目标细菌数,并告知将单个大肠杆菌分解为目标细菌数所需的时间,精确到 20 分钟

• The program must make use of the while loop • 程序必须使用while循环

• The program should reject non-numeric inputs or a target number over 130,000 • 程序应拒绝非数字输入或超过 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因此,我说得对吗... Targetnumber / 2,每次减半计数,直到数字变为 1,计数次数 * 20 分钟

So far in my code I have the user input of the target number (under 130,000) and validation if it's not numeric:到目前为止,在我的代码中,我有用户输入的目标数字(低于 130,000)并验证它是否不是数字:

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.但是,我发现很难在我的代码中使用while循环实现 targetnumber / 2, count 每次减半直到 number 变为 1, number of count * 20 mins 。

If you could help and ELI5 that would be much appreciated.如果您能提供帮助和 ELI5,将不胜感激。 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.不是将目标细菌数除以 2,您可以使用初始值为 1 的变量,然后继续乘以 2,直到它等于或大于目标细菌。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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