我的逻辑运算符理解尝试

2024-10-01 00:24:42 发布

您现在位置: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'"

Tags: ortrueageifbinusrdefstatus
2条回答

多亏了@PatrickArtner,我才能够用构建程序的初始IF语句来实现它。谢谢您!!!你知道吗

#!/usr/bin/env python3


def statusCheck(somage):
    if somage >= 65:
        return True
    else:
        return False

def ageCheck():
    while True:

        age = input("Enter Your Age: ")

        if age.isdigit() and int(age) > 0: 
            return int(age)

def discountCheck(someage, mystatus):
        if (someage >= 65 and mystatus == "isAble") or someage < 18: 
            print("You get 5% off")
        else:
            print("Age inacceptable")

def welcome():
    print()
    print("Welcome to Age Test")


welcome()

age = ageCheck()
statusCheck(age)

def ifstatus():
    if statusCheck(age) == True:
        status = "isAble"
        return str(status)

status =  ifstatus()

discountCheck(age, status)

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

改用age。你知道吗

注意范围-在ageCheck()内的status不是您的全局status,而是一个局部变量。使用status作为stringbool取决于函数。你知道吗

决定使用哪一个或两个不同的变量作为status(true/false)和status(retired或not)。你知道吗

您可以这样重写一些代码:

#!/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.

HTH公司

相关问题 更多 >