Alright, so I defined a function where the user can input his/her name. I want to make it so that the user is not allowed to input a number like "69" for his/her name. How would I go about doing this? Here is the code I used:
def name():
while True:
name = input("What is your name? "))
try:
return str(name)
break
except TypeError:
print("Make sure to enter your actual name.")
You can use isalpha() to check name:
Return true if all characters in the string are alphabetic and there
is at least one character, false otherwise.
>>> "69".isalpha()
False
>>> "test".isalpha()
True
Here's your code with modifications:
while True:
name = input("What is your name? ")
if name.isalpha():
break
else:
print("Make sure to enter your actual name.")
continue
Or:
name = input("What is your name? ")
while not name.isalpha():
print("Make sure to enter your actual name.")
name = input("What is your name? ")
You can use str.isdigit() method to check if the string contains just digits:
name = input("What is your name? ")
while name.isdigit():
print("Make sure to enter your actual name.")
name = input("What is your name? ")
Note that this will allow names like - "Rohit1234". If you just want to allow alphabetic characters, then you can use str.isalpha() method instead.
Invert your logic:
while True:
name = ...
try:
int(name)
print "Name can't be a number."
except TypeError:
return str(name)
Mind you, this will accept any input that is not a valid integer, including 123abc or so.
Related
Currently I have this, but when entering a name with a surname, but it does not validate it accordingly
name = input("Enter your name: ")
if True == name.isalnum():
print("Correct, it's a name")
else:
print("Error")
You can try to split the input by space symbols first and then check each part. The code will be something like that:
name = input("Enter your name: ")
if all(part.isalnum for part in name.split()):
print("Correct, it's a name")
else:
print("Error")
Btw, I guess you should use isalpha instead of isalnum, because '123' not seems to be a valid name.
I think you should change your code checking for if all are digits
False == name.isdigit():
So I have for example the following while statements and I would like to combine them. Because this can get tiresome if you have 20 of these with all different if statements.
while True:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
break
print("Please chars dude")
while True:
age = raw_input("Please type your age\n")
if age.isdigit():
break
print("Please digits only")
If I combine them and someone types a A-Z character with 'age' then the code restarts all over without having saved the 'name' statement. I would like it to save 'name' if it's correct and only start over from the if statement that was false.
while True:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
break
print("Please chars dude")
age = raw_input("Please type your age\n")
if age.isdigit():
break
print("Please digits only")
Use a function to encapsulate asking for information. You can pass in a validation test function:
def ask(question, validator, errormessage):
while True:
result = raw_input(question)
if not validator(result):
print(errormessage)
continue
return result
name = ask("NAME PLEASE\n", lambda s: s.isalpha(), "Please chars dude")
age = ask("Please type your age\n", lambda s: s.isdigit(), "Please digits only")
This is far more readable then any number of tests to see if the user already entered a correct name and you only need to ask for the age now.
Why not use functions and cut down on some duplication in the process?
def ask_input(prompt, error_msg, validation_fn):
while True:
data = raw_input(prompt)
if validation_fn(data):
return data
print(error_msg)
name = ask_input("NAME PLEASE\n", "Please chars dude", lambda x: x.isalpha())
age = ask_input("Please type your age\n", "Please digits only",
lambda x: x.isdigit())
In this case, the prompt (what to ask the user), an error message (what to provide on invalid input), and a validation function are provided to the ask_input() function. This hides the while loop behind the function call and gives you something more meaningful to read in the code.
The lambda functions are just an easy way to help do the validation. You could do this instead:
def isalpha(x):
return x.isalpha()
def isdigit(x):
return x.isdigit()
name = ask_input("NAME PLEASE\n", "Please chars dude", isalpha)
age = ask_input("Please type your age\n", "Please digits only", isdigit)
You can set the variables to None first, and then check them before assignment:
name, age = None, None
while True:
if name is None:
name = str(raw_input("NAME PLEASE\n"))
if not name.isalpha():
print("Please chars dude")
name = None
continue
if age is None:
age = raw_input("Please type your age\n")
if not age.isdigit():
print("Please digits only")
age = None
continue
print("input is valid")
break
continue will start the loop over again. This fits better in the logic of your code, since break actually stop and exit the loop code.
Just use flags to track weather valid input is given, if given then exit the loop.
name_input_required = True
name = ''
while name_input_required:
name = str(raw_input("NAME PLEASE\n"))
if name.isalpha():
name_input_required = False
else:
print("Please chars dude")
age_input_required = True
age = None
while age_input_required:
age = raw_input("Please type your age\n")
if age.isdigit():
age_input_required = False
else:
print("Please digits only")
Try this:
name = None
age = None
while requires_info:
if name is None:
temp_name = str(raw_input("NAME PLEASE\n"))
if temp_name.isalpha():
name = temp_name
continue
else:
print("Please chars dude")
continue
if age is None:
temp_age = raw_input("Please type your age\n")
if temp_age.isdigit():
age = temp_age
continue
else:
print("Please digits only")
continue
break
What we do here is use a single continuous loop and a few if statements/variables to track what still needs to be done. Note depending on how you want them to enter the data you may also add logic to not ask for age if the name was invalid.
So I have for example the following while statements and I would like to combine them. Because this can get tiresome if you have 20 of these with all different if statements.
I assume the actual problem is "How to reduce tiresome code?" instead of "How to merge two loops into one?". I think keeping two loops is a good idea.
def safe_input(prompt, err_message, validation_fn):
while True:
value = raw_input(prompt)
if validation_fn(value):
return value
print err_message
name = safe_input("NAME PLEASE\n", "Please chars dude", str.isalpha)
age = safe_input("Please type your age\n", "Please digits only", str.isdigit)
If you always want the used to enter text in a separate line, you might want to print prompt before raw_input and to not give an argument to raw_input. That way you don't have to supply "\n" in every call of safe_input.
Yes, you can combine both loops in one loop!
Always try to solve the problem line by line.
You will get to learn the language better and it is the most simple way to solve any problem too.
A line by line solution would look like this:
name = '' # define name outside while loop
while True:
if not name:
name = str(raw_input("NAME PLEASE\n"))
if not name.isalpha(): # validate name
print("Please chars dude")
# reset name
name = ''
else:
age = raw_input("Please type your age\n")
if age.isdigit(): # validate age
"""continue your code here"""
print('name: ' + name + ' and age: ' + age)
print('Ok! Goodbye!')
break # while loop
else:
print("Please digits only")
will print:
NAME PLEASE
Elis
Please type your age
30
name: Elis and age: 30
Ok! Goodbye!
This will help you understand while loop better and how to use it in more difficult cases.
Do not over design using redundant language features. It will make refactoring and debugging difficult.
strFName = ""
while strFName != strFName.isalpha():
if strFName != strFName.isalpha():
strFName = input("What is your first name? ")
else:
print("Your name cannot contain numbers")
break
I want the user to enter their name, but if they enter any letters the program will throw up an error. So far I am trying to do this with a try and except but whenever I enter a number it just goes straight on to the next part of the program.
You mean the first name cannot contain digits?
If so, you can do something like this:
import string
has_digits = lambda x: any([i.isdigit() for i in x])
first_name = "0"
while has_digits(first_name):
first_name = input("Enter first name (cannot contain digits): ")
print('Your name is {}'.format(first_name))
I have a program that asks the user's name:
while True:
try:
name = str(input("Please enter your name > "))
except ValueError:
print("Please enter a valid name")
continue
else:
break
I want to prevent the user from entering an integer, but with the code above integers are accepted in a string. How can I prevent the user from entering an integer in the string?
Firstly, do not cast str as input returns an str. Note from the docs
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that
After you get the input into name you can have a if condition.
name = str(input("Please enter your name > "))
if (re.search('\d',name)):
print("Sorry your name contains a number")
And don't forget to import re
break when trying to cast to an int if an exception is raised as it is not an int:
while True:
name = input("Please enter your name > ")
try:
int(name)
except ValueError:
break
print("Please enter a valid name")
str.digit might work also but will fail on negative input.
To check if any character is a digit use any:
while True:
name = input("Please enter your name > ")
if any(ch.isdigit() for ch in name):
print("Please enter a valid name")
else:
break
You could also create a set of accepted characters:
from string import ascii_letters
st = set(ascii_letters)
while True:
name = input("Please enter your name > ")
if not st.issuperset(name):
print("Please enter a valid name")
else:
break
Where you might want to add -, " " and any other potential characters.
You can use the string method isdigit() to check if the string is just integers.
name = input("Please enter your name: ")
if name.isdigit() == True:
print ("That's not a name!")
Likewise, you can also use the method isalpha() to check if the string is just text. However, if there's a space, it will return False.
name = input("Enter your name: ")
if name.isalpha() != True:
print ("That's not a name!")
Maybe:
if len(set(name) - set('1234567890')) < len(set(name)):
name = input("Please enter a valid name: ")
I need help encasing the:
if any(c.isdigit() for c in name):
print("Not a valid name!")
inside of a while statement. This pretty much just reads the input for the "name" variable and sees if there's an integer in it. How could I use that in a while statement? I just want it to be if the user inputs a variable into the input, it will print out the string up above and loop back and ask the user for their name again until they successfully enter in a string with no integer, then I want it to break. Any help?
print("Hello there!")
yn = None
while yn != "y":
print("What is your name?")
name = raw_input()
if any(c.isdigit() for c in name):
print("Not a valid name!")
print("Oh, so your name is {0}? Cool!".format(name))
print("Now how old are you?")
age = raw_input()
print("So your name is {0} and you're {1} years old?".format(name, age))
print("y/n?")
yn = raw_input()
if yn == "y":
break
if yn == "n":
print("Then here, try again!")
print("Cool!")
Use while True and a break to end the loop when a valid name has been entered:
while True:
name = raw_input("What is your name? ")
if not any(c.isdigit() for c in name):
break
print("Not a valid name!")
This is much easier than first initializing name to something that is invalid then using the any() expression in the while test.
Something like this:
name = input("What is your name? : ")
while any(c.isdigit() for c in name):
print ("{0} is invalid, Try again".format(name))
name = input("What is your name? : ")
demo:
What is your name? : foo1
foo1 is invalid, Try again
What is your name? : 10bar
10bar is invalid, Try again
What is your name? : qwerty
Are you just saying you want a continue after your print("Not a valid name!")?
print("Hello there!")
yn = None
while yn != "y":
print("What is your name?")
name = raw_input()
if any(c.isdigit() for c in name):
print("Not a valid name!")
continue
print("Oh, so your name is {0}? Cool!".format(name))
...
The continue will just go back to the top of your loop.