You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Snakecoin区块链Python代码语法错误求助:引号处报错

修复Snakecoin区块链代码的Python语法错误

嘿,这个问题很常见——是Python2和Python3的语法差异搞的鬼!你遇到的红色高亮错误,根源在于Python3里print是一个函数,必须用括号包裹输出内容,而你的代码用了Python2的print语句写法。

修复后的完整代码

import hashlib as hasher
import datetime as date

class Block:
    def __init__(self, index, timestamp, data, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.hash_block()

    def hash_block(self):
        sha = hasher.sha256()
        sha.update(str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash))
        return sha.hexdigest()

def create_genesis_block():
    return Block(0, date.datetime.now(), "Genesis Block", "0")

def next_block(last_block):
    this_index = last_block.index + 1
    this_timestamp = date.datetime.now()
    this_data = "Hey! I'm block " + str(this_index)
    this_hash = last_block.hash
    return Block(this_index, this_timestamp, this_data, this_hash)

blockchain = [create_genesis_block()]
previous_block = blockchain[0]

num_of_blocks_to_add = 20

for i in range(0, num_of_blocks_to_add):
    block_to_add = next_block(previous_block)
    blockchain.append(block_to_add)
    previous_block = block_to_add
    # 关键修复:给print添加括号,适配Python3语法
    print('Block #{} has been added to the blockchain!'.format(block_to_add.index))
    print("Hash: {}\n".format(block_to_add.hash))

错误原因说明

  • 在Python2中,print是一个语句,可以直接写成print '内容';但Python3将print升级为了函数,必须用括号把要输出的内容括起来,也就是print('内容')。
  • 你代码里的其他部分在Python3中都是兼容的,只需要修改这两行print语句,就能正常运行代码,生成包含创世块在内的21个区块链节点,并打印每个区块的编号和哈希值。

内容的提问来源于stack exchange,提问作者StxrsStillFade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:26:57