变量未定义Python

时间:2015-03-10 10:45:21

标签: python syntax

我试图制作某个代码并且它一直在给我一个语法错误:

  

"文件" N:/ piethorn / Python工作簿/文件简介   handling / challenge.py",第5行,in       string = str(string + character)
  NameError:name' string'未定义"

原始代码是:

> f = open("temp","r")   
f.seek(0)  
character = str(f.read(1))  
if character !=" ":  
>     string = str(string + character)  
>     character = f.read(1)  
else:  
>     print(string)  
>     f.close

4 个答案:

答案 0 :(得分:0)

您需要string。从错误消息中可以明显看出,string超出else块的范围。修改后的代码应为: -

> f = open("temp","r")   
f.seek(0)  
character = str(f.read(1))  
string = ''
if character !=" ":  
>     string = str(string + character)  
>     character = f.read(1)  
else:  
>     print(string)  
>     f.close

答案 1 :(得分:0)

f = open("temp","r")   
f.seek(0)   
string ="" # definition
character = str(f.read(1))  
if character !=" ":  
 string = str(string + character)  # definition
 character = f.read(1)  
else:  
 print(string)  # usage
 f.close()

else中,正在定义string。如果print string等于character " ",则string定义为elsestringstring相同}。


此外,您正在使用名为String的变量,同时还有一个名为{{1}}的Python模块。您最好以某种方式重命名变量,例如{{1}}。

答案 2 :(得分:0)

您没有在Program

中定义string变量
  f = open("temp","r")   
  f.seek(0)  
  string=""
  character = str(f.read(1))  
  if character !=" ":  
       string = str(string + character)  
       character = f.read(1)  
  else:  
       print(string)  
       f.close

答案 3 :(得分:0)

首先将string定义为空字符串:

f = open("temp","r")   
f.seek(0)  
character = str(f.read(1))  
string = ""
if character !=" ":  
     string = str(string + character)  
     character = f.read(1)  
else:  
     print(string)  
     f.close
print(string)