猿问

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

我不断得到这两个。如果我设法修复一个,另一个就会出现。


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


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])我会得到“意外缩进”


慕标琳琳
浏览 114回答 3
3回答

慕的地10843

正确的代码如下所示。你必须在几个地方意图。import randomdef 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 intentedif __name__== "__main__":    primary() #if statements shud always be intented编写单行 if 语句的另一种方法是if __name__== "__main__": primary()

斯蒂芬大帝

import randomdef 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()希望这对您有所帮助。享受!

RISEBY

import randomdef 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()
随时随地看视频慕课网APP

相关分类

Python
我要回答