Check for correct user input without exiting loop - python

I'm trying to write a travel itinerary program using base Python functionality. In step 1, the program should ask for primary customer (making the booking) details viz name and phone number. I've written code to also handle errors like non-alphabet name entry, errors in phone number input (ie phone number not numeric, not 10 digits etc) to keep asking for valid user input, as below, which seems to work fine:
while True:
cust_name = input("Please enter primary customer name: ")
if cust_name.isalpha():
break
else:
print("Please enter valid name")
continue
while True:
cust_phone = input("Please enter phone number: ")
if cust_phone.isnumeric() and len(cust_phone) == 10:
break
else:
print("Error! Please enter correct phone number")
continue
while True:
num_travellers = input("How many people are travelling? ")
if int(num_travellers) >= 2:
break
else:
print("Please enter at least two passengers")
continue
Output:
Please enter primary customer name: sm
Please enter phone number: 1010101010
How many people are travelling? 2
For the next step, the program should ask for details of all passenger ie name, age and phone numbers and store them. I want to implement similar checks as above but my code below simply exits the loop once the number of travellers (num_travellers, 2 in this case) condition is met, even if there are errors in input:
for i in range(int(num_travellers)):
travellers = []
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
else:
print("Please enter valid name")
continue
for j in range(int(num_travellers)):
travel_age = []
age = input("Please enter passenger age: ")
if age.isnumeric():
travel_age.append(age)
else:
print("Please enter valid age")
continue
Output:
Please enter passenger name: 23
Please enter valid name
Please enter passenger name: 34
Please enter valid name
Please enter passenger age: sm
Please enter valid age
Please enter passenger age: sk
Please enter valid age
Please enter passenger age: sk
I've tried using a while loop like mentioned in this thread but doesn't seem to work. Where am I going wrong? Thanks

You have missed while True: loop when asking for passenger data. Try something like below:
travellers = []
for i in range(int(num_travellers)):
while True:
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
break
else:
print("Please enter valid name")
continue
BTW I moved travellers variable out of the loop, otherwise it is going to be cleared on every iteration.

Related

Using Python's Loop Functions

I am trying to stop the for loop based on the variable numOfEmp. For example, if I input 2 into numOfEmp, I expect the loop to run two times, showing the statement "Enter Employee's ID" and "Enter Employee's Name" twice, respectively. However, with this code that I have, the loop continues to appear "Enter Employee's ID(i.e. AF101): " after two times (my anticipation). This is the code I have, any help would be greatly appreciated:
#Ask how many employees are there
numOfEmp = int(input("How many employee are in this week's payroll: "))
#Input validation
while numOfEmp < 0:
print ('Sorry, illegal input! Please input again.')
numOfEmp = int(input("How many employee are in this week's payroll: "))
#Input validation
while numOfEmp == 0:
print ("NO PAYROLL? Great! Goodbye.")
break
while numOfEmp > 0: #Ask for each employee's detail
for program in range (numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
Please let me know if I format this wrongly!
Example output page: (asterisk is input)
How many employee are in this week's payroll: **2**
Enter Employee's ID (i.e. AF101): **AS111**
Enter Employee's Name: **First Last**
Enter Employee's ID (i.e. AF101): **AS111**
Enter Employee's Name: **First Last**
Enter Employee's ID (i.e. AF101): **AS111**
Enter Employee's Name: **First Last**
[and so on]
I think just removing the while would work:
while numOfEmp > 0: #Ask for each employee's detail
for program in range (numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
Should become ->
for program in range(numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
The for i in range iterates over all values from 0 to the stop value (exclusive). Find more about it here.
I think the issue is with the last while loop. It is gonna run forever since the numOfEmp isn't being decremented at all. You need to decrement numOfEmp by one for each iteration like so:
while numOfEmp > 0: #Ask for each employee's detail
for program in range (numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
numOfEmp -= 1
Your problem is that while numOfEmp > 0: is always true
One solution is changing the value of numOfEmp after the for loop finishes
while numOfEmp > 0: #Ask for each employee's detail
for program in range (numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
numOfEmp = -1
A better solution might be to simply use if instead of while
if numOfEmp > 0: #Ask for each employee's detail
for program in range (numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
Your numOfEmp is not decreasing anywhere in this while loop:
while numOfEmp > 0: #Ask for each employee's detail
for program in range (numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
That's why the program is prompting for input forever. Just decrease the value of numOfEmp after each iteration, if you do not want to change your code that much:
while numOfEmp > 0: #Ask for each employee's detail
for program in range (numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
numOfEmp=-1
Apart from that fix, you can simplify the whole input process like this:
#Input & Corresponding validation
while True:
numOfEmp = int(input("How many employee are in this week's payroll: "))
if numOfEmp < 0:
print ('Sorry, illegal input! Please input again.')
continue
elif numOfEmp == 0:
print ("NO PAYROLL? Great! Goodbye.")
break
else:
for program in range (numOfEmp):
print () #Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input ("Enter Employee's Name: ")
break
Could you try adding break to the last while loop
# Ask how many employees are there
numOfEmp = int(input("How many employee are in this week's payroll: "))
# Input validation
while numOfEmp < 0:
print('Sorry, illegal input! Please input again.')
numOfEmp = int(input("How many employee are in this week's payroll: "))
# Input validation
while numOfEmp == 0:
print("NO PAYROLL? Great! Goodbye.")
break
while numOfEmp > 0: # Ask for each employee's detail
for program in range(numOfEmp):
print() # Divider line
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input("Enter Employee's Name: ")
break
You can remove all the while loops and make one single while loop which runs based on inputs -
while True:
numOfEmp = int(input("How many employees are in this week's payroll: "))
if numOfEmp < 0:
print ('Sorry, illegal input! Please input again.')
elif numOfEmp == 0:
print ("NO PAYROLL? Great! Goodbye.")
break
else:
for i in range(numOfEmp):
print()
empID = input("Enter Employee's ID(i.e. AF101): ")
empName = input("Enter Employee's Name: ")
break

How do i break out of my while loop?

Doing an assignment, this is my first program so bear with me. I cant get the while loop to end although i have broke it. I need a way to get out of the loop, and what I'm doing isn't working. Any suggestions would be very helpful thank you.
def main(): #Calls the main function
while True:
try:
name = input("Please enter the student's name: ") #Asks for students name
while name == "":
print("This is invalid, please try again")
name = input("Please enter the students name: ")
teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name
while teacher_name == "":
print("This is invalid, please try again")
teacher_name = input("Please enter the teacher's name: ")
marker_name = input("Please enter the marker's name: ") #Asks for markers name
while marker_name == "":
print("This is invalid, please try again")
marker_name = input("Please enter the marker's name: ")
break
except ValueError:
print("This is invalid, please try again")
The problem with your code is your indentation. You have told the program to break when the marker_name is an empty string. I am assuming that you would like the code to finish when all three values are correct, so as such the following code should work for you:
def main():
while True:
try:
name = input("Please enter the student's name: ") #Asks for students name
while name == "":
print("This is invalid, please try again")
name = input("Please enter the students name: ")
teacher_name = input("Please enter the teacher's name: ") #Asks for teachers name
while teacher_name == "":
print("This is invalid, please try again")
teacher_name = input("Please enter the teacher's name: ")
marker_name = input("Please enter the marker's name: ") #Asks for markers name
while marker_name == "":
print("This is invalid, please try again")
marker_name = input("Please enter the marker's name: ")
break
except ValueError:
print("This is invalid, please try again")
main()
I am a little confused why you have used a try and except? What is the purpose of it?
May I ask why the code block is wrapped in the try-except?
Some suggestions:
remove the try-except as you shouldn't be raising any errors
remove the break statement (after marker_name) as the loop should end when the input is valid
ensure the indentation of all the input while-loop code blocks are identical (your formatting is messed up so I'm not sure if you have nested while loops)
Let me know how this works
Well first of all you break out of a while loop in python with break as you did already. You should only break if a condition you set is met in the loop. So lets say you wanted to break in a while loop that counts and you want to break if the number reaches 100, however, you already had a condition for your while loop. You would then put this inside your while loop.
if x == 100:
break
As you have it now you just break in your while loop after a couple lines of code without a condition. You will only go through the loop once and then break every single time. It defeats the purpose of a while loop.
What exactly are you trying to do in this code? Can you give more detail in your question besides that you would like to break in a while loop? Maybe I can help you more than giving you this generic answer about breaking in a loop.

TypeError: transferMoney() missing 1 required positional argument: 'amount'

Hi ive looked at other threads like this but cant find a fix...
Im only including the code where the problem occurs, there is more code but the rest is irreverent.
def transferMoney(self, sender_account, receiver_name, receiver_account_no, amount):
self.sender_account = found_customer
self.reciver_name = customer_name = input("\nPlease input customer name \n")
customer = self.search_customers_by_name(customer_name)
def run_admin_options(self, admin):
loop = 1
while loop == 1:
choice = self.admin_menu(admin.get_name())
if choice == 1:
customer_name= input("Please Enter The Name Of The Customer Sending Money: ")
sender_account_no= int(input("Please Enter the Account Number Of The Person Sending Money: "))
recipient_name= input("Please Enter the name of the person reciving money: ")
recipient_account_no= int(input("Please Enter the recipient account number: "))
found_recipient= self.search_customers_by_name(recipient_name)
found_customer= self.search_customers_by_name(customer_name)
if found_recipient ==None:
return ("Customer Not Found")
else:
if found_customer != None:
my_account= found_customer.get_account()
receiver_account= found_recipient.get_account()
amount_transfer= float(input("Please Enter Amount You Would Like To Send: "))
transferMoney= self.transferMoney(my_account, receiver_account, amount_transfer)
Please give receiver_name parameter value to your function.
In the last line of code you provided you do not have receiver_account_no being passed in. As of now your program thinks the receiver_account_no is actually the amount to be transferred. This leaves the expected amount argument not being passed in.

While loop not repeating once information in entered

Making a program which has a list of the different star signs, then asks the user to enter what star sign they are and then for the program to check that is contained in the list before moving on.
The problem is that it does check that it is in the list, but it does not repeat.
play = True
while play:
print("Welcome to my Pseudo_Sammy program, please enter your name, star sign and then your question by typing it in and pressing the enter key, and I will give you the answer to your question")
name = input("What do they call you? ")
starsigns = ("leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces", "aries", "taurus", "gemini", "cancer")
starsign = str(input("What star do you come from? ")).lower()
while True:
try:
if starsign in starsigns:
break
else:
raise
except:
print("Please enter a valid star sign")
question = input("What bothers you dear? ")
if you want to repeat an input until you get a valid answer and THEN ask the next question, you need to place the 1st input inside while loop and the 2nd input outside the loop, like this:
starsigns = ("leo", "virgo", ...)
starsign = None
while starsign not in starsigns:
if starsign:
print("Please enter a valid star sign: {}.".format(", ".join(starsigns)))
starsign = input("What start do you come from? ").lower().strip()
question = input("What bothers you dear? ")

breaking a loop when enter is pressed

I'm trying to break the loop once Enter is pressed, while writing data to a file. This is what I have so far. I also don't want to limit the number of time the loop is run either... (example output is below)
def main():
myfile = open('friends.txt','w')
friend = input('Enter first name of friend or Enter to quit')
age = input('Enter age (integer) of this friend')
while friend != '':
for n in range():
friend = input('Enter first name of friend or Enter to quit')
age = input('Enter age (integer) of this friend')
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
myfile.close()
main()
This is how to output is supposed to be when its ran right.
Enter first name of friend or Enter to quit Sally
Enter age (integer) of this friend 20
Enter first name of friend or Enter to quit Sam
Enter age (integer) of this friend 24
Enter first name of friend or Enter to quit
File was created
def main():
myfile = open('friends.txt','w')
while True:
friend = input('Enter first name of friend or Enter to quit: ')
if not friend:
myfile.close()
break
else:
age = input('Enter age (integer) of this friend: ')
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
main()
Output:
Enter first name of friend or Enter to quit: Mack
Enter age (integer) of this friend: 11
Enter first name of friend or Enter to quit: Steve
Enter age (integer) of this friend: 11
Enter first name of friend or Enter to quit:
Process finished with exit code 0
You had a couple of errors in your code, such as using range() and indentation and using input for a string, when raw_input may have been a better choice.
To do what you want, you should put the write at the beginning of your loop, and after asking for the name, check if it's empty and, if it is, break. Code is below:
def main():
myfile = open('friends.txt','w')
friend = raw_input('Enter first name of friend or Enter to quit')
age = int(raw_input('Enter age (integer) of this friend'))
while friend != '':
while True:
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
friend = raw_input('Enter first name of friend or Enter to quit')
if not friend:
break
age = int(raw_input('Enter age (integer) of this friend'))
print('File was created')
myfile.close()
main()

Categories