我是 Python 编程新手,无法将 IP 地址存储在变量 (ip) 中
ip = input("Enter IP address: ")
# 192.168.0.1 (Example)
print ("you entered: "+ip)
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息,不知道该怎么办。
小智 5
我认为您正在使用 Python 2.x。如果是这样,则将input其输入评估为真正的 Python 代码。
换句话说,当您输入时192.168.0.1,SyntaxError会引发a ,因为输入包含非法语法:
>>> input()
192.168.0.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
192.168.0.1
^
SyntaxError: invalid syntax
>>>
Run Code Online (Sandbox Code Playgroud)
要解决此问题,您需要raw_input改用:
ip = raw_input("Enter IP address: ")
Run Code Online (Sandbox Code Playgroud)
与 不同input,raw_input总是返回一个字符串对象:
>>> raw_input()
192.168.0.1
'192.168.0.1'
>>>
Run Code Online (Sandbox Code Playgroud)