Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何仅允许数字作为输入?-python_Python_Input - Fatal编程技术网

如何仅允许数字作为输入?-python

如何仅允许数字作为输入?-python,python,input,Python,Input,我想用IP格式制作一个简单的Python IP跟踪器,但是我很困惑,因为我无法过滤输入。 这是我的代码: while True: ip= raw_input("What Your Target IP : ") url = "http://blabla.com/json/" response = urllib2.urlopen(url + ip) data = response.read() values = json.loads(data) pr

我想用IP格式制作一个简单的Python IP跟踪器,但是我很困惑,因为我无法过滤输入。 这是我的代码:

while True:
    ip= raw_input("What Your Target IP : ")
    url = "http://blabla.com/json/"
    response = urllib2.urlopen(url + ip)
    data = response.read()
    values = json.loads(data)

    print("------------------------------------")
    print "\r"
    print(" IP: " + values['query'])
    print(" City: " + values['city'])
    print(" Region: " + values['regionName'])
    print(" Country: " + values['country'])
    print(" Time Zone: " + values['timezone'])
    print "\r"

    break

您可以使用正则表达式或IP地址模块来解决问题

import re
import os
import urllib2
import json
while True:
    ip = raw_input("What Your Target IP : ")
    if not re.match(("^\d{0,9}\.\d{0,9}\.\d{0,9}\.\d{0,9}$"), ip):
        print ("Error! Make sure you only use numbers")
    else:
        print("You picked number "+ ip)
        url = "https://blablabla/"
        response = urllib2.urlopen(url + ip)
        data = response.read()
        values = json.loads(data)

print("------------------------------------")
print "\r"
print(" IP           :  " + values['ip'])
print(" City         :  " + values['city'])
print(" Region       :  " + values['region'])
print(" Country      :  " + values['country_name'])
print(" Continent    :  " + values['continent_name'])
print(" Time Zone    :  " + values['time_zone'])
print(" Currency     :  " + values['currency'])
print(" Calling Code :  " + "+" + values['calling_code'])
print(" Organisation :  " + values['organisation'])
print(" ASN          :  " + values['asn'])
print "\r"

使用stdlib模块。您的标题具有误导性。你不想检查数字,你想检查有效的IP地址。我这里有一个错误,但我不知道如何在comment.print error中使用代码格式!确保只使用数字^IndentationError:unindent与任何外部缩进级别都不匹配检查时出错<回答后是我的代码您的缩进与此处建议的答案不匹配