如何将空输入转换为定义的变量?
我对 python(一般代码)非常陌生,我正在为 python 3 中的函数进行一些练习。
我知道这可能是草率的代码,我将在学习过程中努力清理它。
def show_employee():
name = input("Employee name: ")
salary = int(input("Employee salary: "))
default = 9000
if salary <= 9000:
return (f'{name}, {default}')
elif len(salary) == 0:
return (f'{name}, {default}')
else:
return (f'{name}, Salary: {salary}')
我继续收到此错误“以 10 为基数的 int() 的文字无效:''”
我想要完成的只是如果用户输入 9000 或更少的数字,它会返回他们的姓名并9000。如果他们输入超过 9000 的任何内容,它会返回他们的姓名和输入值。让我困惑的是我怎样才能得到它,这样如果他们不输入工资值,它就会默认为 9000?
感谢您抽出宝贵时间提供帮助!
I am super new to python (code in general) I was working on some practice exercises for functions in python 3.
I know it is probably sloppy code and I will work on cleaning it up over my time learning.
def show_employee():
name = input("Employee name: ")
salary = int(input("Employee salary: "))
default = 9000
if salary <= 9000:
return (f'{name}, {default}')
elif len(salary) == 0:
return (f'{name}, {default}')
else:
return (f'{name}, Salary: {salary}')
I continue to receive this error "invalid literal for int() with base 10: '' "
What I am trying to accomplish is simply if the user inputs a number 9000 or less, it returns their name and 9000. If they input anything over 9000, it returns their name and their input value. The part that is puzzling me is how can I get it so that if they do not input a salary value it will default itself to 9000?
Thanks for taking your time to help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行此操作的最佳时间是在定义
薪水
时。如果您只想处理空字符串的情况,您可以这样做:这有效,因为如果它是“truthy”并且
x 或 y
将计算为x
y(如果不是)——因此,如果maybe_thing
是任何“,则thing = Maybe_thing 或 default_thing
是分配default_thing
的便捷方法”假”值(其中包括空字符串)。如果您想用 9000 替换任何无效输入,
try/ except
会更合适:The best time to do this is at the time you define
salary
. If you just want to handle the case of an empty string, you could do:This works because
x or y
will evaluate tox
if it's "truthy" andy
if it's not -- hencething = maybe_thing or default_thing
is a handy way to assign adefault_thing
ifmaybe_thing
is any "falsy" value (which includes an empty string).If you wanted to replace any invalid input with 9000, a
try/except
would be more appropriate:不要立即将输入转换为 int:
首先检查输入是否为空,如果需要则转换为字符串:
Instead of transforming the input into an int right away:
First check if the input is empty and transform into a string if you need: