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
Related
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.
I create a few class about pet, the following code was part of my main() function, First, ask the user to select one thing they want to do. that is if use input '1' they will add some pet instance. At the same time, I want to append part of the pet instance's information to a list. Then if the user chooses to read this information. I want to print it in another if statement branch. that is when the user input '2'. the problem occurs when I input 2 after already generating some pet instance. the list called l_weight always be void. How could I fix it? I already try to use the global list but is not work
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
return main()
elif a==2:
for i in l_weight:
print(i)
return main()
The reason l_weight() isn't appending is because in your code, you named the list l_weight and then in the rest of your code it's written as l_weigh
It should be:
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
elif a==2:
for i in l_weight:
print(i)
I am writing a banking application using arrays and functions in python. I am having trouble with the line if (position>4):
print("The account number not found!") Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==AccountNumbersArray[position]):
print("Name is: " +NamesArray[position])
print(NamesArray[position]+" account has the balance of : $" +str(BalanceArray[position]))
break
if (position>4):
print("The account number not found!")
while True:
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid choice. Please try again!")
The code works fine, except if the user inputs a position over 5. It has to print The account number not found! and then go back to the menu. It goes back to the main menu, but without printing the statement. How can I fix this?
You want to check account to search not position:
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==AccountNumbersArray[position]):
print("Name is: " +NamesArray[position])
print(NamesArray[position]+" account has the balance of : $" +str(BalanceArray[position]))
break
if (accounttosearch>4):
print("The account number not found!")
Is there actually a way to store every different input for n number of inputs and then displays all of them all together in correct order for example:
The User Inputs Record Number, Name, Employee Type, Number Of Days Worked For n number of users
After n number of users, it displays the following all at once:
Record Number: 1
Employee Name: Alexander
Employee Type: C
Days Worked:5
Pay(RM):2500.00
Record Number: 2
Employee Name: Bella
Employee Type: V
Days Worked:10
Pay(RM):1000.00
Record Number: 3
Employee Name: Tom
Employee Type: S
Days Worked:20
Pay(RM):5000.00
Or is it only possible to display one by one? Here is my current code
print("{0:^15s}{1:^25s}".format("Employee Type", "Employee Rate (per day)"))
print("{0:^15s}{1:>15s}".format("C", "RM 500.00"))
print("{0:^15s}{1:>15s}".format("S", "RM 250.00"))
print("{0:^15s}{1:>15s}".format("V", "RM 100.00"))
print()
numEmployee = 1
confirmation = 0
while confirmation != "Y":
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
while numEmployee == str():
print("No Input Has Been Detected. Please Input Number Of Employee(s) In An Integer")
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
while eval(numEmployee) <= 0:
print("Please Enter A Valid Number Of Employees")
numEmployee = input("Enter The Number Of Employees To Be Keyed In: ")
confirmation = input("Are You Sure You The Number Of Employee Is Correct? Enter Y to Continue or any other key to reenter The Correct Number:")
confirmation = confirmation.upper()
print()
numEmployee = eval(numEmployee)
#for recordNum in range (1, numEmployee + 1):
recordNum = 1
finalTotalC = 0
finalTotalS = 0
finalTotalV = 0
while recordNum <= numEmployee:
print("Record Number: ", recordNum)
recordNum = recordNum + 1
name = input("Employee Name: ")
while name == str():
print("Please Enter A Name")
name = input("Employee Name: ")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
while employeeType == str():
print("No Input Has Been Detected. Please Input An Employee Type")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
while employeeType != "C" and employeeType != "S" and employeeType != "V":
print("Employee Type Is Invalid. Please Enter C,S or V Only")
employeeType = input("Employee Type: ")
employeeType = employeeType.upper()
daysWorked = input("Days Worked: ")
while daysWorked == str():
print("No Input Has Been Detected. Please Input Number Of Days Worked In That Month")
daysWorked = input("Days Worked: ")
while eval(daysWorked) < 0 or eval(daysWorked) > 31:
print("Please Enter The Number Of Days In A Range Of 0 until 31 Only")
daysWorked = input("Days Worked: ")
daysWorked = eval(daysWorked)
if employeeType == "C":
EMPLOYEERATE = 500.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalC = daysWorked*EMPLOYEERATE
finalTotalC = finalTotalC + totalC
print()
if employeeType == "S":
EMPLOYEERATE = 250.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalS = daysWorked*EMPLOYEERATE
finalTotalS = finalTotalS + totalS
print()
if employeeType == "V":
EMPLOYEERATE = 100.00
print("Pay (RM): ", format(daysWorked*EMPLOYEERATE, ",.2f"))
totalV = daysWorked*EMPLOYEERATE
finalTotalV = finalTotalV + totalV
print()
You need to store the data somewhere, as you are receiving it. I would suggest a list (https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) of dicts (https://docs.python.org/2/tutorial/datastructures.html#dictionaries) might be appropriate for your case. Then you can iterate over the list after you're done (in order to print).
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()