python-3.x - Python 3 新手问题:这段代码高效/干净吗?它可以改进/简化吗
解决方案
我会以不同的方式组织代码。1. 打包代码片段的函数,以便它们可以重用和参数化。2.异常处理以指示不正确的用户输入。
def get_hrs_rph_from_user():
while True:
hrs = input('Enter Hours: ')
try:
hrs = int(hrs)
break
except ValueError:
print('Cannot convert [{}] into integer'.format(hrs))
while True:
rph = input('Enter Rate per Hour: ')
try:
rph = float(rph)
break
except ValueError:
print('Cannot convert [{}] into float'.format(rph))
return hrs, rph
def calculate_payout(hrs, rph, hrs_norm=40, coeff=1.5):
if hrs <= hrs_norm:
return hrs * rph
else:
return hrs_norm * rph + (hrs - hrs_norm) * coeff * rph
if __name__ == '__main__':
payout = calculate_payout(*get_hrs_rph_from_user())
print('\nCalculated payout = {}'.format(payout))
基于@Jeronimo 建议的相同代码的另一个版本(对于python 新手来说非常复杂且容易出错):
def get_from_user_factory(config):
ans = dict()
for key, elem in config.items():
def get_from_user(line=elem['input_line'], type_=elem['value_type']):
while True:
value = input('{}: '.format(line))
try:
return type_(value)
except ValueError:
print(
'Cannot convert [{}] into {}'
.format(value, type_.__name__))
ans[key] = get_from_user
return ans
def calculate_payout(hrs, rph, hrs_norm=40, coeff=1.5):
if hrs <= hrs_norm:
return hrs * rph
else:
return hrs_norm * rph + (hrs - hrs_norm) * coeff * rph
if __name__ == '__main__':
input_config = {
'hrs': {'input_line': 'Enter Hours', 'value_type': int},
'rph': {'input_line': 'Enter Rate per Hour', 'value_type': float}}
input_functions = get_from_user_factory(input_config)
input_data = {key: func() for key, func in input_functions.items()}
print('\nData from user: {}'.format(input_data))
payout = calculate_payout(**input_data)
print('Calculated payout = {}'.format(payout))
推荐阅读
- c - 有没有办法让我在 DevC++ 的 C 程序中更改特定文本的颜色?
- ionic-framework - 打开的应用程序仍然是桌面 Chrome 响应,它不是移动响应视图
- regex - 如果有多个,则匹配所有逗号
- laravel - Laravel 8 validate unique through columns and rows on create and update
- python - 用 pvpython 画线
- tensorflow - 无法从 Jupyter notebook 或 Lab 访问 Tensorflow 和 Pytorch?
- sql - 如何将 JSON 文件及其所有密钥加载到 Postgres 中?
- swiftui - GraphicalDatePickerStyle() 是十二月文本和时间压缩错误
- azure - 如何将 azurerm_resource_group_template_deployment 用于 azure 预算资源,但忽略开始和结束日期的更改?
- c# - 在 Linux 上使用 Asp.net 核心应用程序访问外部项目文件夹