Python中的简单逻辑错误

时间:2015-07-08 20:03:58

标签: python function csv functional-programming

我的代码的第12行和第13行不影响该程序。

当前输出:

嗨10

嗨10

hola 10

期望的输出:

嗨10

hi 6

hola 10

CSV输出右栏中的第二个数字应更改为6而不是10(由于第12行和第13行)为什么这些行没有影响?

感谢您的任何帮助或想法。

# -*- coding: utf-8 -*-
import csv
levels = [["1"], ["2"], ["3"]]
def column1Logic(self, level, greeting):
    self.column1 = "logic worked"
    if greeting == ["hola"]:
        self.column1 = ["poop"]
    else:
        self.column1 = self.greeting
def column2Logic(self, level, greeting): # budget
    self.column2 = 10 
    if level == [2]: 
        self.column2 = self.column2 * .6
class Row(object):
    column1 = "name"
    column2 = "budget"
    greeting = "oh"
    def __init__(self, level, greeting):
        self.level = level
        self.greeting = greeting
    def rowEntry(self, level, greeting):
        column1Logic(self, level, greeting)
        column2Logic(self, level, greeting)
        lol = [[self.column1], [self.column2]]
        lol[0] = self.column1
        lol[1] = self.column2
        file_writer.writerow([o for o in lol])
with open("test.csv", "wb") as test_file:
    file_writer = csv.writer(test_file)
    for a in range(0, len(levels)):
        if levels[a] == ["3"]:
            greeting = "hola"
            food = Row(levels[a], greeting)
            food.rowEntry(levels[a], greeting)
        else:
            greeting = "hi"
            food = Row(levels[a], greeting)
            food.rowEntry(levels[a], greeting)

1 个答案:

答案 0 :(得分:2)

if level == [2]:需要使用字符串'2'而不是数字2才能将该条件评估为True。你在if levels[a] == ["3"]:的不同行中做对了。