Python Forum
I am new to python and Could someone please explain how this below code is working?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am new to python and Could someone please explain how this below code is working?
#2
Calling a function returns a value. Calling print() always returns None. not None is True, so not print("sucess") is True.

In Python, A and B, B is only evaluated if A is truthy. In your code, A is a, and B is print("success")

"assert X, Y" raises AssertionError(Y) if X evaluates to something that is falsey. In your code "assert a and not print("sucess")" is X and "failure" is Y.

In an try/except:
try:
    body
except exception_type as excception_info:
    exception code
If an exception is raised while the body is executed, control jumps to the except. If the raised exception matches the exception type, the exception code is executed. Information associated with the exception can be passed as an argument (exception_info)

Putting them all together:
If a is True, then then print("success") is called to get the return value of the print() function. The expression "assert a and not print("sucess")" evaluates to True, so the assertion error is not raised.

If a is False, the print() function is not called, and AssertionError("failure") is raised.

If an AssertionError("failure" is raised, the exception code prints the exception info ("failure")
Reply


Messages In This Thread
RE: I am new to python and Could someone please explain how this below code is working? - by deanhystad - Dec-19-2022, 05:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Can you explain the strings in Python ebn852_pan 3 117 Today, 08:36 AM
Last Post: Pedroski55
  New to Python - Not sure why this code isn't working - Any help appreciated TheGreatNinx 4 1,032 Jul-22-2023, 10:21 PM
Last Post: Pedroski55
  code not working when executed from flask app ThomasDC 1 955 Jul-18-2023, 07:16 AM
Last Post: ThomasDC
  New to python/coding Need help on Understanding why this code isn't working. Thanks! mat3372 8 1,862 May-09-2023, 08:47 AM
Last Post: buran
  [split] Explain the python code in this definition Led_Zeppelin 1 783 Jan-13-2023, 10:20 PM
Last Post: deanhystad
  Explain the python code in this definition Led_Zeppelin 1 1,140 Oct-27-2022, 04:04 AM
Last Post: deanhystad
Exclamation My code is not working as I expected and I don't know why! Marinho 4 1,133 Oct-13-2022, 08:09 PM
Last Post: deanhystad
  Sudoku Solver in Python - Can someone explain this code ? qwemx 6 2,200 Jun-27-2022, 12:46 PM
Last Post: deanhystad
  Can someone explain this small snippet of code like I am a 5 year old? PythonNPC 3 1,300 Apr-08-2022, 05:54 PM
Last Post: deanhystad
  My Code isn't working... End3r 4 1,992 Mar-21-2022, 10:12 AM
Last Post: End3r

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020