Restricting the User Input to Alphabets - python

I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?

If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.

I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():

One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.

Related

Passwords/username from a file

I've recently been having trouble writing a program that involves taking the password and username from a .txt file. So far I have written:
username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()
print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
while True:
try:
nametry = input("What is your Username player1?: ")
break
except ValueError:
print("Not a valid input")
(The various prints are to help me to see what the error is)
The password is successfully extracted from the file however when it is put into a variable and put through an if statement, it doesn't work!
Any help would be much appreciated!
Hopefully this is a simple fix!
Your problem is that readlines() function lets the \n character remain in your text lines and that causes the texts to not match. You can use this instead when opening the file:
name = username_file.read().splitlines()
give it a try.
the readlines function doen't strip the newline character from the end of the lines, so eventough you wrote "samplename" as input, it won't equal "samplename\n".
You can try this:
name = [x.rstrip() for x in username_file.readlines()]

Very new to Python and need guidance

interactive input prompt to open browsers...(will print something instead for now).
chrm = ['Google Chrome', 'Chrome']
input("type a browser..: ")
if chrm[0:1] == input():
print("starting: " + chrm)
What my intention is for this little thing is for a person to write one of the two possible input options..."Google Chrome" or "Chrome" to get a certain response. like openfile or printing something. but I can't seem to get it right.
You should assign the returning value of input() to a variable, and use the in operator to test if it is one of the values in the chrm list:
chrm = ['Google Chrome', 'Chrome']
i = input("type a browser..: ")
if i in chrm:
print("starting: " + i)

Python program giving unexpected results, why?

My python program is giving unexpected results within the regular expressions functions, when I enter a number plate for recognition, it tells me it's invalid, although it is valid and I don't know why?
I would be grateful if you could tell me what's wrong and give a possible solution, as this is a very important homework assignment.
#Start
#04/02/2016
bad=[]#initialise bad list
data="Y"#initialise value to prevent infinite loop
standardNumberPlateObj=""
NumPlate=""
import re#import re functions
import pickle#import pickle function
print ("Welcome to the number plate recognition program.\n\n")
choice=input("Press 1 to input number plates and save\nPress 2 to read binary number plate file: ")
if choice == "1":
while data=="Y":# while loop
NumPlate = input("Input Registration number in format (XX01 XXX) *With a space at the end!*:\n\n") #user input for numberplate
standardNumberPlateObj=re.match(r'\w\w\d\d\s\w\w\w\s', NumPlate, re.M|re.I)#validate that numberplate is valid
if standardNumberPlateObj:
print("Verification Success")
data=input(str("Would you like to continue? (Y/N):"))
else:
print("Verification Failed")
bad.append(NumPlate)#add numberplate to bad list
data=input(str("Would you like to continue? (Y/N):"))#ask user to continue
while data=="N":#saving number plates to file if user enters N
f = open("reg.dat", "wb")
pickle.dump(bad, f)
f.close()
print ("\nRestart the program to read binary file!")#ending message
break
elif choice == "2":
print ("\nBad number plates:\n\n")
f=open("reg.dat", "rb")
Registrations = pickle.load(f)
print(Registrations)
f.close()
else:
print ("Please enter a valid choice!")
print ("\n END of program!")
It's not really possible to tell without an example input and the expected and the actual result.
But judging from the expression \w\w\d\d\s\w\w\w\s and your example in the prompt (XX01 XXX), I'd say that your regular expression is expecting a space in the end, while your input doesn't provide one.

New line for input in Python

I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number
How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number
It didn't work.
Put it inside of the quotes:
Number = raw_input("Enter a number\n")
\n is a control character, sort of like a key on the keyboard that you cannot press.
You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")
If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()
I do this:
print("What is your name?")
name = input("")
print("Hello" , name + "!")
So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!
# use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed
It will also work with: your_name = input("What is your name?\n")
in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
i = input("Enter the numbers \n")
for a in range(len(i)):
print i[a]
if __name__ == "__main__":
enter_num()
In the python3 this is the following way to take input from user:
For the string:
s=input()
For the integer:
x=int(input())
Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))

what is wrong in my python code?

#!usr/bin/python
listofnames = []
names = input("Pls enter how many of names:")
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print listofnames
error
inname = input("Enter the name " + str(x))
File "", line 1, in
NameError: name 'Jhon' is not defined
Use raw_input instead. See http://docs.python.org/library/functions.html#raw_input. input will do the same thing as eval(raw_input(prompt)), so entering in Jhon will try to find the symbol Jhon within the file (which doesn't exist). So for your existing script you'd have to input 'Jhon' (notice the set of quotes) in the prompt so the eval will convert the value to a string.
Here's the excerpt warning from the input documentation.
Warning
This function is not safe from user
errors! It expects a valid Python
expression as input; if the input is
not syntactically valid, a SyntaxError
will be raised. Other exceptions may
be raised if there is an error during
evaluation. (On the other hand,
sometimes this is exactly what you
need when writing a quick script for
expert use.)
Below is the corrected version:
#!usr/bin/python
# The list is implied with the variable name, see my comment below.
names = []
try:
# We need to convert the names input to an int using raw input.
# If a valid number is not entered a `ValueError` is raised, and
# we throw an exception. You may also want to consider renaming
# names to num_names. To be "names" sounds implies a list of
# names, not a number of names.
num_names = int(raw_input("Pls enter how many of names:"))
except ValueError:
raise Exception('Please enter a valid number.')
# You don't need x=1. If you want to start your name at 1
# change the range to start at 1, and add 1 to the number of names.
for x in range(1, num_names+1)):
inname = raw_input("Enter the name " + str(x))
names.append(inname)
print names
NOTE: This is for Python2.x. Python3.x has fixed the input vs. raw_input confusion as explained in the other answers.
input gets text from the user which is then interpreted as Python code (hence it's trying to evaluate the thing you entered, Jhon). You need raw_input for both of them and you'll need to convert the number entered (since it's a string) to an integer for your range.
#!usr/bin/python
listofnames = []
names = 0
try:
names = int(raw_input("Pls enter how many of names:"))
except:
print "Problem with input"
for x in range(0, names):
inname = raw_input("Enter the name %d: "%(x))
listofnames.append(inname)
print listofnames
In python3, input() now works like raw_input(). However to get your code to work with Python3 a couple of changes are still required
#!usr/bin/python3
listofnames = []
names = int(input("Pls enter how many of names:"))
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print(listofnames)

Categories