python - 我的逻辑运算符理解尝试
问题描述
#!/usr/bin/env python3
status = False
while status == True:
status == "retired"
def ageCheck():
age = int(input("Enter Your Age: "))
if ageCheck.age() >= 65 or age <18:
status = True
def discountCheck():
if (ageCheck.age() >= 65 and status == "retired") or ageCheck.age() < 18:
print("You get 5% off")
def welcome():
print()
print("Welcome to Age Test")
welcome()
ageCheck()
discountCheck()
我实际上只是试图构建一个程序来理解逻辑运算符。问题是它不断抛出这个错误。
"File "/home/pi/Murach/randomtests/while test.py", line 10, in ageCheck
if ageCheck.age() >= 65 or age <18:
AttributeError: 'function' object has no attribute 'age'"
解决方案
agecheck
是一个函数 - 您访问它的age()
属性,它没有 - 因此错误。
改为使用age
。
当心范围 -status
内部ageCheck()
不是您的全局status
变量,而是局部变量。您使用status
asstring
或bool
- 取决于您的功能。
决定使用哪一个或 2 个不同的变量来表示状态(真/假)和状态(退休与否)。
您可以像这样重写一些代码:
#!/usr/bin/env python3
def getAge():
while True:
age = input("Enter Your Age: ")
if age.isdigit() and int(age) > 0:
return int(age)
# repeat until number given
def isElegibleForDiscount(someAge, isRetired):
return someAge < 18 or someAge >= 65 and isRetired # operator precedence, no () needed
def discountCheck(myAge,myStatus):
if isElegibleForDiscount(myAge, myStatus == "retired"):
print("You get 5% off")
else:
print("No discount, sorry.")
def welcome():
print()
print("Welcome to Age Test")
welcome()
age = getAge()
discountCheck(age,"retired")
discountCheck(age,"still kickin")
避免在解析非整数输入时出错,在不需要全局变量的情况下传递变量并方便您的逻辑检查。
17 的输出:
Welcome to Age Test
Enter Your Age: 17
You get 5% off
You get 5% off
65 的输出:
Welcome to Age Test
Enter Your Age: 65
You get 5% off
No discount, sorry.
高温高压
推荐阅读
- php - 如何过滤 php 二维数组以返回具有包含搜索查询作为通配符的名称属性的元素?
- pycharm - pycharm - 我什么时候应该在路径中使用查找(cmd-shift-f),什么时候应该在任何地方使用搜索(双班)?
- angular - 对于不同的按钮单击,将调用相同的模式弹出窗口,每次调用的模式弹出窗口中的数据略有不同
- python - 在词标记化和小写之后删除停用词
- javascript - 与 expo 深度链接到特定屏幕或组件
- typescript - 如何正确输入“类型映射”函数
- html - 表单操作不适用于 Android 或 iOS
- django - 如何在 Django 模型(休息框架)中返回图像文件?
- python - 比较两组最有效的方法是什么?
- python - tkinter python上的鼠标事件,没有返回输出