Skip to main content
 首页 » 编程设计

python之硬币翻转模拟

2025年05月04日9tuyile006

我刚开始学习 Python,正在尝试编写以下问题的代码:

投币模拟 - 编写一些代码来模拟 throw 单个硬币,但用户可以决定 throw 多少次。代码应记录结果并计算反面和正面的数量。

以下是我的代码:

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 循环中,因此它会在继续询问我的输入时不断检查条件。

请您参考如下方法:

我认为您一定是在某处弄乱了缩进。我复制了您的代码,修复了 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()) .它的可读性通常也低于其他结构。