简体   繁体   中英

Need to fix a function to turn an even number into the next highest odd number

This is my current code:

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

My program just makes triangles out of the users input. I need the base to be an odd number to prevent the triangle from looking like this (with base of 10):

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

When i enter 10, i get a 'NoneType' error which I'm assuming is referring to the base. If i use an odd number, like 11, everything works as it should.

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

Is there something that needs to be changed in my getBase() function?

You have your evenness test backwards; if base % 2 == 1, base is odd.

Try instead

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

You forgot to return the base! Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM