I have a program the functions correctly but I have to add error checking and now I am running into an issue. The problem is that if you type in a number for the worker_name then the following time you type in a name, once you go through all of the input fields it prints out the "Production worker information" twice. How do I fix this?
Entire program:
class Employee(object):
def __init__(self, name, id_number):
self.id_number = id_number
self.name = name
class Worker(Employee):
def __init__(self, name, id_number, shift_number, pay_rate):
#call superclass __init__ method
Employee.__init__(self, name, id_number)
#initialize shift_number and pay_rate attributes
self.shift_number = shift_number
self.pay_rate = pay_rate
def main():
#variables
worker_name= " "
worker_id = " "
worker_shift = 0
worker_pay = 0.00
#get data attributes
while 1:
try:
worker_name = input("Enter the worker name: ")
print()
if not worker_name.isalpha():
print("Only letters are allowed!")
print()
main()
break
worker_id = int(input("Enter the ID number: "))
print()
worker_shift = int(input("Enter the shift number: "))
print()
worker_pay = float(input("Enter the hourly pay rate: "))
print()
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
#create an instance of Worker
Employee.worker = worker_name, worker_id, worker_shift, worker_pay
if not worker_name.isalpha():
pass
#display information
print ("Production worker information ")
print("---------------------------------")
print()
print ("Name: ", worker_name)
print()
print ("ID number: ", worker_id)
print()
print ("Shift: ", worker_shift)
print()
print ("Hourly Pay Rate: $ " + format(worker_pay, ",.2f"))
main()
You are recursively calling main() instead of allowing the while 1: loop to work.
I think you meant:
if not worker_name.isalpha():
print("Only letters are allowed!")
print()
continue
The continue will jump back to the while 1:
You shouldn't call again main() inside itself, use you try/except system
def main():
#variables
worker_name, worker_id, worker_shift,worker_pay = "", "", 0, 0
while True:
try:
worker_name = input("Enter the worker name: ")
if not worker_name.isalpha():
print("\nOnly letters are allowed!")
continue
worker_id = int(input("\nEnter the ID number: "))
worker_shift = int(input("\nEnter the shift number: "))
worker_pay = float(input("\nEnter the hourly pay rate: "))
break
except Exception as e:
print("Invalid choice! try again! " + str(e), "\n")
Use the loop to retry the input if it fails (rather than calling recursively). You can also take advantage of try/catch to make the code quite a bit shorter -- just try the whole thing you want to do in order to create the worker and then you don't need to separately declare and check each variable one at a time.
class Employee:
def __init__(self, name: str, id_number: int):
assert name.isalpha(), "Only letters are allowed in employee names!"
self.id_number = id_number
self.name = name
class Worker(Employee):
def __init__(
self,
name: str,
id_number: int,
shift_number: int,
pay_rate: float
):
# call superclass __init__ method
Employee.__init__(self, name, id_number)
# initialize shift_number and pay_rate attributes
self.shift_number = shift_number
self.pay_rate = pay_rate
def main():
# create an instance of Worker
while True:
try:
name = input("\nEnter the worker name: ")
assert name.isalpha(), "Only letters are allowed!" # fail fast!
worker = Worker(
name,
int(input("\nEnter the ID number: ")),
int(input("\nEnter the shift number: ")),
float(input("\nEnter the hourly pay rate: "))
)
break
except Exception as e:
print(f"Invalid choice! try again! {e}\n")
# display information
print(f"""
Production worker information
---------------------------------
Name: {worker.name}
ID number: {worker.id_number}
Shift: {worker.shift_number}
"Hourly Pay Rate: ${worker.pay_rate:.2f}
""")
main()
Related
#class of bank account with withdraw and deposite
how do i add a code that tells the customer to enter a valid amount if he enter symbols or unvalid number or character of the deposite or withdraw
enter code here
def __init__(self):
self.balance=0
print("Hello Welcome to the Deposit & Withdrawal ATM")
def deposit(self):
amount=float(input("Enter amount to be Deposited: "))
self.balance += amount
print("\n Amount Deposited:",amount)
i want to add a code that if the user enters a unvalid num or Letter here
def withdraw(self):
amount = float(input("Enter amount to be Withdrawn: "))
if self.balance>=amount:
self.balance-=amount
print("\n You Withdrew:", amount)
else:
print("\n Insufficient balance ")
Let's create a function to see if a number is a valid float. There are two main ways that we can do this. Firstly, we can try to parse it and check to see if we get an error, which is not ideal. Otherwise we can use a trick in the playbook. If we remove a single '.' from a string and it is a valid integer then it must have be a valid float or integer previously. This is the ideal method to use.
def CheckValid(string):
# This also doesn't accept negative numbers, which is ideal
return string.replace(".", "", 1).isdigit()
def __init__(self):
self.balance = 0
print("Hello Welcome to the Deposit & Withdrawal ATM")
def deposit(self):
user_input = input("Enter amount to be Deposited: ")
valid = self.CheckValid(user_input)
if valid:
amount = float(user_input)
self.balance += amount
print("\n Amount Deposited:", amount)
else:
# Example
print("An invalid value was entered. Please try again!")
def withdraw(self):
user_input = input("Enter amount to be Withdrawn: ")
valid = self.CheckValid(user_input)
if valid:
amount = float(user_input)
if self.balance >= amount:
self.balance -= amount
print("\n You Withdrew:", amount)
else:
print("\n Insufficient balance ")
else:
# Example
print("An invalid value was entered. Please try again!")
def CheckValid(self, string):
return string.replace(".", "", 1).isdigit()
See:
Checking if a string can be converted to float in Python
I have an inventory program that works 100% but when adding a new item in inventory. How do I make sure the ID number isn't a duplicate to another item already in inventory? The inputs for this are located in the function add_one_item. Please ask questions for more details if need be thank you for your time.
Part of code affected:
import os
class Inventory:
def __init__(self):
#AT LAUNCH GROUPS AND LOADING FUNCTION
self.ID = []
self.item = []
self.qty = []
self.load()
def add_one_item(inventory):
#ADDING PROMPT AND ERROR CHECKING
print('Adding Inventory')
print('================')
while True:
try:
new_ID = int(input("Enter an ID number for the item: "))
new_name = input('Enter the name of the item: ').lower()
assert new_name.isalpha(), "Only letters are allowed!"
new_qty = int(input("Enter the quantity of the item: "))
inventory.add(new_ID, new_name, new_qty)
break
except Exception as e:
print("Invalid choice! try again! " + str(e))
print()
try if statement if new_ID in class_variable ID: print something or do the thing that you want and store a variable of the class in the add_one_item so you call the the values in the class inventory.
Im learning python and am currently trying to pass values from input to the args for a module I wrote but I have no idea how to start.
Can someone give me some advice?
This is the module im calling
#!/usr/bin/python
class Employee:
'Practice class'
empCount = 0
def __init__(self, salary):
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employees %d" % Employee.empCount
def displayEmployee(self):
print "Salary: ", self.salary
class Att(Employee):
'Defines attributes for Employees'
def __init__(self, Age, Name, Sex):
self.Age = Age
self.Name = Name
self.Sex = Sex
def display(self):
print "Name: ", self.Name + "\nAge: ", self.Age, "\nSex: ", self.Sex
This is the code im using to call and pass the values to the args in the above module
#!/usr/bin/python
import Employee
def Collection1():
while True:
Employee.Age = int(raw_input("How old are you? "))
if Employee.Age == str(Employee.Age):
print "You entered " + Employee.Age + " Please enter a number"
elif Employee.Age > 10:
break
elif Employee.Age > 100:
print "Please enter a sensible age"
else:
print "Please enter an age greater than 10"
return str(Employee.Age)
def Collection2():
Employee.Name = raw_input("What is your name? ")
return Employee.Name
def Collection3():
while True:
Employee.Sex = str(raw_input("Are you a man or a woman? "))
if Employee.Sex == "man":
Employee.Sex = "man"
return Employee.Sex
break
elif Employee.Sex == "woman":
Employee.Sex = "woman"
return Employee.Sex
break
else:
print "Please enter man or woman "
Attributes = Employee.Employee()
Collection1()
Collection2()
Collection3()
Attributes.displayEmployee()
Im guessing I need to take the input from the user and place it in the variables of the class. I tried that but im guessing im doing everything wrong??
Employee.Age = int(raw_input("How old are you? "))
There's no use to setting a variable in the module instead of using a local variable, and setting whatever you need to set outside the Collection1() function. Note that you are not setting the employee (object) atributes', but the module's - this is probably not what you want. Also, functions, by convention, should be named with initial lowercase.
Your inheritance model is a bit strange. Why are the employee attributes in a different (sub) class? Generally, the attributes go into the main class constructor. If you really want to use a separate class for the attributes, you shouldn't use a subclass at all in this case.
EDIT
Here's what I think you meant to do:
#!/usr/bin/python
class Employee:
def __init__(self, salary, age, name, sex):
self.salary = salary
self.age= age
self.name= name
self.sex= sex
#Employee.empCount += 1 #don't do this. you should count instances OUTSIDE
def __str__(self):
return "Employee<Name: {0}, Age: {1}, Sex: {2}, Salary: {3}>".format( self.name, self.age, self.sex, self.salary)
def getAge():
while True:
try:
s=raw_input("How old are you? ")
age = int(s)
if age > 100:
print "Please enter a sensible age"
elif age<=10:
print "Please enter an age greater than 10"
else:
return age
except ValueError:
print "You entered " + s + " Please enter a number"
def getName():
return raw_input("What is your name? ")
def getSex():
while True:
sex = str(raw_input("Are you a man or a woman? "))
if not sex in ("man", "woman"):
print "Please enter man or woman "
else:
return sex
age= getAge()
name= getName()
sex= getSex()
salary=100000
employee = Employee(salary, age, name, sex)
print employee
if you want the Employee in a different file (module), just put it there and from your main code run from Employee import Employee (the first is the module, the second is the class).
I am working on this homework assignment and I am stuck on what I know to be a very simple problem. The premise of the code is a petty cash system in which the user can make deposits, withdraws, and get their current balance.
My problem is that the withdraws and deposits don't seem to be going through my Account class. Is it a global variable issue? I'll be adding timestamps later. Thank you in advance.
import datetime
import time
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
def yesno(prompt):
ans = raw_input(prompt)
return (ans[0]=='y' or ans[0]=='Y')
def run():
done = 0
while not done:
user_options()
print
done = not yesno("Do another? ")
print
def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
u = raw_input("Please select a letter option: ").lower()
user_input(u)
def user_input(choice):
account = Account(0.00)
if choice == "a" or choice == "b" or choice == "c":
if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)
if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)
if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()
else:
print ("Not a correct option")
run()
#now = datetime.datetime.now()
Python Version: 2.7.2
The problem is:
account = Account(0.00)
Every time user_input is called, you create a new, empty account. Since user_input is called from user_options which is called inside the while loop in run, this happens before every transaction.
You need to move that line out of the loop, for example:
def run():
done = 0
global account # just showing you one way, not recommending this
account = Account(0.00)
while not done:
user_options()
print
done = not yesno("Do another? ")
print
You don't need global variables, just restructure the code slightly like this
def run():
account = Account(0.00)
done = 0
while not done:
user_option = user_options()
user_input(user_option, account)
print
done = not yesno("Do another? ")
print
def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
return raw_input("Please select a letter option: ").lower()
def user_input(choice, account):
if choice == "a" or choice == "b" or choice == "c":
if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)
if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)
if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()
else:
print ("Not a correct option")
run()
You can still do more to make the code nicer, this is just enough to get the account part working
I'm trying to use a while loop to add objects to a list.
Here's basically what I want to do:
class x:
pass
choice = raw_input(pick what you want to do)
while(choice!=0):
if(choice==1):
Enter in info for the class:
append object to list (A)
if(choice==2):
print out length of list(A)
if(choice==0):
break
((((other options))))
I can get the object added to the list, but I am stuck at how to add multiple objects to the list in the loop.
Here is the code I have so far:
print "Welcome to the Student Management Program"
class Student:
def __init__ (self, name, age, gender, favclass):
self.name = name
self.age = age
self.gender = gender
self.fac = favclass
choice = int(raw_input("Make a Choice: " ))
while (choice !=0):
if (choice==1):
print("STUDENT")
namer = raw_input("Enter Name: ")
ager = raw_input("Enter Age: ")
sexer = raw_input("Enter Sex: ")
faver = raw_input("Enter Fav: ")
elif(choice==2):
print "TESTING LINE"
elif(choice==3):
print(len(a))
guess=int(raw_input("Make a Choice: "))
s = Student(namer, ager, sexer, faver)
a =[];
a.append(s)
raw_input("Press enter to exit")
Any help would be greatly appreciated!
The problem appears to be that you are reinitializing the list to an empty list in each iteration:
while choice != 0:
...
a = []
a.append(s)
Try moving the initialization above the loop so that it is executed only once.
a = []
while choice != 0:
...
a.append(s)
Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}