saimadan
saimadan

Reputation: 183

how to use assert and == in python?

I'm trying to learn python. I found a question saying correct this:

def main():
    assert ___ == type("Hello World").__name__
    assert ___ == isinstance("Hello World", str)
if __name__=="__main__":
    main()

I tried:

__some__={}
def main():
    assert __some__ == type("Hello World").__name__
    assert __some__ == isinstance("Hello World", str)
if __name__=="__main__":
    main()

When I run this, I'm getting AssertionError:

Traceback (most recent call last):
  Line 6, in <module>
    main()
  Line 3, in main
    assert __some__ == type("Hello World").__name__
AssertionError

I found that assert is used to specify a condition and an exception will be raised when that condition fails. I even used python tutor, but if I put assert somevariable I'm getting assertion error. I'm unable to understand to understand how to use == and assert to accomplish some task.

Upvotes: 2

Views: 1579

Answers (1)

user3553031
user3553031

Reputation: 6214

The code that you posted on codepad.org is

__some__={}
def main():
    assert __some__ == type("Hello World").__name__
    assert __some__ == isinstance("Hello World", str)
if __name__=="__main__":
    main()

type("Hello World").__name__ is 'str' and __some__ is {}, so of course they don't match. Likewise, isinstance("Hello World", str) is True, so it doesn't match either. Your conditions are false, so the assertions fail and throw AssertionError. If on the other hand, you tried assert 'str' == type("Hello World").__name__, you'd get no exception because that comparison is true.

Also, you shouldn't declare your own variables using names like __foo__. By convention, those are reserved for special variables created by Python.

Upvotes: 4

Related Questions