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

运行Python绘制平行四边形代码时提示'row'未定义是什么原因?

报错原因

  • 你在rows()函数中定义的row属于函数局部变量,作用域仅局限在rows()函数内部,make_shape()函数无法直接读取该变量。
  • 同理de()函数中定义的character也是局部变量,row报错修复后也会触发character未定义的报错。
  • 你在main()中调用rows()、de()时,没有接收两个函数返回的结果,返回值直接被丢弃,其他函数自然无法获取对应的数值。

修复方案

方案1:通过参数传递变量(推荐,符合Python函数封装规范)

不使用全局变量,通过函数返回值+参数传递的方式共享变量,代码可维护性更高:

def pe():
  print("This program will output a parallelogram.")
 
def rows():
  row = int(input("How long do you want each side to be?"))
  return row
 
def de():
  character = input("Please enter the character you want it to be made of:")
  return character # 补充返回字符值的逻辑

# 给图形生成函数增加参数,接收边长和绘制字符
def make_shape(row, character):
  for i in range(row):
    for j in range(1, i + 1):
        print(character, end="")
    print()

  # 原代码此处缩进错误,已经调整到外层循环
  for k in range(1, row + 1):
    for l in range(1, row + 1):
      if(l < k):
          print(' ', end = "")
      else:
          print(character, end = "")
    print()
 
def main():
  pe()
  row = rows() # 接收返回的边长值
  character = de() # 接收返回的绘制字符
  make_shape(row, character) # 传入参数调用图形生成函数
 
main()

方案2:声明全局变量(不推荐,会增加代码调试和维护成本)

如果一定要用全局变量实现,需要在修改全局变量的函数内提前声明global关键字:

# 提前定义全局变量
row = 0
character = ''

def pe():
  print("This program will output a parallelogram.")
 
def rows():
  global row # 声明此处修改的是全局变量row
  row = int(input("How long do you want each side to be?"))
 
def de():
  global character # 声明此处修改的是全局变量character
  character = input("Please enter the character you want it to be made of:")
 
def make_shape():
  for i in range(row):
    for j in range(1, i + 1):
        print(character, end="")
    print()
 
    for k in range(1, row + 1):
      for l in range(1, row + 1):
        if(l < k):
            print(' ', end = "")
        else:
            print(character, end = "")
    print()
 
def main():
  pe()
  rows()
  de()
  make_shape()
 
main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:39:04