我试图制作某个代码并且它一直在给我一个语法错误:
"文件" 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
答案 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
定义为else
,string
与string
相同}。
此外,您正在使用名为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)