首页 > 解决方案 > 我的逻辑运算符理解尝试

问题描述

#!/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'"

标签: pythonpython-3.x

解决方案


agecheck是一个函数 - 您访问它的age()属性,它没有 - 因此错误。

改为使用age

当心范围 -status内部ageCheck()不是您的全局status变量,而是局部变量。您使用statusasstringbool- 取决于您的功能。

决定使用哪一个或 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.

高温高压


推荐阅读