gpt4 book ai didi

python - 将 Code Academy 战舰代码转换为 python 3.2

转载 作者:行者123 更新时间:2023-11-30 23:28:21 24 4
gpt4 key购买 nike

我正在编写代码学院战舰代码,我需要找到一种方法将其转换为 python 3.2 它在 2.7 中工作得很好,但在 3.2 中不起作用这是我到目前为止所拥有的:

import random

board = []

for x in range(0,5):
board.append(["O"] * 5)

def print_board(board):
for row in board:
print (" ").join(row)

print_board(board)

def random_row(board):
return random.randint(0,len(board)-1)

def random_col(board):
return random.randint(0,len(board[0])-1)

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")

print ship_row
print ship_col

if (guess_row == ship_row and guess_col == ship_col):
print ("Congratulations! You sank my battleship!")
else:
if guess_row < 0 or guess_row >= len(board) or guess_col < 0 or guess_col >= len(board):

print ("Oops, that’s not even in the ocean.")
else:
print ("You missed my battleship!")
guess_row = ("X")
guess_col = ("X")
print_board(board)
if board[guess_row][guess_col] == ("X"):
print ("You guessed that one already.")

就像我说的,它在 2.7 中有效,但在 3.2 中无效在 3.2 中,我收到 print Ship_row 的语法错误有什么想法吗?

最佳答案

3.x 中打印语句被 print() 函数取代

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline

Old: print # Prints a newline
New: print() # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!

是文档的摘录。 http://docs.python.org/3.0/whatsnew/3.0.html

关于python - 将 Code Academy 战舰代码转换为 python 3.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21661947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com