Check for Python version in script before functions are evaluated

I thought this post would answer this question, but the solution doesn't seem to work for me. My script is not compatible with Python 2, and I need it to exit gracefully if it is run with Python 2. It doesn't because python evaluates all the functions before running any code, regardless of where the code is placed.

Here's what I have:

import os, sys, re, argparse
import pandas as pd

if sys.version_info[0] < 3:
print("Please run this script using python 3 or higher")

def get_samples(filename):
    summary_table = pd.read_csv(filename, sep='\t')
except Exception:
    print(f"Could not import {filename} using Pandas")

#more functions 

def main():
    #some code here

if '__name__' == __main__:

When I test run the script in Python 2.7, the script fails at the print line (the first incompatibility location):

/usr/bin/python -d Run_2021.04.16-10.36.20_M947-21-010
File "", line 43
print(f"Could not import {filename} using Pandas")

Incidentally, the except statement for the pandas import statement also doesn't work. I wanted a clean way to exit if the import breaks. That's obviously not the point of this post, but I welcome suggestions if you happen to have them.

1 answer