What's wrong with my code? name is not defined? [duplicate] - python

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 6 years ago.
Here I've defined a function that creates a list using the argument "number in list". I can use the function but when I try to print the list it says the variable isn't defined. Anytime I try to take the declared variables out of the defined function, it tells me local variable "i" referenced before assignment. Can someone help me get this code to work? Thanks!
def create_list(number_in_list):
i = 0
numbers = []
while i < number_in_list:
numbers.append(i)
i += 1
print "How many numbers do you want in your list?"
value = int(raw_input("> "))
create_list(value)
print "The numbers: "
print numbers
for num in numbers:
print num

Your numbers variable exists only in the function create_list. You will need to return that variable, and use the return value in your calling code:
Thus:
def create_list(number_in_list):
i = 0
numbers = []
while i < number_in_list:
numbers.append(i)
i += 1
return numbers # <----
And in your main code:
numbers = create_list(value)

Related

How come the global variable is not returned despite keyword global being used [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 4 months ago.
I have accessed a global variable called counter using the keyword global however the function does not return the global variable. Oddly, print works but not return.
FYI: The function below is recursive and is supposed to take as input any integer and output the number of steps required to reduce it to 0, depending on whether it's odd or even at each iteration.
counter = 0
def number_of_steps(num):
global counter
if num == 0:
return(counter)
elif num % 2 == 0:
num = num / 2
counter += 1
number_of_steps(num)
else:
num -= 1
counter += 1
number_of_steps(num)
number_of_steps(2) #expect => 2, but actually get NoneType
As pointed out by #tripleee this is a duplicate of this post
In short, Python implicitly returns None if a return statement is not added.

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!

Having difficulty getting my code to run correctly [duplicate]

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)

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)

why am i getting invalid syntax? [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 8 years ago.
generate 10 random integers 1-100 store them in a list. Use a loop. Use a second loop to process the list. In this latter loop, display all numbers in the list and determine the sum of the odd numbers and the sum of the even numbers. Display these sums after the second loop has ended. what's wrong?
import random
randomList = [] # create list
sumEven= sumOdd = 0
for x in range(10):
r = random.randint(1,100)
print(r),
randomList.append(r)
for x in range(len(randomList)):
if (randomList[x]%2 == 0): #even number
sumEven += randomList[x]
else:
sumOdd += randomList[x]
print "\nSum of even numbers =",sumEven
print "Sum of odd numbers =",sumOdd
In the future, please post the full error message.
That being said, print is a function. You should use parentheses with it.
https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function

Categories

Resources