python function return not working - python-3.x

I have a recursive traversal function to go through a JSON object and return the information that I want. The problem is that it's not returning anything. I know that the recursion is working properly because I modified to function to print out the input at each step and it was printing out the expected results - including the final step.
def wikipedia_JSON_traversal(wiki):
if type(wiki)==dict:
if 'definitions' in wiki.keys():
wikipedia_JSON_traversal(wiki['definitions'])
elif 'text' in wiki.keys():
wikipedia_JSON_traversal(wiki['text'])
else:
pass
elif type(wiki)==list:
wikipedia_JSON_traversal(wiki[0])
else:
return wiki

You need a return after each function call, the returns don't bubble up automatically.
def wikipedia_JSON_traversal(wiki):
if type(wiki)==dict:
if 'definitions' in wiki.keys():
return wikipedia_JSON_traversal(wiki['definitions'])
elif 'text' in wiki.keys():
return wikipedia_JSON_traversal(wiki['text'])
else:
pass
elif type(wiki)==list:
return wikipedia_JSON_traversal(wiki[0])
else:
return wiki

Related

Why print function doesn't work in method: get_details() and None is returned for print(x.increment_odometer)?

class Car:
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_details(self): #SELF allows access of attributes and methods of a class
details=print((f'The make is: {self.make}, the model is: {self.model}, & the year is: {self.year}\n'))
#return details without print function works? i.w. details=rest of the line without print + return details (next line)
def read_odometer(self): #reading the value (default)
print(f'\nReading: {self.odometer_reading}')
def update_odometer(self,mileage):
if mileage>=self.odometer_reading:
print('\nReading has been changed')
self.odometer_reading=mileage
else:
print('\nCan, not change ')
def increment_odometer(self,miles):
self.odometer_reading+=miles
x.get_details() #trying to modify print(x.get_details()) which does work. Why does print need to be supplied here?
#incrementing the odometer
print(x.increment_odometer(50)) #why is this none?
I am learning classes and am confused about some aspects:
Why is "return details" line needed for method get_details()? Normally a simple function call having def f(): print('a') works, hence the confusion.
print(x.increment_odometer(50)) is None. Perhaps a function return needed in increment_odometer() method?
Confusing points having been commented in the code. Please englighten me.
Sincerely.

Is not using return value in Python bad practice/dangerous?

I have a function that only sometimes returns values. Below a simplified example.
def return_something(bool):
if bool:
return "Something"
else:
print("Hello ")
I figured that I could also rewrite the function as such:
def return_something():
print("Hello ")
return "Something"
As I only sometimes need the return value and when I need it the rest of the function may execute normally. Now I would call the function in two ways:
return_something()
string = return_something()
My question: When using the second design I don't use the returned value in the first function call. Is this considered bad practice and or dangerous?

I am new to python coding and i do not understand how to use a variable from another method

Here is what i have tried:
I do not understand how can i use a variable from another method of same class. Also please explain how can i use a variable from a method in different class. I tried searching but could not find a solution. So what i did to pass the test cases is to copy code from calculate_percentage and paste it in find_grade method. It worked but i think this is the worst method. So please tell a possible solution.
Thanks
#!/bin/python3
#Enter your code here. Read input from STDIN. Print output to STDOUT
class Student:
def __init__(self,roll,name,marks_list):
self.roll=roll
self.name=name
self.marks_list=marks_list
def calculate_percentage(self):
length=len(self.marks_list)
sum=0
for i in self.marks_list:
sum+=i
percent=sum/length
return int(percent)
def find_grade(self,percent):
if percent>=80:
return 'A'
elif percent>=60 and percent<80:
return 'B'
elif percent>=40 and percent<60:
return 'C'
elif percent<40:
return 'F'
if __name__ == '__main__':
roll=int(input())
name=input()
count=int(input())
marks=[]
for i in range(count):
marks.append(int(input()))
s=Student(roll,name,marks)
print(s.calculate_percentage())
print(s.find_grade())
i am getting the error:
print(s.find_grade())
TypeError: find_grade() missing 1 required positional argument: 'percent'
Thanks for every one who answered but i found the answer:
i just need to put self.percent
or percent=self.calculate_percentage() to call the method and use the variables
The assumption would be that the marks are x/100 scale while otherwise your percentage will be incorrect.
As said above, you need to pass the variable percent back to the function since it is not known in the class, it is only returned.
print(s.find_grade(s.calculate_percentage()))
or if the percentage is a class variable you can rewrite it into the class like this:
from statistics import mean
class Student2:
def __init__(self,roll,name,marks_list):
self.roll=roll
self.name=name
self.marks_list=marks_list
def calculate_percentage(self):
self.percent=mean(marks)
return int(self.percent)
def find_grade(self):
if self.percent>=80:
return 'A'
elif self.percent>=60 and self.percent<80:
return 'B'
elif self.percent>=40 and self.percent<60:
return 'C'
elif self.percent<40:
return 'F'
percent = int(0)
# test variables
vRoll = 2
vName = 'student'
vCount= 2
vMarks= [100, 75]
# main
if __name__ == '__main__':
roll=vRoll
name=vName
count=vCount
marks=vMarks
s2=Student2(roll,name,marks)
print(s2.calculate_percentage()) # 87
print(s2.find_grade()) # A

Using loops to call recursive function

I am trying to create a recursive function that takes three parameters: name of the dictionary, name of the original (This will be the key in the dict), and name of the final (trying to determine if it is possible to reach the final from the original)
My code functions well and enters the correct if statements and everything (tested using print statements) however, instead of the function returning True or False, it returns None every time.
I determined that this is because rather than calling my recursive function with "return" I only call the name of the function. However, if I include return in my code, the function only runs with the first value from the dictionary's key.
Any and all help on this would be appreciated.
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
elif babyname in dictname.keys():
if dictname[babyname]:
for i in dictname[babyname]:
evolve(dictname,i,evolvedname)
else:
return False
else:
return False
Collect all recursive call's results, and return True if any of them is true.
Something like:
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
elif babyname in dictname.keys():
if dictname[babyname]:
results = [] #To collect results
for i in dictname[babyname]:
results.append(evolve(dictname,i,evolvedname))
#Check if any of them is True
for res in results:
if res==True: return True
return False #No true among childs
else:
return False
else:
return False
But I think this code can be simplified to just:
def evolve(dictname, babyname, evolvedname):
if babyname == evolvedname:
return True
return any(evolve(dictname,i,evolvedname) for i in dictname.get(babyname,[]))
Lastly, although I don't know what you are trying to do, you might get an infinite loop, this is like doing dfs but without marking any node as already explored(black) or currently exploring(gray).

function call behaves differently in a class vs w/o class in python3

Here is my code:
#Check if the value has only allowed characters
def checkStr(value):
return (set(value) <= allowed)
#Enter parameter
def enterParam (msg)
value=input(msg)
if len(value) == 0:
print("Cannot be empty, try again")
enterParam(msg)
if not checkStr(value):
print("incorrect symbols detected, try again")
enterParam(msg)
return value
Now my question is:
This works OK inside the body of the script, but as soon as i put inside a class like below the eclipse/pydev starts complaining about enterParam and checkStr not being defined. What am i doing wrong?
class ParamInput:
#Check if the value has only allowed characters
def checkStr(self, value):
return (set(value) <= allowed)
#Enter parameter
def enterParam (self, msg)
value=input(msg)
if len(value) == 0:
print("Cannot be empty, try again")
enterParam(msg) #<==== not defined
if not checkStr(value): #<====not defined
print("incorrect symbols detected, try again")
enterParam(msg) #<====not defined
return value
You need to call the methods as self.enterParam() and self.checkStr().
(Also note that the Python style guide PEP 8 recommends to name methods like enter_param() and check_str() -- CamelCase is only used for class names in Python.

Resources