Having difficulty getting my code to run correctly [duplicate] - python

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 3 years ago.
Beginner programmer here working with Python and am currently experiencing a bug.
I am trying to write a function where, when a user inputs a number the machine will return True if the number input is 5. If the number input is any other number it will return as None.
Currently, when I enter 5 I will get True followed by None. If I enter any other number I will get None followed by None again. Anyone have any ideas?
Here is the code:
x = int(input('Enter a number: '))
def is_it_five (x):
if x == 5:
print(True)
else:
print(None)
print(is_it_five (x))

Your first value is coming from the loop, and the second value 'None' is coming from Print function, since you are not returning anything.
Either you can call the function without print statement:
is_it_five (x)
Or you can return it from the function and print.
x = int(input('Enter a number: '))
def is_it_five (x):
if x == 5:
return True
else:
return None
print(is_it_five (x))

x = int(input('Enter a number: '))
def is_it_five (x):
if x == 5:
return(True)
else:
return(False)
print(is_it_five (x))

Functions in Python always return some value. By default, that value is None.
So if I create any random function e.g
def get_string(some_string):
print(some_string)
and then execute it;
get_string("Example")
The output will be
Example
But, if you do print(get_string("Example"))
The output will change to
Example
None
This is because the
get_string("Example")
is treated as an object in this case when you pass it inside the print statement.
However, when you are calling the function without printing it, you are not printing the value which the function returns.
In the same context if you do something like
value = get_string(some_string)
Your string will get printed as usual, but now the value variable will contain None.

Your problem is that you are printing a function that already prints something when called. Replace
print(is_it_five(x))
with just
is_it_five(x)

Related

why do this line of code return none even though there's return in the line [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
def recursion():
A=input("please enter a number between 1-5:")
if A.isdigit():
A=int(A)
if A in range(1,6):
return A
else:
recursion()
else:
recursion()
print(recursion())
so the first time that I input the right number that it should return it would return the value correctly but when I'm spamming other stuff that it would make the code return back to recursion() line for about 10 times then after that when I put 3 in the input section which is the correct value and it should return 3 but it returns as none why does it return like that cuz I already put return A so for example
please enter a number between 1-5:d
please enter a number between 1-5:sd
please enter a number between 1-5:fsd
please enter a number between 1-5:f4
please enter a number between 1-5:4
None
the first 1 to 4 line I input something that would make it run the recursion() line again but the last one that I input I input it as 4 which it should return as 4 but it returns as none
please enter a number between 1-5:3
3
this is what I mean by the first time that I enter the correct number then it would return correctly
I would be very appreciative if you corrected my code because I'm so bad at python I'm just a beginner and sry for terrible grammar I'm not a native speaker but at least I tried
You need to return the value returned by the call to the recursive function
def recursion():
A=input("please enter a number between 1-5:")
if A.isdigit():
A=int(A)
if A in range(1,6):
return A
else:
A = recursion()
else:
A = recursion()
return A
print(recursion())
Personally, I'd use a loop to do this instead rather than calling the same function again.
def getNumber():
valid = False
while not valid:
A=input("please enter a number between 1-5:")
if A.isdigit():
A=int(A)
if A in range(1,6):
valid = True
return A
print(getNumber())

What is the quick meaning of the terms print and return in Python? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed last month.
I'm learning some new things, and I cannot figure out the whole return process from reading my texts and looking online. I believe I need it explained to me once for me to wrap my head around it.
The code here works as intended; I would like the user to input a number, then if less than 0, print 0, if greater than or equal to zero print the number.
def positiveNumber():
num = int(input("Please enter a number: "))
if num <= 0:
print("0")
else:
print(num)
positiveNumber()
What isn't working is where I just want the function to return the values, then only give me the answer when I call the function.
def positiveNumber():
num = int(input("Please enter a number: "))
if num <= 0:
return 0
else:
return num
positiveNumber()
print(num)
My shell keeps telling me "name 'num' is not defined".
num is a local variable that only exists in positiveNumber().
You want:
print(positiveNumber())
The variable num is defined within your function. It thus only exists in the "scope" of the function.
When you're calling the function, you should try
a = positiveNumber()
print(a)
The returned value is something that you should assign to a variable in order to use.
Your function is sending back the value of num
So you can either
print(positiveNumber())
Or you can store it somewhere, and then use that.
This happens because the name num only exists inside the function, it's computed and the VALUE is being returned. So you can either directly print this VALUE or you could store it in some variable and then use it.
Here is the code that worked:
def positiveNumber():
num = int(input("Please enter a number: "))
if num <= 0:
return 0
else:
return num
print(positiveNumber())
Thank you so much!

How can I add 1 to the parameter [duplicate]

This question already has answers here:
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
Closed 6 years ago.
Im stuck with this very simple code were I'm trying to create a function that takes a parameter and adds 1 to the result and returns it but somehow this code gives me no results. (I've called the function to see if it works.)
Somebody please help me since I'm very new to python :)
def increment(num):
num += 1
a = int(input("Type a number "))
increment(a)`
I changed it to
def increment(num):
return num + 1
a = int(input("Type a number "))
increment(a)`
but still no results are showing after I enter a number, Does anybody know?
You need to return some value or it never will appear.
def increment(num):
return num + 1
a = int(input("Type a number "))
increment(a)
You need to ensure you return the num in the increment function and assign it to a.
Return:
def increment(num):
return num + 1
Assign:
a = increment(a)

Run while loop one extra time after condition is met

I am making an area calculator to help me understand the basics of Python, but I want to do some type of validation on it - if a length is less than zero, then ask again.
I've managed to do this with the 'validation' code inside the function for the shape (e.g. inside the 'square' function) but when I put the validation code in a separate function - 'negativeLength,' it doesn't work. This is my code in the separate function:
def negativeLength(whichOne):
while whichOne < 1:
whichOne = int(input('Please enter a valid length!'))
When I run this by calling 'negativeLength(Length)' it will ask me for the length again (as it should) but when I enter the positive length, the condition is met and so the actual loop does not run.
I have also tried (after following Emulate a do-while loop in Python?)
def negativeLength(whichOne):
while True:
whichOne = int(input('Please enter a valid length!'))
if whichOne < 1:
break
... but that doesn't work either.
I've put the parameter as 'whichOne' because the circle's 'length' is called Radius, so I'd call it as negativeLength(Radius) instead of negativeLength(Length) for a square.
So is there any way to make the while loop finish after the 'whichOne = int(input...)'?
Edit: I'm using Python 3.3.3
The code you've written works, as far as it goes. However, it won't actually do anything useful, because whichOne is never returned to the caller of the function. Note that
def f(x):
x = 2
x = 1
f(x)
print(x)
will print 1, not 2. You want to do something like this:
def negative_length(x):
while x < 0:
x = int(input('That was negative. Please input a non-negative length:'))
return x
x = input('Enter a length:')
x = negative_length(x)
I'm going to assume you're using Python 3. If not, you need to use raw_input() rather than input().
The code that I usually use for this would look like:
def negativeLength():
user_input = raw_input('Please enter a length greater than 1: ')
if int(user_input) > 1:
return user_input
input_chk = False
while not input_chk:
user_input = raw_input('Entry not valid. Please enter a valid length: ')
if int(user_input) > 1:
input_chk = True
return user_input
Which should do what you want.

Python not returning expected value

I simply cannot understand what is happening here. The problem is important for my homework (studying programming so I'm a beginner... also my English is not that good, sorry).
I am trying to read a string... it can be either a number or a set number of commands.
I'll just give a very small example of what I'm trying to do and what is going wrong.
def validate():
choice = str(input(">>> "))
if (choice == "exit"):
return 0 # should exit validate
else:
try:
aux = int(choice) # Tries converting to integer
except:
print("Insert integer or exit")
validate() # If it can't convert, prompts me to try again through
# recursivity
else:
return aux
rezult = validate()
print (rezult)
Problem is that this small script returns totally random stuff.
If "exit", returns "None".
If first input is correct, it returns correct number.
If first input is an "error" and second input is correct, it's "None" again and I simply can't understand what is going wrong... Why it doesn't want to work or what should I do (alternatively).
In case you enter the except block, the function validate() uses a recursive call to call itself. When this call returns, it returns to the place where the function was called, i.e. into the except block. The return value of validate() is ignored at this point, and control reaches the end of the outer call without hitting a return statement, so None is implicitly returned.
Don't use recursion here. Use a loop.
Use raw_input instead of input (unless you are on Python 3.x):
choice = raw_input(">>> ")
And you are missing a return here:
except:
print ("Insert integer or exit")
return validate () # <<< here
Also, don't use recursion for this. Use a loop instead.
Ok, decided to listen and changed the recursive part into a loop, thank you for your help. (Works now)
def validateChoice():
condition = False
while (condition == False):
choice = str (input (">>> "))
if (choice == "exit"):
return 0
else:
try:
aux = int (choice)
except:
print ("Insert integer or 'exit'")
else:
condition = True
return aux

Categories

Resources