函数名称()和函数testCraps()无法正常工作。任何人都可以找出原因吗?

时间:2015-11-17 16:55:21

标签: python python-2.7

我试图将两个功能放在一起,我不能为我的生活弄清楚我做错了什么。

  1. 函数names()应该反复要求用户输入名称。当用户停止输入名称时,程序应打印每个名称输入的次数。这是我到目前为止所做的。

    def names():
        counter={}
        name=input('Enter next name:')
        while name!='':
            if name in counter:
                counter[name]+=1
            else:
                counter[name]=1
            name=input('Enter next name:')
        for name in counter:
            if counter[name]>1:
            print('There are {1} students named {2}.'.format(counter[name], name))
        else:
            print('There is {1} student named {2}.'.format(counter[name], name))
    
  2. 直到我停止输入名字为止。那时,它只是给我一个语法错误,在解析时说出了意外的EOF。"有人知道我需要修理什么吗?

    1. 函数testCraps()应该将正整数n作为输入并模拟骰子游戏的掷骰游戏。然后它应该在n场掷骰子之后返回用户的赢率。在这里,我得到了:

      def craps():
          import random
          dice=random.randrange(1,7)+random.randrange(1,7)
          if dice in (7,11):
              return 1
          elif dice in (2,3,12):
              return 0
          else:
              newRoll=random.randrange(1,7)+random.randrange(1,7)
          while newRoll not in (7,dice):
              newRoll=random.randrange(1,7)+random.randrange(1,7)
          if newRoll==dice:
              return 1
          else:
              return 0
      
      def testCraps(n):
          count=0
          for i in range(n):
              if craps()==1:
                  count+=1
          return count/n
      
    2. 出于某种原因,testCraps()似乎总是给我0,我无法看到它的任何问题。你能看到我失踪的东西吗?

1 个答案:

答案 0 :(得分:1)

names()的问题在于,在字符串格式设置时,您应该从{0}而不是{1}开始编制索引。纠正这个和缩进后,它工作正常:

def names():
    counter={}
    name=input('Enter next name:')
    while name!='':
        if name in counter:
            counter[name]+=1
        else:
            counter[name]=1
        name=input('Enter next name:')
    for name in counter:
        if counter[name]>1:
            print('There are {0} students named {1}.'.format(counter[name], name))
        else:
            print('There is {0} student named {1}.'.format(counter[name], name))

names()

互动环节:

Enter next name:Galax
Enter next name:Test
Enter next name:Galax
Enter next name:
There is 1 student named Test.
There are 2 students named Galax.

这是掷骰子代码,缩进修正,并且上面的一条评论中提出了施法浮动:

def craps():
    import random
    dice=random.randrange(1,7)+random.randrange(1,7)
    if dice in (7,11):
        return 1
    elif dice in (2,3,12):
        return 0
    else:
        newRoll=random.randrange(1,7)+random.randrange(1,7)
        while newRoll not in (7,dice):
            newRoll=random.randrange(1,7)+random.randrange(1,7)
        if newRoll==dice:
            return 1
        else:
            return 0

def testCraps(n):
    count=0
    for i in range(n):
        if craps()==1:
            count+=1
    return float(count)/n

print(testCraps(100))

示例输出:

0.44