How to make a proper name input program in python [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How to validate person names? - Python/Django
(4 answers)
Closed 4 years ago.
I am at the part where I ask the user for their name. So far I got this:
# Import stuff
import time
# Create empty variable
Name = ""
# Ask their name
while Name = ""
Name = input("What is your name? ")
print("")
print(Name)
print("")
time.sleep(3)
So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.
How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?

I'm updating my answer to simplify the code and make it more readable.
The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.
from string import ascii_letters
def get_name():
name = input("What is your name?\n: ").strip().title()
while not all(letter in ascii_letters + " -" for letter in name):
name = input("Please enter a valid name.\n: ").strip().title()
return name
To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".
The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".
This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.
After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.
Old answer is as follows, it will still be useful.
This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.
Notice the use of str.isalpha().
def get_name():
name = input("What is your name?\n: ").strip().title()
while not (name.replace("-", "") and
name.replace("-", "").replace(" ", "").isalpha()):
name = input("Please enter a valid name.\n: ").strip().title()
return name
Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.
The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out #AGN Gazer.
Now you can just call the function later in your script, or store it for later.
name = get_name().title()
print("You said your name was " + name + ".)
The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".
Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().

You can try this :
while Name == "" or Name.isnumeric() == True:
Name = input("What is your name? ")
print("")
Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.

You can use a function like .isalpha() as this will return True if all the string contains all the alphabets:
while True:
Name = input("Please enter a valid name.\n: ")
if name.isalpha()
break
else:
print("Please enter a valid name.")
continue
print(Name)
Or You can try exception handling in python as (but this should be prevented):
try :
int(Name)
print("Please enter a valid name")
...
except:
print("Accepted")
...
This will check if the input is an integer print the error.

You can try:
This will check if variable Name containing numeric data or not.
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if not Name.isalpha():
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You also can try if name is like "harsha-biyani":
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if any(i.isdigit() for i in Name):
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)

You can use:
Name.isalpha()
"3".isalpha()
False
"anna".isalpha()
True

Related

I keep getting an error on the line with the #. I've tried putting "" around each symbol, all the symbols together, and put the symbols in () [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 months ago.
I keep getting an error on the line with the #. I've tried putting "" around each symbol, all the symbols together, and put the symbols in ().
def main():
name = input("Enter a reader's name: ")
symbol = input("Enter a symbol: ")
rating = input("Enter a rating: ")
if name not in 'ratings.txt':
print("No such reader " + name)
print("bye!")
return
#if symbol not >,<,=:
print("please use >,<,=")
return
if rating not -5,-3,0,1,3:
print("please use -5,-3,0,1,3")
return
if name = []:
print('no books found')
return
You can use the not in construct to check if an item is not in a list/tuple/other container. Thus, you can do this:
item = "foo"
print(item not in ["foo", "bar", "baz"]) # False
print(item not in ["ham", "egg", "pan"]) # True
This works for numbers too. However, using sets (with curly braces) is more efficient if all you're doing is testing if an item is in the container. Also, I see your code has
if name = []:
When testing for equality in an if statment, use the equals operator ==. Thus your code will be:
name = input("Enter a reader's name: ")
symbol = input("Enter a symbol: ")
rating = input("Enter a rating: ")
if name not in 'ratings.txt':
print("No such reader " + name)
print("bye!")
return
if symbol not in {">", "<", "="}:
print("please use >,<,=")
return
if rating not in {-5, -3, 0, 1, 3}:
print("please use -5,-3,0,1,3")
return
if name == []:
print('no books found')
return
Finally, the line
if name not in "ratings.txt":
does not check if name is in the contents of the file ratings.txt, but rather if it is a substring of that filename. For checking the file contents, you can try this question.

Checking whether the input is empty or not without if statements

I need to check whether the input is empty or not and cannot use if statements.
print("What is your name?")
name = input()
print("Hi, {}".format(name))
Use a while loop that only terminates if the length of name is 0:
name = ""
while len(name) == 0:
print("What is your name?")
name = input()
print("Hi, {}".format(name))
You could try something like this:
print("What is your name?")
name = input()
name = "Hi, {}".format(name)
while name == "Hi, ":
name = "You didn't key in any name"
print(name)
This is ugly, but it will produce the exact output you want.
The idea is to use a loop that will run only once, and will only run if the name variable is empty after input() is called.
I would recommend assert. It will stop your programming to continue running when the requirement is not met.
print("What is your name?")
name = input()
assert name != "", "You didn't key in any name"
print("Hi, {}".format(name))
What is your name?
AssertionError: You didn't key in any name
As my previous answer with the while loop received some criticism, I decided to demonstrate a less "naive" but perhaps more complicated solution, that actually does not use any kind of direct conditional operator:
print("What is your name?")
name = input()
answer = {}
answer[len(name)] = "Hi, {}".format(name)
answer[0] = "You didn't key in any name"
print(answer[len(name)])
Here we rely on a dictionary with the length of the input as an integer key.
We don't even need to compare the length to 0, we just overwrite the 0 key with the error message.
If input length is greater than 0, the name will be under its own key, and will be printed, if not, the empty "Hi" string will be replaced.
Would this ever be useful in the real world?
Probably not, unless there are many more than 2 options.
Does it comply with the task requirements?
Yes. It gives the desired output.

How would I use a while loop so that if they enter a number it would ask them the again?

fn = input("Hello, what is your first name?")
firstname = (fn[0].upper())
ln = input("Hello, what is your last name?")
lastname = (ln.lower())
I want fn to be on a loop so that if they enter their a number instead of letters, it would repeat the question
I guess you need something like this
final_fn = ""
while True:
fn = input("Hello, what is your first name?")
if valid(fn):
final_fn = fn
break
Define you validation method before it. An example would be as Joran mentioned
def valid(fn):
return fn.isalpha()
if result.isalpha():
print "the string entered contains only letters !"
I guess ?
a="6"
while not a.isalpha():
a = raw_input("Enter your name:")
print "You entered:",a
if you just wanted to eliminate only words that contained numbers you could do
while any(ltr.isdigit() for ltr in a):

NameError when calling upon variable that I have defined within a def - Python 3.x

This code is meant to allow the user to input a name- but if they input numbers, then it will display an error ('No numbers please!') and prompt them to input their name again. This process will continue in a loop until the user inputs a string with no number characters.
However, If the user inputs a pure alphabetical string-
if not any(char.isdigit() for char in name):
break
Then the loop will be broken and the result of the input will be turned into a list for use later in the program. Here is where the error comes in:
When the loop is broken, I get this error:
namelist = list(name.lower().strip(" "))
NameError: name 'name' is not defined
As you can see below, I have already defined the variable name as the result of an input within the naming() definition. What am I doing wrong? Thanks for the help!
def naming():
name = input ("please input your name: ")
while any(char.isdigit() for char in name):
print ("\nNo numbers please!\n")
naming()
if not any(char.isdigit() for char in name):
break
naming()
#making the name into a list
namelist = list(name.lower().strip(" "))
name has its scope limited to only the function, which is why you can't access it in the global scope for namelist.
One way to solve this is to return the value from your function:
def get_name():
name = input ("please input your name: ")
while any(char.isdigit() for char in name):
print ("\nNo numbers please!\n")
name = input ("please input your name: ")
return name
name = get_name()
namelist = list(name.lower().strip(" "))

How to make the user only enter one character at a time

OK so what I need to do is make my code only allow the user to enter one letter and then one symbol at a time. The example below shows what I want in a better view.
At the moment my code allows the user to enter more than one character at a time which I don't want.
What letter would you like to add? hello
What symbol would you like to pair with hello
The pairing has been added
['A#', 'M*', 'N', 'HELLOhello']
What I want is a message to be displayed like this and the pairing not to be added to the list.
What letter would you like to add? hello
What symbol would you like to pair with hello
You have entered more than one character, the pairing was not added
['A#', 'M*', 'N',].
So far my code for this section is as follows...
It would also be great for when the user enters a number in the letter section, an error message to be printed.
def add_pairing(clues):
addClue = False
letter=input("What letter would you like to add? ").upper()
symbol=input("\nWhat symbol would you like to pair with ")
userInput= letter + symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
elif len(userInput) ==1:
print("You can only enter one character")
else:
newClue = letter + symbol
addClue = True
if addClue == True:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
The easiest way to ensure user input is with a loop:
while True:
something = raw_input(prompt)
if condition: break
Something set up like this will continue to ask prompt until condition is met. You can make condition anything you want to test for, so for you, it would be len(something) != 1
Your method can be simplified to the following if you let the user enter a letter and symbol pair:
def add_pairing(clues):
pairing = input("Please enter your letter and symbol pairs, separated by a space: ")
clues = pairing.upper().split()
print('Your pairings are: {}'.format(clues))
return clues
Not exactly sure what you want to return but this will check all the entries:
def add_pairing(clues):
addClue = False
while True:
inp = input("Enter a letter followed by a symbol, separated by a space? ").upper().split()
if len(inp) != 2: # make sure we only have two entries
print ("Incorrect amount of characters")
continue
if not inp[0].isalpha() or len(inp[0]) > 1: # must be a letter and have a length of 1
print ("Invalid letter input")
continue
if inp[1].isalpha() or inp[1].isdigit(): # must be anything except a digit of a letter
print ("Invalid character input")
continue
userInput = inp[0] + inp[1] # all good add letter to symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
else:
newClue = userInput
addClue = True
if addClue:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
I am fan of raising and catching exceptions in similar cases. Might be shocking for people with 'C-ish' background (sloooow), but it is perfectly pythonic and quite readable and flexibile in my opinion.
Also, you should add check for characters outside of set you are expecting:
import string
def read_paring():
letters = string.ascii_uppercase
symbols = '*##$%^&*' # whatever you want to allow
letter = input("What letter would you like to add? ").upper()
if (len(letter) != 1) or (letter not in letters):
raise ValueError("Only a single letter is allowed")
msg = "What symbol would you like to pair with '{}'? ".format(letter)
symbol = input(msg).upper()
if (len(symbol) != 1) or (symbol not in symbols):
raise ValueError("Only one of '{}' is allowed".format(symbols))
return (letter, symbol)
def add_pairing(clues):
while True:
try:
letter, symbol = read_paring()
new_clue = letter + symbol
if new_clue in clues:
raise ValueError("This pairing already exists")
break # everything is ok
except ValueError as err:
print(err.message)
print("Try again:")
continue
# do whatever you want with letter and symbol
clues.append(new_clue)
print(new_clue)
return clues

Categories

Resources