需要修复一个函数,将偶数转换为下一个最高奇数

时间:2014-03-24 23:50:49

标签: python

这是我目前的代码:

def main():
print()
print("Program to draw triangles.")
print("Written by Josh Sollenberger.")
print()
triangle = ''
while(True):

    choice = getChoice()
    if choice == "1":
        triangle = triangle + makeStripeUp()
    if choice == "2":
        triangle = triangle + makeStripeDown()
    if choice == "3":
        print(triangle)
    if choice == "4":
        triangle = triangle + "\n"
    if choice == "5":
        break

def makeStripeUp():
    triangle = ''
    base = getBase()
    blanks = int(input("Enter number of blanks preceding each line: "))
    character = input("Enter character used to draw: ")
    for i in range(base//2 + 1):
        triangle = triangle + ((' ' *(i+blanks) + character * (base - (2*i)))) +'\n'
    return triangle

def makeStripeDown():
    triangle = ''
    base = getBase()
    blanks = int(input("Enter number of blanks preceding each line: "))
    character = input("Enter character used to draw: ")
    for i in range(base//2 + 1, -1, -1):
        triangle = triangle + ((' ' *(i+blanks) + character * ( base - (2*i)))) +'\n'
    return triangle


def getBase():
        base = int(input("Enter size of base: "))
        if base % 2 == 0:
            base = base + 1
        else:
            return base

我的程序只是从用户输入中创建三角形。我需要基数是一个奇数,以防止三角形看起来像这样(基数为10):

    **
   ****
  ******
 ********
**********

当我输入10时,我会得到一个' NoneType'我假设的错误是指基数。如果我使用一个奇数,比如11,那么一切都可以正常工作。

     *
    ***
   *****
  *******
 *********
***********

我的getBase()函数中是否需要更改某些内容?

2 个答案:

答案 0 :(得分:2)

你的平稳性测试倒退了;如果base%2 == 1,则base为奇数。

尝试改为

def get_base():
    base = int(input("Enter size of base: "))
    if not base % 2:
        # base is even
        base += 1
    return base

答案 1 :(得分:1)

        if base % 2 == 0:
            base = base + 1

你忘了归还基地!尝试

        if base % 2 == 0:
            base += 1
        return base