Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

python - Calling up a def: function in an IF statement

It's been a while since I used python (been studying CISCO IOS) so I'm bit rusty. I have forgotten how to assign a function to an IF statement.

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():

Output

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

Process finished with exit code 1

The aim of the program is to calculate a range of IP addresses, and scan ip addresses for open ports.

I have created the code for the IP Calculator, but I have forgotten how to call up a function in an IF statement.

I want the program, to ask the user if they wish to calculate an IP network address or run a port scan. If the end user inputs "network" I want the program to run the def network clac(): function

It's something quite simple that I'm missing, this should be an easy question for some.

EDIT I HAVE SLOVED THIS ISSUE WITH ASSISTANCE FROM THIS COMMUNITY, I POST UPDATED CODE BELOW

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()

Now, I will work on the port scan function and ultimately convert this in to a GUI

question from:https://stackoverflow.com/questions/65948790/calling-up-a-def-function-in-an-if-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Replacing str(network) with "network" and str(port) with "port" should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...