python recursion is not working as expected - python-2.7

I'm new to coding and trying to teach myself about recursion by building a very simple function that calls itself. However my code is behaving slightly differently to how I was expecting:
get user input number that must not be greater than 50
def getinput():
input = int(raw_input("type number under 50 >>> "))
if input < 50:
return input
else:
print input, "no, must be under 50"
getinput()
print getinput()
This results in the following behavior:
This bit as expected
C:\Python27>python recur.py
type number under 50 >>> 23
23
This bit unexpected
C:\Python27>python recur.py
type number under 50 >>> 63
63 no, must be under 50
type number under 50 >>> 23
None
My question is, why is the last line "None", and not 23? My code seems to correctly call the function again if the user inputs a number 50 or greater, but why doesn't the second call return 23 (the same as the initial output)?
Any advice much appreciated

You don't return the result of the getInput() if the number is greater than 50
def getinput():
input = int(raw_input("type number under 50 >>> "))
if input < 50:
return input
else:
print input, "no, must be under 50"
return getinput()
print getinput()

You missed a return in the else condition. The following code should work:
def getinput():
input = int(raw_input("type number under 50 >>> "))
if input < 50:
return input
else:
print input, "no, must be under 50"
return getinput()
print getinput()

In this case your function will return input
if input < 50:
return input
You are using recursion, so it is just like a stack at the end all the return values will come back to the function which was called. When the condition if input < 50 not satisfied it will return None and you are using print(getinput()).
| 23 |
| 63 | -> None
-----
That's just my understanding about recursion.
so when the value is greater than 50, do return a value instead of None to the function back.
return getinput()
Also please use different variable names instead of input.

Related

How do I have a user enter values between 1 and 5, where 1 will return the employee information saved in the list index [0] in python [duplicate]

I am very new to programming in Python, this is something that seems so simple, but I just don't seem to be able to get it right.
I have a list of values.
I want to prompt the user for input.
Then print out the value that's at the corresponding index number in the list.
myList [0, 1, 20, 30, 40]
choice = input()
print (......)
If the user inputs 2, I want to print the the value that is at the index 2 (20). I am unsure of what to put after print.
You can do this by accessing the list using the given input by the user.
The input given by the user I assume would be a String, so we need to use int() to change it to an integer.
print myList[int(choice)]
Additionally, you may want to first check the validity of the input supplied; it cannot be less than 0, or more than the length of the list - 1;
choice = int(choice)
if (choice < 0 || choice >= len(myList))
print('Not Valid')
else
print myList[int(choice)]

How can i list a number, which this number is gave from user, in Python 2.7.14?

More accurately, I ask user for a number and after I want to list this number so i can use it for my code!
This is the part of my code i want help:
num=int(raw_input("Give me a number: "))
(*) (*)
#(*)...(*) is the part I want help!
try this :
numbers = []
num = int(raw_input('give me a number'))
numbers.append(num)
print numbers
or keep add items to the list :
numbers = []
while True:
num = int(raw_input('give me a number'))
numbers.append(num)
if the input is 10 20 30 40 50
you ca get the input as follows
number=map(int,raw_input("Enter the list of numbers:").split())
print number
this will have
number=[10,20,30,40,50]

Issues multiplying in python

I'm trying to make a very simple BTC To USD converter in python (bear with me I'm in the beginning stages), however when I print the value it prints the entered number 275 times (the value of 1 btc). I need it to return the amount entered by the user times 275 (so the user enters 1 and it multiplies 1 by 275 to return 275) Here is my current code:
enteramt = raw_input ("How many")
value = enteramt * 275
print ("This is worth" , value)
What it prints:
This is worth, 555555555555555555555555555555555555555555555555555555555555555
Except, theres 275 of them, but you get the point
In python 2 raw_input returns a string and in python somestring * value repeats the string value times. You want to convert the input to an int and then do the multiplication. (you also want to remove the parens from the print, that's a python 3 thing)
enteramt = raw_input ("How many")
value = int(enteramt) * 275
print "This is worth" , value
In python 3, raw_input is replaced by input, so you'd write
enteramt = input ("How many")
value = int(enteramt) * 275
print("This is worth" , value)
This is because enteramt is a string. Multiplying a string in python will produce the string repeated. For example:
str = '12'
str * 4
>>> '12121212'
You should convert your input to float or int:
str = float(str)
str * 4
>>> 48.0
You need to convert your raw_input()
So your new code should be like this:
enteramt = float(raw_input("How many"))
value = enteramt * 275
print ("This is worth" , value)
Or this:
enteramt = raw_input("How many")
value = float(enteramt) * 275
print ("This is worth" , value)

Python: how to display exact decimal value

I have a dictionary like
>> dic = {'yearly': 79.00, 'monthly': 59.00}
when the dic is printed the, it removes the last zero from the decimal number.
>> print dic
>> {'monthly': 59.0, 'yearly': 79.0}
How to get the original value as 59.00 not as 59.0 ?
when you print a number, you could do
x = 5
print '%.2f' % x
where the 2 specifies u want 2 decimal place
alternatively, the more updated/versatile version is
print '{:.2f}'.format(x)
if you really want your dict object to print nicely, you could create a custom class that specifies the __str__ function to print the dict however you want to print it

Python remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s