将我的代码分解成循环

时间:2017-03-22 19:29:55

标签: python python-3.x

我目前正在制作战舰游戏,以练习我的编程技巧。我有功能代码,但想知道是否有人可以帮助我将代码分解为for循环?

import random
def main():
    board = []
    for i in range(0,5):
        board.append(random.randint(1,50))

    print(board) #test purposes 

    guess=int(input("enter number between 1-50"))

    if guess == board[0]: 
       print("hit")
       board[0]="hit"
    elif guess != board[0]:
       print("miss")
       board[0]="miss"

注意我想多次执行if语句来检查板[0-5]。 我没有重复5次,而是想做这样的事情:

for x in range(0,5):
    if guess == board[x]:
        print("hit")
        board[x]="hit"
    else:
        print("miss")
        board[x]="miss"

但这不起作用,因为它只需要1个输入,而我希望它采用5.对于每个输入,它必须检查输入是否等于板[0-5]

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

在for循环中写入猜测,注意缩进

import random
def main():
    board = []
    for i in range(0, 5):
        board.append(random.randint(1, 50))
        guess = int(input("enter number between 1-50 : "))
        print(board)  # test purposes

        if guess == board[0]:
            print("hit")
            board[0] = "hit"
        elif guess != board[0]:
            print("miss")
            board[0] = "miss"

答案 1 :(得分:0)

我不太确定你想要实现的目标,但我相信它是:

import random 
def main():
    board = []
    for i in range(0,5):
        board.append(random.randint(1,50))

    print(board) #test purposes

    guesses = []
    try_nr = 0
    while try_nr < 5:
        try_nr += 1  
        guess = int(input("enter number between 1-50"))
        guesses.append(guess)

    for i in enumerate(guesses):
        i = i[0]
        if guesses[i] in board: 
            print("hit")
            # board[0]="hit" --> not quite sure what you want to achieve here?
        else:
            print("miss")
            # board[0]="miss" --> not quite sure what you want to achieve here?

NB1 :还有其他更简洁/密集的方式来编写代码,但这有助于您继续前进。如果需要,看看你是否可以为自己完善它。

NB2 :我已将您的elif声明更改为else。你的等式只能有两个可能的答案(命中或未命中)。通过使用elif,您强制python在使用else时完全重新考虑/重新计算您的if语句,它只考虑if语句一次。

答案 2 :(得分:0)

您可以使用enumerate()函数为for循环添加计数器。这将很有用。

board = [12, 4, 76, 2]
for index, number in enumerate(board):
    print index, number

#output
# 0 12
# 1 4
# 2 76
# 3 2
你说你想要5个猜测吗?你可以这样做:

for i in range(5):

    guess=int(input("enter number between 1-50"))

    for index, number in enumerate(board):
        if guess == number
            print("hit")
            board[index] = "hit"
        else:
            print("miss")
            board[index] = "miss"