This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I'm attempting to accept user input and check the string for non-alphabet values. My problem is if they enter a bad value, how do I query them again and start the loop over? See below
name = str(input("Enter name:"))
for i in name:
if not i.isalpha():
name = str(input("Enter name:")
**line to start iterating from the beginning with new entry.**
Just trying to verify users only enter letters. If the check fails they enter the name again and it starts over. Thanks in advance!
You can do something like this:
correct = False
while correct == False:
name = str(input("Enter name:"))
for i in name:
if not i.isalpha():
correct = False
break
else:
correct = True
You can see below an example code:
while True:
number_found = False
name = str(input("Enter name:"))
for i in name:
print("Check {} character".format(i))
if i.isdigit():
print("{} is number. Try again.".format(i))
number_found = True
break # Break the for loop when you find the first non-alpha. You can reduce the run-time with this solution.
if not number_found:
break
print("Correct input {}".format(name))
Output:
>>> python3 test.py # Success case
Enter name:test
Check t character
Check e character
Check s character
Check t character
Correct input test
>>> python3 test.py # Failed case
Enter name:test555
Check t character
Check e character
Check s character
Check t character
Check 5 character
5 is number. Try again.
Enter name:
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
Is there is a way to make sure that the user enters the input data as I want them to,
For example,
I wrote this code so the user can enter some birthdays and the script will choose one in random:
import random, re
print("keep in mind that you need to enter the date in this format dd/mm/yyyy")
cont_1 = input("please enter the informations of the 1st contestant : \n")
cont_2 = input("please enter the informations of the 2nd contestant : \n")
cont_3 = input("please enter the informations of the 3rd contestant : \n")
cont_4 = input("please enter the informations of the 4th contestant : \n")
cont_5 = input("please enter the informations of the 5th contestant : \n")
print("Thank you,")
win = cont_1 + " " + cont_2 + " " + cont_3 + " " + cont_4 + " " + cont_5
contDates = re.compile(r'\d\d/\d\d/\d\d\d\d')
ir = contDates.findall(win)
print(" And the Winner is: ", random.choice(ir))
I want to know if there is a way to force the user to write in the input in this format ../../... when he enters the first two digits a slash shows and the next two
There is not easy way to do this. The easiest solution is to just check that what the user input is correct before asking for the next input:
date_re = re.compile(r'\d\d/\d\d/\d\d\d\d')
def ask_date(prompt):
while True: # Ask forever till the user inputs something correct.
text = input(prompt)
if date_re.fullmatch(text): # Does the input match the regex completly (e.g. no trailing input)?
return text # Just return the text. This will break out of the loop
else:
print("Invalid date format. please use dd/mm/yyyy")
cont_1 = ask_date("please enter the informations of the 1st contestant : \n")
cont_2 = ask_date("please enter the informations of the 2nd contestant : \n")
cont_3 = ask_date("please enter the informations of the 3rd contestant : \n")
cont_4 = ask_date("please enter the informations of the 4th contestant : \n")
cont_5 = ask_date("please enter the informations of the 5th contestant : \n")
This also simplifies the selection process, since all dates are valid:
print(" And the Winner is: ", random.choice((cont_1, cont_2, cont_3, cont_4, cont_5))
You can check if it is correct date format like this without using regex.
import datetime
user_input = input()
try:
datetime.datetime.strptime(user_input,"%d/%m/%Y")
except ValueError as err:
print('Wrong date format')
If you want it custom:
i = input("date (dd/mm/yyyy):")
split = i.split("/")
for item in split:
try:
int(item)
except:
print("error")
exit()
if len(split) != 3 or len(split[0]) not in [1, 2] or len(split[1]) not in [1, 2] or len(split[2]) != 4:
print("error!")
else:
print("accepted!")
This makes sure that all of the items are numbers, and that there are 3 slashes, the first and second ones are two digits, and the last one is 4 digits. If you want to accept any correct date:
My task is to have the user input an unlimited amount of words while using enter.
Example:
(this is where the program asks the user to input names)
Please input names one by one.
Input END after you've entered the last name.
(this is where the user would input the names)
Sarah
Tyler
Matthew
END
(by pressing enter, they are entering the names into a list until they enter END)
I'm not sure where the coding for this will be. I assume I would use a while loop but I'm not sure how. Thanks.
I'm really really new to programming and I'm really lost. This is what I have so far:
def main() :
name = []
print("Please input names one-by-one for validation.")
diffPasswords = input("Input END after you've entered the last name.")
while True :
if
Try using the below while loop:
l = []
while 'END' not in l:
l.append(input('Name: '))
l.pop()
print(l)
Output:
Name: Sarah
Name: Tyler
Name: Matthew
Name: END
['Sarah', 'Tyler', 'Matthew']
it's simply done with a while loop.
name_list=[]
while True:
i = input('enter').rstrip()
if i == 'END':
break
name_list.append(i)
Basically keep on getting a new line but if it equals END\n then stop. The \n is from the enter. Otherwise add it to the list but make sure to omit the last character because that is the newline character(\n) from the enter.
import sys
list = []
while True:
c = sys.stdin.readline()
if c == "END\n":
break
else:
list.append(c[0:-1])
print(list)
I am currently testing my knowledge of python programming as a student and can't get Len() to work on a simple program that asks a user for a user name that is maximum 12 letters long
Name = input("What Is Your Player Name\t")
# Check That The User Has Got A Maximun Of 12 Characters
if Name.len(0-13):
else:
print("Your Name Can Only Contain 12 Characters")
In extension of the other answers using len() you might want to look into using a while-loop to ask the user to enter the name again if it is more than 12 characters like so:
while(True):
name = input("What is your Player Name: ")
if len(name) > 12:
print("Your Player Name can only contain a maximum of 12 characters")
else:
break;
print("\nYou entered the Player Name: %s" % name)
Try it here!
In Python you pass the String into the len function to return the length of the String.
len(Name)
I have to create a program that lets the user enter a string and then, using range, the program outputs that same string backwards. I entered this into python, but it goes me an error, in the 4th line, it says 'int' object has no attribute '__getitem__'.
Can someone please help me correct it? (Using range)
user=raw_input("Please enter a string: ")
user1=len(user)-1
for user in range(user1,-1,-1):
user2=user[user1]
print user2
I think you have a mistake because you keep using the same words to describe very different data types. I would use a more descriptive naming scheme:
user = raw_input("Please enter a string: ")
user_length = len(user)
for string_index in range(user_length - 1, -1, -1):
character = user[string_index]
print(character)
For example, if the user input was foo, it would output:
o
o
f
You are overwriting the user string with your for-loop, fix it by changing the for-loop variable
Fix:
for ind in range(user1,-1,-1):
user2 = user[ind]
print (user2)
Alternative (without for-loop):
print user[::-1]
This is because you are overwriting the string user with an int in the line for user in range(...)
Perhaps you'd be better off with:
user=raw_input("Please enter a string: ")
for user1 in range(len(user)-1,-1,-1):
user2=user[user1]
print user2
your user has been overwrited in your for loop. Take this(Use range)
user=raw_input("Please enter a string: ")
print ''.join([user[i] for i in range(len(user)-1, -1, -1)])
Python 3 solution:
user=input("Please enter a string: ")
for ind in range(1,len(user)+1):
char = user[-ind]
print(char)
And another non for loop solution is:
''.join(reversed(user))
This question already has answers here:
While loop user input in range
(2 answers)
Closed 8 years ago.
This is my code:
my_Sentence = input('Enter your sentence. ')
sen_length = len(my_Sentence)
sen_len = int(sen_length)
while not (sen_len < 10 ):
if sen_len < 10:
print ('Good')
else:
print ('Wo thats to long')
break
I'm trying to make the program ask the user continuously to write a sentence, until it is under 10 characters. I need to know how to have the program as for a sentence again, but I think the simplest way would be to have the code start from the top; but I'm not surte how to do that. Can someone help?
The pattern
The general pattern for repeatedly prompting for user input is:
# 1. Many valid responses, terminating when an invalid one is provided
while True:
user_response = get_user_input()
if test_that(user_response) is valid:
do_work_with(user_response)
else:
handle_invalid_response()
break
We use the infinite loop while True: rather than repeating our get_user_input function twice (hat tip).
If you want to check the opposite case, you simply change the location of the break:
# 2. Many invalid responses, terminating when a valid one is provided
while True:
user_response = get_user_input()
if test_that(user_response) is valid:
do_work_with(user_response)
break
else:
handle_invalid_response()
If you need to do work in a loop but warn the user when they provide invalid input then you just need to add a test that checks for a quit command of some kind and only break there:
# 3. Handle both valid and invalid responses
while True:
user_response = get_user_input()
if test_that(user_response) is quit:
break
if test_that(user_response) is valid:
do_work_with(user_response)
else:
warn_user_about_invalid_response()
Mapping the pattern to your specific case
You want to prompt a user to provide you a less-than-ten-character sentence. This is an instance of pattern #2 (many invalid responses, only one valid response required). Mapping pattern #2 onto your code we get:
# Get user response
while True:
sentence = input("Please provide a sentence")
# Check for invalid states
if len(sentence) >= 10:
# Warn the user of the invalid state
print("Sentence must be under 10 characters, please try again")
else:
# Do the one-off work you need to do
print("Thank you for being succinct!")
break
longEnough = false
while not longEnough:
sentence = raw_input("enter a sentence: ") # Asks the user for their string
longEnough = len(sentence) > 10 # Checks the length