在 IF 语句中调用 def: 函数

时间:2021-01-29 04:29:53

标签: python function if-statement

我已经有一段时间没有使用 python(一直在研究 CISCO IOS),所以我有点生疏了。我忘记了如何将函数分配给 IF 语句。

import ipaddress

q1= input("Please enter 'network' to calculate an IP address range, or enter 'port' to scan an ip address for open ports  ")
if (q1 == str(network)):
    networkclac()
if (q1 == str(port)):
    portscan()


def networkclac():
    try:
        network = input('please input network address: ')
        network = ipaddress.ip_network(network)
        print(network)

    except ValueError:
        print('That is not a network address')

    iplist= list(ipaddress.ip_network(network).hosts())
    for i in range(10,len(iplist),2):
        print(iplist[i])

#def portscan():

输出

Traceback (most recent call last):
  File "C:\Users\shane\PycharmProjects\RodCertIV\ITCNWK409.py", line 4, in <module>
    if (q1 == str(network)):
NameError: name 'network' is not defined

Process finished with exit code 1

该程序的目的是计算 IP 地址范围,并扫描 IP 地址以获取开放端口。

我已经为 IP 计算器创建了代码,但我忘记了如何在 IF 语句中调用函数。

我想要该程序,询问用户是否希望计算 IP 网络地址或运行端口扫描。如果最终用户输入“网络”,我希望程序运行 def network clac(): function

我遗漏了一些非常简单的问题,这对某些人来说应该是一个简单的问题。

编辑 我在这个社区的帮助下解决了这个问题,我在下面发布了更新的代码

import ipaddress

def f1():
    try:
        network = input('please input network address with the prefix: ')
        network = ipaddress.ip_network(network)
        print(network)

    except ValueError:
        print('That is not a network address')

    iplist= list(ipaddress.ip_network(network).hosts())
    for i in range(10,len(iplist),2):
        print(iplist[i])

#def portscan():

print("Please enter 'network' to calculate an IP address range")
print("Please enter 'port' to scan for open ports")

q1= input("please input your choice:  ")
if q1 == "network":
    f1()
#if q1 == "port":
    #f2()

现在,我将研究端口扫描功能并最终将其转换为 GUI

2 个答案:

答案 0 :(得分:1)

str(network) 替换为 "network" 并将 str(port) 替换为 "port" 应该可以工作。

答案 1 :(得分:0)

我能够通过在 def 函数之后对用户输入部分进行编码来解决这个问题。 即计算机在读取用户输入函数之前先读取def函数

import ipaddress

def f1():
    try:
        network = input('please input network address: ')
        network = ipaddress.ip_network(network)
        print(network)

    except ValueError:
        print('That is not a network address')

    iplist= list(ipaddress.ip_network(network).hosts())
    for i in range(10,len(iplist),2):
        print(iplist[i])

#def portscan():


q1= input("Please enter 'network' (with prefix) to calculate an IP address range, or enter 'port' to scan an ip address for open ports  ")
if q1 == "network":
    f1()
#if q1 == "port":
    #f2()
相关问题