Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm new to Python and am learning how it works through doing the exercises from project euler. Problem 2 is focused on the Fibonacci sequence for which I've created this recursive function:
def CalcFb(start,end):
if (end<=4000000):
CalcFb(end,start+end)
else:
print "Returning:",end
return end
print "Answer: {0}".format(CalcFb(start,start+1))
When I run the program I get the following output:
Returning: 5702887
Answer: None
I'm calling the function with:
start=1
I don't understand why "None" is being printed it should have printed 5702887. Can someone please help me to understand why this is happeneing?
Thanks
Dan
You are missing the return statement in the if-clause:
if (end<=4000000):
return CalcFb(end,start+end)
Otherwise you call your function recursively but only the last call returns a value and the second-to-last one does not return anything.
You are not returning any value when recursing...
def CalcFb(start,end):
if (end<=4000000):
return CalcFb(end,start+end) ### this needs to return a value as well
else:
print "Returning:",end
return end
for me its return 2
>>> def CalcFb(start,end):
... if (end<=4000000):
... CalcFb(end,start+end)
... else:
... print "Returning:",end
... return end
...
>>>
>>> start=1
>>> print "Answer: {0}".format(CalcFb(start,start+1))
Returning: 5702887
Answer: 2
Check indent.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I tried to call my function here and it returns function get_song_input at 0x7ff9869ee050
whats wrong with my code? I put it in python visualizer it worked out fine.
Album = namedtuple('Album', 'id artist title year songs')
Song = namedtuple('Song', 'track title length play_count')
def get_song_input():
"""Prompt user input."""
songtrack = input('Enter the song\'s track:\n')
songtitle = input('Enter the song\'s title:\n')
songlength = input('Enter the song\'s length:\n')
songplaycount = input('Enter the song\'s play_count:\n')
song_info = Song(songtrack, songtitle, songlength, songplaycount)
return song_info
print(get_song_input)
output:
<function get_song_input at 0x7ff9869ee050>
The function definition does not execute the function body; this gets executed only when the function is called.
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
As others have stated, you need the brackets, i.e.:
print(get_song_input())
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to make a Python function that lets me input multiple URLs, and it will return multiple dataframes, see below.
def getdata(*urls):
for i in urls:
return pd.read_csv(i,skiprows=4)
derby20, derby19, derby18, derby17 = getdata('https://uk-air.defra.gov.uk/data_files/site_data/DESA_2020.csv',
'https://uk-air.defra.gov.uk/data_files/site_data/DESA_2019.csv',
'https://uk-air.defra.gov.uk/data_files/site_data/DESA_2018.csv',
'https://uk-air.defra.gov.uk/data_files/site_data/DESA_2017.csv')
However I get the following error: ValueError: too many values to unpack (expected 4).
Any idea how I can successfully implement this?
Thank you!
You're returning once and never going in function back again. You can use yield instead of return.
def getdata(*urls):
for i in urls:
yield pd.read_csv(i,skiprows=4)
See this:
>>> def foo():
... for i in range(3): yield i
...
>>> a, b, c = foo()
>>> a, b, c
(0, 1, 2)
Change the lines
for i in urls:
return pd.read_csv(i,skiprows=4)
to
return (pd.read_csv(i, skiprows=4) for i in urls)
because after the first return command your function will not continue, effectively breaking your loop after the first iteration.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I wanted to write a simple little function to return the type to me. Unfortunately i get all those indentation errors( i use sublime text 2... no idea why i get those all the time)
def get_the_type(value):
if value== "NULL" or value=="":
return(type(None))
elif (value=="{"):
return (type([]))
elif isinstance(value,(int)):
return type(1))
elif isinstance(value,(float)):
return(type(1.1))
else:
return (type("bla"))
Can someone tell me where my error is ?
Indent inside the def and remove the extra paren:
def get_the_type(value):
if value== "NULL" or value == "":
return "NoneType"
elif value == "{":
return "dict" # maybe set?
elif isinstance(value, int):
return "int" # <- removed )
elif isinstance(value, float):
return "float"
else:
return "str"
Not sure if you want to use the type or just see what type it is, if you just want to see the type use strings as above. Also [] is a list and you have { as the value so that should maybe be a dict or set.
You're missing indentation of the if statement relative to the function definition.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My qestion is that my def kept on getting a invalid syntax.
l=0
a=1
b=1
i=int(input("How many iterations?" )
def mains():
while i>l;
l=l+1
a=a+b
print(a)
def mains()
Here is the error.
File "Fibonacci.py", line 6
def mains():
^
SyntaxError: invalid syntax
I am currently using 3.4.1 version of python.
Well firstly you have incomplete ) on the previous line:
i=int(input("How many iterations?" ))
^
and secondly, it should be : not ;:
while i>l:
and thirdly, to call a method, you just do:
mains()
not def mains()
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hey guys I am working on a python program and I keep getting errors returned from the loop which is supposed to just reprompt the user to enter a number. The problem I am having is that it keeps returning a nonetype which cannot be used to operate on which I need to do in on of the other functions any help is appreciated. Thanks.
( Here's my code, Sorry ahead of time if it is not formatted correctly. )
def getTickets(limit):
ticketSold=int(input("How many tickets were sold? "))
if (ticketsValid(ticketSold,limit)):
return ticketSold
else:
getTickets(limit)
#This function checks to make sure that the sold tickets are within the Limit of seats
def ticketsValid(sold,limit):
if (sold>limit or sold<0):
print ("ERROR: There must be tickets less than "+str(limit)+" and more than 0")
return False
return True
# This function calculates the price of the tickets sold in the section.
def calcIncome(ticketSold,price):
return ticketSold*(price)
You are not returning getTickets(limit) inside your else block:
def getTickets(limit):
ticketSold=int(input("How many tickets were sold? "))
if (ticketsValid(ticketSold,limit)):
return ticketSold
else:
return getTickets(limit) # You need to use return here
Python functions return None by default, if nothing is returned. You have an else clause that calls a function, but does nothing with it, and the function ends there, therefore if it goes down that control flow path, you will return None from that function.