未定义/未使用的变量或意外缩进

2024-09-27 07:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这两个我都有。如果我能修好一个,另一个就会出现

这将获得引号的未定义/未使用变量错误

import random
def primary():
  print("Keep it logically awesome.")
 
  f = open("quotes.txt")
  quotes = f.readlines()
  f.close()

last = len (quotes) - 1
rnd = random.randint(0, last)

  print(quotes[rnd])

if __name__== "__main__":
primary()

如果我只是从print (quotes[rnd])中删除所有空格,那么我会得到“意外缩进”


Tags: importdef错误itrandom引号quotesawesome
3条回答

正确的代码如下所示

你必须在几个地方集中精力

import random
def primary():
    print("Keep it logically awesome.")

    f = open("quotes.txt")
    quotes = f.readlines()
    f.close()

    last = len (quotes) - 1  #this shud be intented
    rnd = random.randint(0, last) #this shud also be intented

    print(quotes[rnd]) #this shud be intented

if __name__== "__main__":
    primary() #if statements shud always be intented

编写单行if语句的另一种方法是

if __name__== "__main__": primary()

有关缩进的更多信息,请参阅: https://docs.python.org/3/reference/lexical_analysis.html#indentation

https://www.geeksforgeeks.org/indentation-in-python/amp/

https://www.w3schools.com/python/gloss_python_indentation.asp

import random
def primary():
    print("Keep it logically awesome.")
 
    f = open("quotes.txt")
    quotes = f.readlines()
    f.close()

    last = len(quotes) - 1
    rnd = random.randint(0, last)
    print(quotes[rnd])

if __name__== "__main__":
    primary()

希望这对你有帮助。享受吧

import random

def primary():
    print("Keep it logically awesome.")

    f = open("quotes.txt")
    quotes = f.readlines()
    f.close()

    last = len(quotes) - 1
    rnd = random.randint(0, last)

    print(quotes[rnd])

if __name__== "__main__":
  primary()

相关问题 更多 >

    热门问题