2

when I run mario.py it gives me this error NameError: name 'get_int' is not defined. I don't know why.

import cs50


def main():
while True:
    print("Height:")
    h = get_int()
    if h < 0 or h > 23:
     break
width = h
for i in range(h):
    print(" " * (h - i), end="")
    print("#" * (i + 1), end="")
print()

if __name__=="__main__":
main()

can someone tell me where is the problem?

4

In python, if you want to use a function from an imported library, you have to somehow tell Python that you are going to get that function from which library.

I would do:

h= cs50.get_int()

or

import cs50 as cs
h= cs.get_int()
1
  • Thank you, I forgot that. – SamGal Jun 18 '17 at 15:43
1

For the sake of completeness, you could also do:

from cs50 import get_int

h = get_int("Height: ")

But directly importing functions (or classes, etc) from a module is not recommended. It'll pollute your global namespace, and soon you'll have no idea where a given function came from.

It's much better to stick to importing modules only and using prefixed namespaces, such as cs50.get_int(). You immediately knows from which library any functions came from.

That said, there are a few other issues in the code you pasted:

  • Proper indentation is a good practice in all languages, but in Python it is required. There are many indentation errors in your code.

  • You don't need to print("Height") and then call get_int(). In both C and Python, get_int() takes a prompt as an argument and prints that for you. And IIRC, that is a required argument.

  • No need to use issuing a 3rd (empty) print() for the newline, just remove the end="" in your 2nd print() and it will print the trailing newline for you.

  • IIRC, 0 and 23 are not the valid range for mario.

Anyway, I realize this is a 2017 question, and the OP is probably graduated by now. But it might help future readers to know what to fix if they read this code.

2
  • In this case, why IIRC aren't valid for Mario? – Danellson M Apr 9 at 0:00
  • @DanellsonM: because the valid height range for Mario is [1, 8] (inclusive), and the OP is testing for [0, 23], so he's accepting heights such as 0, 10, 15, etc as valid when they're not. – MestreLion Apr 9 at 5:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .