0

Hi I'm new to python programming and can't find this help anywhere

I have a user input value that I want to search for in a specified list exp :

option=input("option: ")

iplist=['192.168.1.1', '192.168.1.2', '192.168.1.254']

while option <= "3":
  #this is wrong. Help!
  nub = iplist[option]
  subprocess.call(["ping", nub])

I want The Option Of The User To Be The Number Inside The List For This program the output should be :

Option : 0

Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64

Ping statistics for 192.168.1.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 2ms, Maximum = 2ms, Average = 2ms
Torxed
  • 22,866
  • 14
  • 82
  • 131

1 Answers1

0

Why do you need a loop? Use in to check if the input value exists in the list and follow accordingly:

option=input("option: ")
iplist=['192.168.1.1', '192.168.1.2', '192.168.1.254']

if option in iplist:
   # do the rest
    pass

OR:

If you want to get the Index of the element in the list:

for index, elem in enumerate(iplist):
    if option == elem:
        print("Element found at Index: {}".format(index))

OUTPUT:

option: 192.168.1.2
Element found at Index: 1

EDIT 2:

There are a couple of things to note first:

  1. Take the input from the user and convert it to an int since you cannot access the list with str indexing:

  2. I still do not see a point of loop

So:

import subprocess
option= int(input("option: "))    # 1
iplist=['192.168.1.1', '192.168.1.2', '192.168.1.254']

nub = iplist[option]
subprocess.call(["ping", nub])

OUTPUT:

Pinging 192.168.1.2 with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 192.168.1.2:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
DirtyBit
  • 16,613
  • 4
  • 34
  • 55