在while循环中同时给出1000个答案

时间:2018-11-07 20:48:37

标签: python python-3.x

(我已经开始讨厌while,在我的学校工作中……)

现在的问题是,我需要创建一个程序,要求用户提供一定百分比的篮球投篮准确性。并模拟1000次投掷-对于每个答案,无论结果是命中还是未命中。

如果用户输入45作为百分比,则程序工作的示例

throwing_accuracy = int(input("Enter throwing percentage")): 45

#Somewhere here would be while :
1. Throw hit
2. Throw hit
3. Throw hit
5. Throw missed
#.........#
999. Throw hit
1000. Throw hit
   #And then prints also a result how many hits there were
There were 458 hits

该程序必须使用while构建,我阅读了一些可以使用ifelse语句的提示,应该使用from random import randint,因为可能会使用一行if randint(1,100) <= percentage

1 个答案:

答案 0 :(得分:0)

您可以编写如下程序:

import random
percentage_accuracy = int(input("Input throwing accuracy here: "))
hits = 0
throws = 1
while throws <= 1000:
    if random.randint(1, 100) <= percentage_accuracy:
        hits += 1
        print("{}: Hit".format(x))
    else:
        print("{}: Miss".format(x))
    throws += 1
print("")
print("Player results:")
print("{} Hits".format(hits))
print("{} Misses".format(1000-hits))

使用for循环会更有效,例如:

for throws in range(1,1001):

而不是:

throws = 1
while throws <= 1000:
    throws += 1