3

我刚开始学习 Python 并试图编写以下问题:

硬币翻转模拟 - 编写一些代码来模拟翻转单个硬币,无论用户决定多少次。代码应记录结果并计算正面和正面的数量。

以下是我的代码:

import random

def num_of_input():
   while True:
     try:
        time_flip= int(input('how many times of flips do you want?'))
    except:
        print('please try again')
        continue
    else:
        break

return time_flip    

def random_flip():
   return random.randint(0, 1)


def count_for_sides():
   count_head=0
   count_tail=0
   times=num_of_input()
   while True:
      if count_head+count_tail==times
        break

      else:
          if random_flip()==0:
              count_head+=1
          else:
             count_tail+=1

     print(count_head)
     print(count_tail)

我现在遇到的问题是:如果我将输入作为 x(x 次翻转),那么我需要输入 X+1 次才能看到结果,如下所示:

count_for_sides()
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4

 0
 4

我真的很困惑这种情况。我认为这意味着我的输入函数处于一个 while 循环中,因此它会继续检查条件,因为它会继续询问我的输入。

4

3 回答 3

1

我想你一定在某个地方弄乱了你的缩进。我复制了你的代码,修复了 SO 中的缩进问题,它基本上工作正常。

这就是我所拥有的:

import random

def num_of_input():
  while True:
    try:
     time_flip= int(input('how many times of flips do you want?'))
    except:
      print('please try again')
      continue
    else:
      break
  return time_flip    

def random_flip():
  return random.randint(0, 1)


def count_for_sides():
  count_head=0
  count_tail=0
  times=num_of_input()
  while True:
    if count_head+count_tail==times:
      break

    else:
      if random_flip()==0:
        count_head+=1
      else:
        count_tail+=1
  print(count_head)
  print(count_tail)

count_for_sides()

话虽如此,你正在做一些你不应该做的事情。

首先,有些地方适合无限循环,但你的用途不是那些地方。对于第一个功能,我认为类似

def num_of_input():
    try:
        time_flip = int(input('how many times of flips do you want?'))
    except ValueError:
        print('That was not a valid integer. Please try again)
        time_flip = num_of_input()
    finally:
        return time_flip

更具可读性和安全性。

对于 count_for_sides() 函数,类似于:

def count_for_sides:
     count_head, count_tail = 0, 0
     for i in range(num_of_input()):
          if random.randint(0, 1) == 0:
               count_head+=1
          else:
               count_tail+=1
      print(counthead)
      print(counttail)

除了用 for 循环替换无限 while 循环外,我完全摆脱了 random_flip 函数,因为它什么都不做,只是直接使用 random.randint(0, 1) 。

通常,python 中的 break 命令应该非常谨慎地使用,因为它很少能改进带有条件的 while 循环、for 循环(如 count_for_sides() 函数)或递归函数(如 num_of_input())。它通常也比其他结构可读性差。

于 2018-02-16T21:53:53.170 回答
0

这是处理该问题的一种简洁方法,也许可以适应您希望从用户输入中收集 n_times 的代码?

import random
from collections import Counter


def coin_toss(n_times):
  all_outcomes = []
  for x in range(n_times):
    outcome = random.random()
    if outcome > .50:
      all_outcomes.append('H')
    if outcome <= .50:
      all_outcomes.append('T')
  return Counter(all_outcomes)


print(coin_toss(100))

>> Counter({'H': 56, 'T': 44})

正如其他人所提到的,您的缩进无处不在,但这可以通过一些试验和错误来解决。我跟踪尾部和头部结果的方式是将所有结果保存在一个列表中,然后使用名为“集合”的模块中的 Counter 对象,该模块可以轻松计算元素频率。

于 2018-02-16T22:00:07.003 回答
-1

我将 SO 的两个解决方案合二为一,进行了一次非常简单的抛硬币。它与您的解决方案有一些相似之处,但一切都被剥离了。

import random

def int_input(text):
    """Makes sure that that user input is an int"""
    # source: https://stackoverflow.com/questions/22047671

    while True:
        try:
            num = int(input(text))
        except ValueError:
            print("You must enter an integer.")
        else:
            return num

def main():
    """Asks for amount of tosses and prints sum(heads) and sum(tails)"""
    # source: https://stackoverflow.com/questions/6486877/

    tosses = int_input("How many times of flips do you want? ")

    heads = sum(random.randint(0, 1) for toss in range(tosses))
    tails = tosses - heads

    print('The {} tosses resulted in:\n{} heads and {} tails.'
          .format(tosses,heads,tails))    

main()
于 2018-02-16T22:07:28.550 回答