#The following code is used by the instructor to demonstrate how /if/ functions: def absolute(x): if x < 0: # if x < 0 is True, then execute line 5, i.e. x = -x x = -x return x # this line is executed whether or not line 4 is True or False print absolute(-3) #>>>3 (the '#>>>' indicates the actual output of in code editor) print absolute(4) #>>>4 #Following this logic, I wrote a procedure that compares two parameters and returns bigger one, #shown below #version_1: #CLARIFICATION by Johanne: the logic in the above code applies only when /else/ is not present #before /return x/ (line 6) #version_1 def bigger (a,b): if a > b: b = a return b print bigger(2,7) #>>>7 print bigger(3,2) #>>>3 print bigger(3,3) #>>>3 #This procedure seems OK, printing out correct answers. But in the lecture, the instructor #suggested two other versions, which seem to contradict my understanding of the use of /if/, #as shown in the following code: #version_2 def bigger(a,b): if a > b: return a return b print bigger(2,7) #>>>7 print bigger(3,2) #>>>3 print bigger(3,3) #>>>3 #The rationale behind the first two procedures predicts that #version_2 should return 2 values, #i.e. both line 38 and line 39 will be executed, contrary to the actual output. #CLARIFICATION by Johanne: one function can only have one return. #version_3 def bigger(a,b): if a > b: r = a else: r = b return r print bigger(2,7) #>>>7 print bigger(3,2) #>>>3 print bigger(3,3) #>>>3 #CLARIFICATION by Johanne: if /else/ is present, then only one of line 54 and line 56 will be #executed.
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question