basically I need the user to enter an ip address.
All I need to do is check that it's valid (0-255; 4 octets).
lets say a user enters 192.168.10.1,
how can I break it down to 192, 168, 10, 1?
Do this:
while True:
ip = raw_input("Please enter an ip address")
ip_split = ip.split(".")
if len(ip_split) != 4:
print "Must have 4 numbers"
elif not all(number.isdigit() for number in ip_split):
print "Must be numbers"
elif not all(0 <= int(number) <= 255 for number in ip_split):
print "Numbers must be in 0-255 range"
else:
ips = [int(number) for number in ip_split]
break
You can use the split method:
your_string.split(separator)
In your case:
ip = "191.168.10.1"
values_list = ip.split(".")
I have this 2 regexes to check this
import re
ip4 = re.compile(r'^(?:(?:25[0-5]|2[0-4]\d|1\d\d|\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|\d?\d)$')
ip6 = re.compile(r'^(?:[\da-fA-F]{1,4}:){7}[\da-fA-F]{1,4}$')
You can do it in several ways. This could be a solution:
ip = "192.168.10.666"
octates = ip.split('.',4)
flag = True
for each_octate in octates:
num = int(each_octate)
if num>=0 and num<=255:
continue
else:
flag = False
break
if flag == True:
print "IP is correct!"
else:
print "IP is incorrect"
you can take the ip address in as a string and then from there split the str by "." and then check each member for that criteria.
ip = input("Enter Ip address: ")
address = ip.split('.')
if len(address) == 4:
for num in address:
if 255 >= num >= 0:
pass
else:
print("Invalid Ip Address!")
else:
print("Invalid Ip Address!")
Related
This is an IP address problem where I need to implement a function is_valid_IP that takes an arbitrary string and determines if it represents a valid IPv4 or IPv6 address.
IPv4_STRING = "127.0.0.1"
IPv4_INVALID_STRING = "300.0.0.1"
IPv6_STRING = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
IPv6_INVALID_STRING = "2001:0db8:85a3:0000:0000:8a2e:0370:7334:7334"
INVALID_IP_STRING = "Some arbitrary string"
def is_valid_IPv4_octet(octet: str):
for element in ip_list:
if int(element) < 0 or int(element) > 255 :
return False
return True
def is_valid_IPv4(ip: str):
if ip.count('.') != 3:
return False
quit()
ip_list = list(map(str, ip.split('.')))
return is_valid_IPv4_octet(ip_list)
def is_valid_IPv6_hextet(hextet: str):
for element in ip_list:
if int(element,16) < 0 or int(element,16)>65535 :
return False
return True
def is_valid_IPv6(ip: str):
if ip.count(':')!=7:
return False
quit()
ip_list=list(map(str,ip.split(':')))
return is_valid_IPv6_hextet(ip_list)
def is_valid_IP(ip: str):
if( is_valid_IPv4() or is_valid_IPv6() == True):
print("Valid IP Address")
else:
print("Invalid IP Address")
print(
f"{IPv4_STRING} is a valid IP Address:",
is_valid_IP(IPv4_STRING))
print(
f"{IPv4_INVALID_STRING} is a valid IP Address:",
is_valid_IP(IPv4_INVALID_STRING),
)
print(
f"{IPv6_STRING} is a valid IP Address:",
is_valid_IP(IPv6_STRING))
print(
f"{IPv6_INVALID_STRING} is a valid IP Address:",
is_valid_IP(IPv6_INVALID_STRING),
)
print(
f"{INVALID_IP_STRING} is a valid IP Address:",
is_valid_IP(INVALID_IP_STRING),
)
The IDE gives me
Traceback (most recent call last):
File "C:\Users\jerry\PycharmProjects\pythonProject1\main.py", line 43, in <module>
is_valid_IP(ip)
File "C:\Users\jerry\PycharmProjects\pythonProject1\main.py", line 38, in is_valid_IP
if( is_valid_IPv4() or is_valid_IPv6() == True):
TypeError: is_valid_IPv4() missing 1 required positional argument: 'ip'
Can someone tell me why? I've been surfing a bit, the general opinion is i need to put something in the bracket of the function. But in this case there is somehting inside...So i dont really know where went wrong.
You are missing the arguments here:
def is_valid_IP(ip: str):
#added ip
if( is_valid_IPv4(ip) or is_valid_IPv6(ip) == True):
print("Valid IP Address")
else:
print("Invalid IP Address")
Also since the functions already return True or False you can get rid of the == True
def is_valid_IP(ip: str):
if( is_valid_IPv4(ip) or is_valid_IPv6(ip)):
print("Valid IP Address")
else:
print("Invalid IP Address")
def is_valid_IP(ip: str):
if( is_valid_IPv4() or is_valid_IPv6() == True):
print("Valid IP Address")
else:
print("Invalid IP Address")
here you are calling 2 functions is_valid_IPv4 and is_valid_IPv6. These 2 need an input which is ip.
I'm trying to make a script where someone can type a username and the script will check if the directory exists, returning true or false as it goes through the list. Currently, the output is always "Not found"/false even though there should definitely be at least one true returned.
def scan():
username = input("Type in the username here: ")
i = 0
searchFor = folderList[i] + username
listLength = len(folderList)
while i < listLength:
if os.path.isdir(searchFor) == True:
print ("Folder found!")
i += 1
elif os.path.isdir(searchFor) == False:
print ("Not found")
i += 1
For reference, this code below which doesn't use a loop works fine, as if I type in the username and the correct index for the element of the directory that exists, it returns true, otherwise if I choose another index it's false as it should, so it's not an issue with the elements or folder permissions.
def test():
username = input("Type in the username here: ")
i = int(input("Type list index number here: "))
searchFor = folderList[i] + username
if os.path.isdir(searchFor) == True:
print("Folder found: " + searchFor)
else:
print("Not found!")
Would appreciate any help!
I'm writing an answer because the existing answers fail to address the problem, and I think they confuse things more than anything.
You currently have searchFor outside of the loop. As a result, it will be given a value once before the loop is entered, then its value is never changed. If you want its value to change, you must manually reassign it:
while i < listLength:
searchFor = folderList[i] + username
Although, really, a for loop should be used here instead (but not as #Sai suggests):
for folder in folderList:
searchFor = folder + username
You never use i for anything other than indexing folderList, so you should just iterate the folderList directly instead. Iterating a range is generally regarded as a code smell if you're just using the number to index a list.
This code will help you
def scan():
username = input("Type in the username here: ")
is_exists = False
for i in range(0,len(folderList)):
searchFor = folderList[i] + username
if os.path.isdir(searchFor):
is_exists = True
break
if is_exists:
print("Search is found")
else:
print("Not Found")
def scan():
username = input("Type in the username here: ")
i = 0
listLength = len(folderList)
while i < listLength:
searchFor = folderList[i] + username
if os.path.isdir(searchFor) == True:
print ("Folder found!")
i += 1
elif os.path.isdir(searchFor) == False:
print ("Not found")
i += 1
I'm currently creating a text based console program in python and I want to add a command to display the current weather using a zip code. I have tried googling it extensively and can't seem to find anything good. The solutions that would work for what I'm trying to do are all using technology I'm not familiar with that are used to make actual apps with python. There is currently no UI and I'm a beginner in python so the more readable and easily understandable the solution the better.
#import statements
import math#import math
import os#access the operating system
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
import time
#end import statement
# welcome user
print("welcome to geeko an all in one desktop helper!")
#end welcome
#variables
username = input("Please enter your username: " )#gets username
sudo = False # sets sudo to false indicating normal privledges
if (username == "Caelin"): # if the user enters the sudo username prompt them for a password
sudoPassword = input("enter sudo password: ")# prompt for passcode
sudoLn = False #sets sudo line mode to false. this line mode is used for sudo commands
pi = math.pi
loc_id = 'USAL0504'
def wrongLineError():
if(sudoLn):
print("You are on the sudo line this is purely for special commands normal commands don't work here type \"switch\" to switch to cmd.ln")
elif(sudoLn == False and sudo == False):
print("You do not have sudo priviledges")
elif(sudoLn == False and sudo == True):
print("to use sudo commands you must be on the sudo line mode type \'switch\' to switch to the sudo line")
def sendEmailMessageOnly(message, password, recipient):
send_to_email = recipient # Who you are sending the message to
server = smtplib.SMTP('smtp.gmail.com', 587) # Connect to the server
server.starttls() # Use TLS
server.login(email, password) # Login to the email server
server.sendmail(email, send_to_email , message) # Send the email
server.quit() # Logout of the email server
def sendFormattedEmail(password, recipient, subject, message):
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, recipient, text)
server.quit()
def sendMultipleFormattedEmails(password, recipients, subject, message):
for recipientEmail in recipients:
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = recipientEmail
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, recipientEmail, text)
server.quit()
#end variables
print ("Hello " + username + "!")# say special welcome
#check if user is root if so alert them and give them sudo status else alert them and leave sudo at a default of false
if(username == "Caelin" and sudoPassword == "bigGlassRemote"):
print("Welcome! you are the root user and therefore have elevated priviledges")
email = input('please enter your email: ')
password = input("please enter your email password: ")
print('logging into email...')
time.sleep(1)
print("logged into email!")
sudo = True
else:
print("You are not the root user and have normal priviledges")
while(True): #run an infinite loop prompting the user for command line inputs
if(sudoLn == False):
command = input(username + "-cmd.ln: ") # if sudo line mode if off use the cmd.ln prompt
else:
command = input(username + "-cmd.sudo: ") # otherwise prompt with cmd.sudo to indicate you are using sudo line mode
if(command == 'welcome'):
if(sudoLn == False): # checks if you are on cmd line
print("Hello " + username) # if the welcome command is used say hello *username*
else: # if you are the sudo line
wrongLineError()
elif(command == "switch"): # if the command is switch
if(sudo): # then check for sudo priviledges
# togles sudoLn
if(sudoLn):
sudoLn = False
else:
sudoLn = True
else:
wrongLineError()
elif(command == 'add'):
if(sudoLn == False):
num1 = input("type the first number to add here: ")
num2 = input("type the second number to add here: ")
ans = float(num1) + float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == 'subtract'):
if(sudoLn == False):
num1 = input("type the first number to subtract here: ")
num2 = input("type the second number to subtract here: ")
ans = float(num1) - float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "multiply"):
if(sudoLn == False):
num1 = input("type the first number to multiply here: ")
num2 = input("type the second number to multiply here: ")
ans = float(num1) * float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "divide"):
if(sudoLn == False):
num1 = input("type the first number to divide here: ")
num2 = input("type the second number to divide here: ")
ans = float(num1)/float(num2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of circle"):
if(sudoLn == False):
r = input("type the radius here: ")
ans = pi*(float(r)**2)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of rectangle"):
if(sudoLn == False):
l = input("type the length here: ")
h = input("type the width here: ")
ans = float(l)*float(h)
if(ans == round(ans)):
print(int(ans))
else:
print(ans)
else:
wrongLineError()
elif(command == "area of triangle"):
l = input("type the length here: ")
h = input ("type the height here: ")
ans = (float(l) * float(h))/2
if(ans == round(ans)):
print(int(ans))
else :
print(ans)
elif(command == 'pi'):
if(sudoln):
print(pi)
else:
wrongLineError()
elif(command == "edit file anywhere"):
if(sudoLn):
path = input("enter the path to the file (if the file doesen't exist it will be created): ")
file = open(path, "w+")
Exit = False
while(not Exit):
write = input("type what you would like to be written on the document. type !#exit to return to the the command line: ")
if(write == "!#exit"):
file.close()
Exit = True
else:
file.write(write)
else:
wrongLineError()
elif(command == "delete file anywhere"):
if(sudoLn):
path = input("enter the path to the file you wish to delete: ")
os.remove(path)
print(path + "has been removed")
else:
wrongLineError()
elif(command == 'send unformatted email'):
if(sudoLn):
recipient = input('enter the recipient\'s email address: ')
msg = input("enter the content of the email: ")
print('Sending email...')
sendEmailMessageOnly(msg, password, recipient)
print('Email sent!')
else:
wrongLineError()
elif(command == "send formatted email"):
if(sudoLn):
subject = input('enter the subject line: ')
recipient = input('enter the recipient\'s email address. type multiple to send an email to multiple recipients: ')
if(recipient == 'multiple'):
sendMultiple = True
repeat = True
i = 1
recipient = []
while(repeat):
newRecipient = input('recipient%s\'s email address. type !#continue to continue to select a message and send the email: ' % i)
if(newRecipient == '!#continue'):
repeat = False
else:
recipient.append(newRecipient)
i += 1
message = input("enter the content of the email: ")
print('Sending email...')
if(not sendMultiple):
sendFormattedEmail(password, recipient, subject, message)
else:
sendMultipleFormattedEmails(password, recipient, subject, message)
print("Email sent!")
else:
wrongLineError()
elif(command == "help"):
if(sudoLn):
print(username + """-sudo.ln command help:
>>edit file anywhere > input(s): path > Takes a file path and edits that file.
If the file doesn't already exist it is created.
If you wish to edit a file in the same location as geeko simply enter the name and leave out the path.
>>delete file anywhere > input(s): path > Takes a file path and deletes the file with that path.
If you wish to delete a file in the same location as geeko simply enter the name and leave out the path.
>>send unformatted email > input(s): recipient, message > Sends an email to the recipient containing the message you entered.
>> send formatted email > input(s): recipient, subject line, message > Sends an email to the recipient with the entered subject line and message.
This also enters To and From information into the email.
>>help > no inputs > Shows this help message.
A different message is shown for cmd.ln and sudo.ln.
>>close > input(s): confirmation > If confirmed exits out of geeko.
END %s-sudo.ln HELP""" % username)
else:
print(username + """-cmd.ln command help:
>>add > input(s): first number, second number > Adds two numbers together.
>>subtract > input(s): first number, second number > Subtracts the second number from the first number.
>>multiply > input(s): first number, second number > Multiplies the two numbers together.
>>divide > input(s): first number, second number > Divides the first number by the second number.
>>area of rectangle > input(s): length, width > Calculates the area of a rectangle with the given length and width.
>>area of triangle > input(s): length, height > Calculates the area of a triangle with the given length and height.
>>area of circle > input(s): radius > Calculates the area of a triangle with the given radius.
>>pi > no inputs > Prints the first 16 digits of pi
>>welcome > no inputs > Gives you a special welcome.
>>print reversed sentence > input(s): sentence > Prints the sentence backwards.
>>help > no inputs > Shows this help message.
The help message is different in cmd.ln and sudo.ln.
>>close > input(s): confirmation > If confirmed exits out of geeko.
END %s-cmd.ln HELP""" % username )
elif(command == 'print reversed sentence'):
sentence = input("enter the senctence you want to reverse: ")
sentence = sentence[::-1]
print(sentence)
elif(command == 'weather'):
get_weather(loc_id)
elif(command == "close"):
confirmedOrDenied = False
while(not confirmedOrDenied):
confirmation = input("are you sure you want to close geeko [Y/N]: ")
if(confirmation == 'y' or confirmation == 'Y'):
exit()
elif(confirmation == 'n' or confirmation == 'N'):
confirmedOrDenied = True
print("cancelled")
else:
print('invalid response please enter Y or N')
else:
print(command + ' is not a valid command make sure everything is spelled correctly') # if no registered command was entered return invalid command
There are 2 main ways to do this.
The first one is to webscrape, using requests and beautifulsoup4. This can most easily be done from google, since if you search "weather {city-name}" it gives you a summary of the weather there.
The second is to use an api such as openweathermap, for which there is a great geeksforgeeks tutorial on:
I want user enter IP subnet which is formatted x.x.x.x/y. But if user enters anything different this format, there should be warning as below. But below code is not working as I want.
What is your suggestion?
def test():
while True:
val = raw_input("enter IP:")
try:
IP=ipaddress.ip_network(str(val),True)
except:
if val == "":
print " Enter subnet:"
else:
print " IP should be formatted X.X.X.X/Y"
test()
So I'm new to python and I'm writing a program that accepts a phone number in the format XXX-XXX-XXXX and changes any letters to their corresponding numbers. I need to check the entry and make sure it's in the correct format, and if its not, allow it to be reentered. I'm having a hard time getting it to prompt me for a new number, and even when that works sometimes, it will still translate the original, wrong phone number.
This is my code so far:
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
validNumber(phone_number)
translateNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
phone_number=input('Please enter a valid phone number: ')
return False
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return False
return True
def translateNumber(phone_number):
s=""
for char in phone_number:
if char is '1':
x1='1'
s= s + x1
elif char is '-':
x2='-'
s= s + x2
elif char in 'ABCabc':
x3='2'
s= s + x3
.....etc this part isn't important
You probably want to use a while loop to force the user to input a valid number. Something like:
def main():
phone_number = ""
while not validNumber(phone_number):
phone_number = input('Please enter a phone number in the format XXX-XXX-XXXX: ')
translateNumber(phone_number)
(You may need to replace input with raw_input if you're using Python 2.7,)
Here is a full, working solution.
import re
from string import maketrans
phone_match = re.compile("^(\w{3}-\w{3}-\w{4})$")
def validPhone(number):
match = phone_match.match(number)
if match:
return match.groups(0)[0]
return None
phone_number = ''
while not validPhone(phone_number):
phone_number = raw_input("Give me your digits!: ")
phone_in = "abcdefghijklmnopqrstuvwxyz"
phone_out = "22233344455566677778889999"
transtab = maketrans(phone_in, phone_out)
print phone_number.lower().translate(transtab)
Examples:
Give me your digits!: 949-POO-PTOO
949-766-7866
Give me your digits!: 555-HOT-KARL
555-468-5275