How to create a loop in Python [duplicate] - python

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

Related

How to force the user to input in a particular format? [duplicate]

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:

Restarting loop to iterate over a user string [duplicate]

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:

Is there a possible way to assign the position of a string to a random integer?

I'm doing some code on a banking system wherein there is a pre-set password, then the program will generate a random number using randint, then that random number is a position of a character in the pre-set password. The user must type the character that is in the position of the number that was generated, for example, if my pre-set password is 12345 and the generated number was 3, I should type 4 to be given access to the system.
As you could see, I'm testing out calling the character from the string and merging it with the random number but it doesn't work, do you have any other ideas to perform it? Thanks. Sorry if it may cause you some confusion but this is how far as my code has gone, I'm still starting out with python though.
import random
randomOne = (random.randint(0,3))
password = "code"
print(randomOne)
decode = input("input a character: ")
if decode == password + str(randomOne):
print("Access Granted")
pass
else:
print("Access Denied")
Is this what you're looking for?
#This is your randomly generated character position in the password
randomIndex = random.randint(0,len(code)-1)
#This is the character itself
randomCharacter = code[randomIndex]
#Ask the user for input
reply = input("Please enter the character in position", randomIndex+1)
#Check to see if user's input matches the actual character
if reply == randomCharacter:
print("Access")
else:
print("Fail")
You're not using any random numbers in here,
If you must know the index it chose, use:
random_position = random.randint(0, len(password)-1)
random_letter = password[random_number]
#then ask them to enter the letter at the index it chose
Otherwise if you only need a random letter from password use:
random_letter = random.choice(password)
#then ask for them to enter the letter it chose
Using random.randrange here would work. This will allow you to build a range using the len of your password, and then select a random integer from that range. You can then use this random int to index your code password.
from random import randrange
pwd = 'code'
pos = randrange(len(pwd))
attempt = input(f'Enter character at index {pos}: ')
if attempt == pwd[pos]:
print('Access Granted')
else:
print('Access Denied')

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.

Restricting the User Input to Alphabets

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.

Categories