-5

Python is saying that the name 'height' is not defined, and I have no idea why that is, as according to my logic, I return the variable height, so I would be able to access it within my for loop?

Can someone point me in the right direction? Thanks. Edit: the get_int() is a function inside the cs50 library.

import cs50

def main():

    print("Enter a number between 0 and 26: ", end="")

    i = get_height("Enter height: ", end="")

def get_height():
    while True:
        height = get_int()
        if height <= 0 or height >= 23:
            break
    return height


for i in range(height):
    print(" " * (height - i), end="")
    print("#" * (i + 2), end="")
    print("")


if __name__ == "__main__":
    main()
Jake
  • 53
  • 1
  • 3
  • 8
  • Do you mean `for i in range(get_height())`? Returning height does not return the variable's name, it returns the value. – Treyten Carey Nov 14 '17 at 17:41
  • 1
    In other words, the name `height` in `get_height` is local to the `get_height` function, it has no connection to anything with that name outside the function. Also, `get_height` is being called in `main`, but `main` itself isn't being called until the very last line of the script. – PM 2Ring Nov 14 '17 at 17:43
  • Hello Jakob, this other question might be able to point you in the right direction. https://stackoverflow.com/questions/419163/what-does-if-name-main-do – MackM Nov 14 '17 at 17:47
  • @ForceBru My deepest apologies for my ignorance. – Jake Nov 14 '17 at 18:15

2 Answers2

1
def get_int():
    tx = input("Enter height: ")
    if tx.isdigit():
        return int(tx)
    return None

def get_height():
    while True:
        height = get_int()
        if height and height > 0 and height < 26:
            return height


if __name__ == "__main__":
    print("Enter a number between 0 and 26: ")

    height = get_height()
    for i in range(height):
        print(" " * (height - i), end='')
        print("#" * (i + 2), end='')
        print("")
  1. get_int doesn't exists
  2. height was out of scope
  3. height on the while loop was not visible from the def scope
  4. get_height get no param
  5. for in range was out of the main scope
Rafael Quintela
  • 1,908
  • 2
  • 12
  • 14
  • Can you explain to me why when I try to run this, and enter a number, in the console, it just jumps to a new line and waits for some input it seems, nothing else happens. Also, in your if statement, you say "if height and height" is that a typo or intentional? Thank you – Jake Nov 15 '17 at 16:32
  • @JakobHansen `input` is a built-in command to ask user for input. The the `if height` is because the `get_int` can return `None`, so we need to check. – Rafael Quintela Nov 16 '17 at 12:02
0

First, off you need to use hight = raw_input("What is your hight") to get your height. You can then use int(height) to use it as an integer. Secondly, you need to have it be top-down processing.

wpercy
  • 9,636
  • 4
  • 33
  • 45