首页 > 解决方案 > 需要从用户输入添加代码但不确定如何

问题描述

我正在使用 Python 3 进行一个小型个人项目,您可以在其中输入名称并获得每周工资。我想添加一个功能,管理员可以进来并向工人添加一个人,包括他们的工资。到目前为止,这是我对人们的看法:

worker = input("Name: ")
if worker == "Anne":
    def calcweeklywages(totalhours, hourlywage):
        '''Return the total weekly wages for a worker working totalHours,
        with a given regular hourlyWage.  Include overtime for hours over 40.
        '''
        if totalhours <= 40:
            totalwages = hourlywage * totalhours
        else:
            overtime = totalhours - 40
            totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
        return totalwages


    def main():
        hours = float(input('Enter hours worked: '))
        wage = 34
        total = calcweeklywages(hours, wage)
        print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'
              .format(**locals()))


    main()
elif worker == "Johnathan":
    def calcweeklywages(totalhours, hourlywage):
        '''Return the total weekly wages for a worker working totalHours,
        with a given regular hourlyWage.  Include overtime for hours over 40.
        '''
        if totalhours <= 40:
            totalwages = hourlywage * totalhours
        else:
            overtime = totalhours - 40
            totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
        return totalwages


    def main():
        hours = float(input('Enter hours worked: '))
        wage = 30
        total = calcweeklywages(hours, wage)
        print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'
              .format(**locals()))


    main()

我想添加一个部分,如果有人输入代码或他们是管理员的东西,它将允许他们添加一个人或编辑现有的人员信息。

标签: pythonpython-3.x

解决方案


我不确定您打算如何部署它,但即使从编码的角度来看,它也不会像您期望的那样运行。我猜你这样做只是为了学习。所以,让我指出几个你对基础知识理解错误的地方,以及一个纯粹的教学示例,说明如何做到这一点。请记住,我强烈反对在任何实际环境中使用它。

您已经在代码中定义了calcweeklywages两次该函数。事实上,它只需要定义一次。如果你想使用代码,你可以调用它,就像你在main()程序中那样。该功能对您的两个工人的工作方式完全相同,因此要获得不同的每周工资,您需要传递不同的工资。但是,您如何将他们各自的工资与他们的姓名(或代码中的某些表示形式)联系起来?

这是使用面向对象编程的一个很好的例子。一个简短而有趣的入门书在这里。至于代码,它看起来像这样,

class Employee:
    def __init__(self, Name, Wage = 0, Hours = 0):
        self.Name = Name
        self.Wage = Wage
        self.Hours = Hours

def calcweeklywages(Employee, totalhours):
    '''Return the total weekly wages for a worker working totalHours,
    with a given regular hourlyWage.  Include overtime for hours over 40.
    '''
    hourlywage = Employee.Wage
    if totalhours <= 40:
        totalwages = hourlywage * totalhours
    else:
        overtime = totalhours - 40
        totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
    return totalwages

# In your main body, you just test the functionality
EmployeeList = []
EmployeeList.append(Employee("Anne", 34))
EmployeeList.append(Employee("Johnathan", 30))

while(True):
    action = input('Exit? (y/n): ')
    if(action == 'y'):
        break
    else:
        name = input('Enter the employee\'s name: ')
        for Employee in EmployeeList:
            if(Employee.Name == name):
                Person = Employee
        hours = int(input('Enter the number of hours worked: '))
        print('Wages for', hours, 'hours at', Person.Wage,'per hour is', calcweeklywages(Person, hours))

编辑:对不起,我忘记了管理部分。但这里,

class Employee:
    def __init__(self, Name, Wage = 0, Hours = 0, Admin = False, code = ''):
        self.Name = Name
        self.Wage = Wage
        self.Hours = Hours
        self.Admin = Admin
        self.code = code

def calcweeklywages(Employee, totalhours):
    '''Return the total weekly wages for a worker working totalHours,
    with a given regular hourlyWage.  Include overtime for hours over 40.
    '''
    hourlywage = Employee.Wage
    if totalhours <= 40:
        totalwages = hourlywage * totalhours
    else:
        overtime = totalhours - 40
        totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
    return totalwages

# In your main body, you just test the functionality
EmployeeList = []
EmployeeList.append(Employee("Anne", 34))
EmployeeList.append(Employee("Johnathan", 30))
EmployeeList.append(Employee("Mr. Admin", 50, 0, True, 'Open Sesame'))
while(True):
    action = int(input('Enter action :\n 1. Exit.\n 2. Add new employee.\n 3. Compute weekly wage\n'))
    if(action == 1):
        break
    elif(action == 2):
        AdminName = input('Enter operator name : ')
        Flag = False
        for EmployeeInst in EmployeeList:
            if((EmployeeInst.Name == AdminName) & (EmployeeInst.Admin)):
                code = input('Enter code :')
                if(code != EmployeeInst.code):
                    break
                NewName = input('New Employee name? :')
                NewWage = int(input('New employee wage? :'))
                EmployeeList.append(Employee(NewName, NewWage))
                Flag = True
        if(not Flag):
            print('Wrong Credentials')
            break
    elif(action == 3):
        name = input('Enter the employee\'s name: ')
        for Employee in EmployeeList:
            if(Employee.Name == name):
                Person = Employee
        hours = int(input('Enter the number of hours worked: '))
        print('Wages for', hours, 'hours at', Person.Wage,'per hour is', calcweeklywages(Person, hours))
    else:
        print('Input out of range')
        break

但同样,会话在不同内核运行之间不是持久的。没有真正的“安全”,这只是对 Python 面向对象代码的探索。请不要将其用于任何实际应用。这一切还有很多其他的东西。您需要将其存储在安全文件中,拥有一些 GUI 前端等。有更聪明的用户将指导您将系统作为一个整体实现。祝你学习顺利。干杯。


推荐阅读