“如果”状态下的多项任务

2024-04-16 20:30:12 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么我不能在python中的if语句下进行多个赋值?有没有我遗漏的语法?在

我想这样做:

files = ["file1", "file2", "file3"]

print "\nThe following files are available: \n"

i = 0
for file in files:
    i = i + 1
    print i, file

choice = int(raw_input("\Enter a file number: "))

if choice ==1:
    file = np.genfromtxt(files[0], usecols = (1,2,3), dtype = (float), delimiter = '\t')
    time = np.genfromtxt(files[0], usecols = (0), dtype = (str), delimiter = '\t')

print time

时间是在if语句之外定义的,所以它不会随着选择的改变而改变……这到底是怎么回事?在


Tags: iftimenp语法files语句fileprint
2条回答

变量file和time必须在比if语句更高的块级别上定义。在

注意“time”,因为它是python模块的名称。您应该使用此名称的变体(例如time)。在

除了1之外,您没有使用任何其他选项,如果选择不是1,则会出现错误,您的代码应该如下所示

choice = int(raw_input("\Enter a file number: "))
choice -= 1 # array index is from 0

if choice < 0 or > 2:
    print "Enter correct choice"
    sys.exit()

file = np.genfromtxt(files[choice], usecols = (1,2,3), dtype = (float), delimiter = '\t')
time = np.genfromtxt(files[choice], usecols = (0), dtype = (str), delimiter = '\t')

相关问题 更多 >