Python Forum
can you understand why this code prints None?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
can you understand why this code prints None?
#1
# assuming n is always greater than m
def fd(n,m):
    if n%m==0:
        print(m)
        return m
    else:
        print(n,m)
        fd(n,(m-1))
print(fd(6,5))
the result is not what i expect,i expect
Output:
6,5 6,4 3 3
but the result i get is:
Output:
6,5 6,4 3 None
i don't why this None is occurring??
Reply
#2
If n % m == 0, then there is a return statement. But if n % m != 0, there is no return statement. In that case, the default return of None is done by Python. You probably want line 8 to be:

return fd(n, m - 1)   # you don't need parentheses for m - 1.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
you are awesome,thanks.

(Mar-13-2019, 02:53 AM)ichabod801 Wrote: If n % m == 0, then there is a return statement. But if n % m != 0, there is no return statement. In that case, the default return of None is done by Python. You probably want line 8 to be:
 return fd(n, m - 1) # you don't need parentheses for m - 1. 


you are the best, thanks.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to understand the meaning of the line of code. jahuja73 0 270 Jan-23-2024, 05:09 AM
Last Post: jahuja73
  zfill prints extra et the end of a var tester_V 4 849 Mar-24-2023, 06:59 PM
Last Post: tester_V
  variable prints without being declared. ClockPillow 2 1,770 Jul-11-2021, 12:13 AM
Last Post: ClockPillow
  Unable to understand how given code takes a fixed input value, without inputting. jahuja73 4 2,646 Jan-28-2021, 05:22 PM
Last Post: snippsat
  Don't understand example code from a textbook lil_fentanyl 1 1,798 Jan-25-2021, 07:02 PM
Last Post: nilamo
  Output prints Account.id at the end? LastStopDEVS 5 2,718 Dec-19-2020, 05:59 AM
Last Post: buran
  Try/Exept prints only ones tester_V 11 3,737 Nov-03-2020, 02:38 AM
Last Post: tester_V
  Unable to understand a statement in an existing code ateestructural 1 2,191 Aug-01-2020, 09:38 PM
Last Post: deanhystad
  Trying to understand the python code spalisetty 2 1,836 Mar-16-2020, 08:11 AM
Last Post: javiertzr01
  loop only prints last character. mcmxl22 1 1,674 Feb-17-2020, 02:36 AM
Last Post: menator01

Forum Jump:

User Panel Messages

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