简体   繁体   中英

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.

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.

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