How to restrict user inputs? [duplicate] - python

This question already has answers here:
Allow Only Alpha Characters in Python?
(5 answers)
Closed 6 years ago.
For example a program has the line:
user_input = raw_input(" enter : ")
How do you make it so that the program will only continue once what the user enters are letters only? And is he enter anything else he will get an error.
EDIT: Thanks for the help but it says try again if there is a space. The solution is:
while True:
name = raw_input("Enter name : ")
if name.replace(' ', '').isalpha():
break
else:
print "Try again"

Just use str.isalpha():
user_input = ""
while not user_input.isalpha():
user_input = raw_input(" enter : ")

while True:
user_input = raw_input(" enter: ")
if user_input.isalpha():
break
else:
print "try again"

Related

How to detect a invalid input and put the user into a loop until an acceptable answer is typed?

I'm trying to figure out how to get the user to type on letters and return numbers as invalid inputs only.
This is my code, I'm still unclear about the ValueError as if I run the code and type in letters it'll come out as an invalid input but if I put in numbers it comes in as valid.
while True:
try:
name = int(input("What is your name? "))
except ValueError:
print("Invalid response. Letters only please.")
continue
else:
break
correctName = input("Your name is...'" + (name) + "', is this correct? \n Please use 'Y' as yes and 'N' as no.\n")
if correctName == "Y":
print("Thank you..!")
int(input()) will expect an integer as an input, so when you type your name (unless you're name wholly consists of numbers), you will get a ValueError like you're experiencing now. Instead, you can use str(input()) to get the user input, then use the str.isdigit() method to check if it's a number.
name = str(input("What is your name? "))
if name.isdigit():
print("Invalid response. Letters only please.")
continue
else:
break
you can also try regex to check if a string contains a number:
bool(re.search(r'\d', name))
\d will matches for digits [0-9].
it will return True if the string contains a number.
full code:
import re
while True:
name = input("What is your name? ")
if bool(re.search(r'\d', name)):
print("Invalid response. Letters only please.")
else:
correctName = input("Your name is...'" + (name) + "', is this correct? \n Please use 'Y' as yes and 'N' as no.\n")
if correctName == "Y":
print("Thank you..!")
break
For Python3
while True:
name = input()
if name.isalpha():
break
For Python2
while True:
name = str(input())
if name.isalpha():
break

Restart the program If user input is no [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I would like the program to ask the user for the password if the password wasnt correct. How do I do it?
#program that saves user passwords
user_input = ""
FB = input("what is your facebook pasword \n")
print("your facebook passoerd is " + FB + " is this correct?")
user_input = input()
if (user_input == "yes"):
print("password has been saved")
elif user_input == "no":
print("password was not saved")
else:
print("i do not understand. sorry")
Welcome to StackOverflow!
One of the usual tricks is to wrap all of that in a while loop and break the loop if user input is anything other than "no"
while True:
user_input = ""
FB = input("what is your facebook pasword \n")
print("your facebook password is " + FB + " is this correct?")
user_input = input()
if user_input is "yes":
print("password has been saved")
break #add break here to exit the program
elif user_input is "no":
print("password was not saved")
else:
print("i do not understand. sorry")
break #add break here to exit the program

Why is my password programme code not working?

The code will only let me guess once . Can someone please tell me what is wrong with my code?
Challenge:
Write a program that sets a password as ‘Gain Access ’ and asks the
user to enter the password and keeps asking until the correct password
is entered and then says ‘Accepted’. The program should count how many
attempts the user has taken and tell them after they have been
accepted.
enter code here
password = 'Gain access'
count = 0
input = input("Enter the password: \n")
while input != password:
print("Incorrect password! Please try again: \n")
count = count + 1
print("You have now got your password wrong " + str(count) + " times. \n")
if(count < 5):
print("Access denied, please contact security to reset your password.")
break
else:
print("Accepted, welcome back.")
print("You had " + str(count) + " attempts until you got your password right.")
You should always include the language you're programming in like simonwo mentioned already.
Looks like Python to me though. I suppose this line input = input("Enter the password: \n") needs to go after while input != password:, as well. Otherwise you can only enter the password once and then it directly executes all 5 loops. But you should NOT assign input because this is the function you want to obtain the input from.
Do something like user_input = input("Enter the password: \n"). So your code should look something like this:
...
user_input = input("Enter the password: \n")
while user_input != password:
print("Incorrect password! Please try again: \n")
user_input = input("Enter the password: \n")
... Your existing code here
But note that this way the user won't get notified if they entered the correct password with their first try. You could insert a check after the first reading of the user input and if it matches the desired password print your welcome phrase.

How can I make a loop in order to ask the user a number when he enter a text for his age [duplicate]

This question already has answers here:
Python check for integer input
(3 answers)
Closed 5 years ago.
I am trying to do a program that asks the user his name, age, and the number of times he wants to see the answer. The program will output when he will turn 100 and will be repeated a certain number of times.
What is hard for me is to make the program asks a number to the user when he enters a text.
Here is my program:
def input_num(msg):
while True:
try :
num=int(input(msg))
except ValueError :
print("That's not a number")
else:
return num
print("This will never get run")
break
name=input("What is your name? ")
age=int(input("How old are you? "))
copy=int(input("How many times? "))
year=2017-age+100
msg="Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
When you're prompting your user for the age: age=int(input("How old are you? ")) you're not using your input_num() method.
This should work for you - using the method you wrote.
def input_num(msg):
while True:
try:
num = int(input(msg))
except ValueError:
print("That's not a number")
else:
return num
name = input("What is your name? ")
age = input_num("How old are you? ") # <----
copy = int(input("How many times? "))
year = 2017 - age + 100
msg = "Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
This will check if the user input is an integer.
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
print "I am afraid {} is not a number".format(age)
Put that into a while loop and you're good to go.
while not age:
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
age = None
print "I am afraid {} is not a number".format(age)
(I took the code from this SO Answer)
Another good solution is from this blog post.
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break

How to loop a program from the beginning

I am coding a mock sign up page for a game or something or other, at the end of the code I want to confirm that the user entered data is correct. I do this by typing.
#User sign up page.
#Getting the user's information.
username = input ("Plese enter your first name here: ")
userage = input ("Please enter your age here: ")
userphoneno = input ("Please enter your home or mobile number here: ")
#Showing the inforamtion.
print ("\nIs the following correct?\n")
print ("•Name:",username)
print ("•Age:",userage)
print ("•Phone Number:",userphoneno)
#Confirming the data.
print ("\nType Y for yes, and N for no. (Non-case sensitive.)")
answer = input ("• ")
if answer == 'Y'or'y':
print ("Okay, thank you for registering!")
break
else:
#Restart from #Getting the user's information.?
My problem arises in the last section of code. The program ends like normal when "Y or y" is entered, but I can't seem to work out how to let the user re enter their data if "N or n" is entered. I tried a While loop, which I'm guessing is the solution, but I couldn't seem to get it to work correctly.
Any help would be greatly appreciated. Thanks!
You should use a while loop! Wrap the part that deals with user input with a function and then keep on calling that function if the user responds with no. By the way, you should use raw_input instead of input. For example:
#User sign up page.
#Getting the user's information.
def get_user_info():
username = raw_input("Plese enter your first name here: ")
userage = raw_input("Please enter your age here: ")
userphoneno = raw_input("Please enter your home or mobile number here: ")
#Showing the inforamtion.
print ("\nIs the following correct?\n")
print ("Name:",username)
print ("Age:",userage)
print ("Phone Number:",userphoneno)
print ("\nType Y for yes, and N for no. (Non-case sensitive.)")
answer = raw_input("")
return answer
answer = get_user_info()
#Confirming the data.
while answer not in ['Y', 'y']:
answer = get_user_info()
print ("Okay, thank you for registering!")

Categories

Resources