Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

In Python, is it possible to assign an if-then statement to a variable?

I've defined a few variables below and I want to use them to define a variable.

today = datetime.today()
datem = str(datetime(today.year, today.month, 1))
curr_month = datem[5:7]
curr_year = datem[2:4]
list_early_fy = ['04', '05', '06', '07', '08', '09', '10', '11', '12']

I then want to use these to define the fiscal year I'm using. I tried both methods below (the first one was what I was really looking for), but both just said "invalid syntax".

test_year = if curr_month in list_early_fy:
            print(int(curr_year)+1, curr_year)
    
def test_year:
        if curr_month in list_early_fy:
            print(int(curr_year)+1, curr_year)

Finally, I want to use that "test_year" variable in other places in my code. Anyway, any suggestions on how to make this work?

question from:https://stackoverflow.com/questions/65850929/in-python-is-it-possible-to-assign-an-if-then-statement-to-a-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A function needs to at least have parentheses, even if it takes no parameters, so def test_year: won't work. An if statement can't be assigned to a variable. Instead, you could define a function that accepts curr_month and list_early_fy as parameters,

def test_year(curr_month, curr_year, list_early_fy):
        if curr_month in list_early_fy:
            print(int(curr_year)+1, curr_year)

And you'd call it via test_year(curr_month, curr_year, list_early_fy).

If you had a class that stored curr_month, curr_year, and list_early_fy, you could reference those class variables:

class MyClass(object):
    def __init__(self, curr_month, curr_year, list_early_fy):
        self.curr_month = curr_month
        self.curr_year = curr_year
        self.list_early_fy = list_early_fy
    
    def test_year():
        if self.curr_month in self.list_early_fy:
            print(int(self.curr_year)+1, self.curr_year)

c = MyClass(curr_month, curr_year, list_early_fy)
c.test_year()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...