Changing a variable outside of a if statement using curses - python

This could be super simple but I can’t think of a solution. I want to be able to change a variable outside of a if statement. I have this in a try loop.
For example:
Try:
X = 0
If char == ord (‘w’):
X += 1
The only problem is that once it runs again the value of x will return to 0. How do I reassign the value of x to be the new number?

assign as an argument of the function what you want to change from one side and inside of the function make sure to use "return" the value that you want to be changed.
Once done push the same returned as an argument, with a loop most likely.
def function_name(x):
x +=1
print('New X Value',x)
return x
for i in range(5):
function_name(i)

Related

Why does it display "local variable referenced before assignment" even I have assigned it in the same function?

def p3(x,y,ls2):
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
c=0
break
else:
c=1
if c==0:
return False
else:
return True
Even I have assigned c in the same function, it still displays "local variable 'c' referenced before assignment"
As the comment by Suraj S says, the problem is if ls2 is an empty list (iterable). Even if that were not a problem, c is a local variable inside the for loop and even though Python allows accessing it outside its scope, it is not a good practice to do so. So it is correct to default initialize it first before running the loop. You can default it to 0 or 1 depending on your use case.
Also, practice Boolean Zen. Don't make redundant checks with booleans. It is better to use True and False instead of 0 and 1.
def p3(x,y,ls2):
c = True # default
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
c = False
break
# no need for else at all
return c
Even better:
def p3(x,y,ls2):
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
return False
# no need for else at all
return True
If I understand correctly your function, you could simplify it to the following:
def p3(x, y, ls2):
# if no list or list is empty
if not ls2: # the condition could be more convoluted if needed
return 'invalid input' # or return boolean depending on use case
for i in ls2:
# if condition is matched return immediately
if abs(i[0]-x)==abs(i[1]-y):
return False
# the condition was not matched in loop, return default True
return True
You could even simplify more using all that will stop prematurely if the condition is met:
def p3(x, y, ls2):
# if no list or list is empty
if not ls2: # the condition could be more convoluted if needed
return 'invalid input' # or return boolean depending on use case
return all(abs(i[0]-x)!=abs(i[1]-y) for i in ls2)
# or: return not any(abs(i[0]-x)==abs(i[1]-y) for i in ls2)
In general, if you instantiate a variable (namely c) inside of a for loop, it's best not to use that variable outside of that for loop.
The practical reason for this is that you can't be sure that for loop will run and so the variable might not get instantiated. The more high-level reason is to maintain a sense of scope in your code, or "what happens in the for loop, stays in the for loop", if you will.
So in your case, I would recommend instantiating c with a 'default' value (depending on what your logic is) before the for loop starts, so that even if the for loop runs 0 times, c still has a value.
Alternatively, this entire function could be implemented as
def p3(x, y, ls2):
return not any([abs(i[0]-x)==abs(i[1]-y) for i in ls2])

Omit in for loop in Python

I have a function to move between the given range of values, but I would like to add in my function a parameter that will be an array which would contain the numbers which must be skipped while my function run iteration
my function:
nums = []
def loopIteration(minValue, maxValue):
minValue += 1
for i in range(maxValue-minValue+1):
num = i+minValue
nums.append(Num('numbers_{}'.format(i)))
#function call
loopIteration(4,25)
i want to add in my function call an parameter like this:
loopIteration(4,25,[8,9,16])
thanks for any answers :)
You can use continue to skip certain is:
def loopIteration(minValue, maxValue, skip=set()):
for i in range(minValue + 1, maxValue + 1):
if i in skip:
continue
cells.append(Cell("numbers_{}".format(i)))
Continue is a Python syntax which would allow you to pass iteration in a for loop. Usually, continue can make it quite hard to follow flow later on, if you ever wish to look back on your script. Here is what you could do:
def loopInteration(minValue, maxValue, skipNums):
for number in range(maxValue-minValue+1):
if number in skipNums:
continue
num = i+minValue
nums.append(Num("numbers_{}".format(i)))
loopIteration(4,25,[NUMBERS HERE])

Number of Odds and Evens in a List Function - Python

I am trying to create a function called "odd_even" which takes my already created list (named "nums") and determines the number of odd and even numbers, and then returns the variables to me. However when I run this code I get:
NameError: name 'odd' is not defined
How do I fix this? If you can give me any useful pointers on the "return" function that would also be greatly appreciated.
import random
def main():
nums = []
for x in range(10):
nums.append(random.randrange(1,26))
def odd_even(given_list):
odd = 0
even = 0
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return odd
return even
odd_even(nums)
print("List had ", odd, "odds and ", even, "evens.")
main()
You are doing 2 things wrong.
First, you are trying to return two values but on different lines. You cant do this, to do this, do so as a tuple:
def odd_even(given_list):
odd = 0
even = 0
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return odd, even
Second, you call the function but dont store the value(s) of return. So you need change:
odd_even(nums) to odd, even = odd_even(nums)
By trying to execute:
print("List had ", odd, "odds and ", even, "evens.")
The main() is looking for variables odd and even, but they dont exist in main(), they exist locally in odd_even() (hence why you are calling return as to return them to the calling function. The reason you only see an error with respect to odd is because it is the first variable in that print() that the interpreter encounters an error on.
The only way around this without correct use of return is to declare them as global. But that is a bad idea so don't do that, keep things local on the stack!
You have some syntactic errors. Python...unlike many programming languages is whitespace conscious. This means you need to be careful with your indentation and spacing. More traditional languages like Java and C use brackets {} to define a scope, and semicolons ; to figure out line termination.
Perhaps you copied it poorly, but from what I see, it appears as though you are defining the function odd_even() within the function main(). That is, the definition of odd_even() is tabbed to the right, which means that its definition is within the function main. I assume that you want main to call the function odd_even(). Thus, you must tab it back over to the left so that it is at the same indentation level as main().
For this reason I use horizontal lines (see below) to clearly outline the scope of functions. This is good for me when I write in Python because otherwise it can be very unclear where one function ends, and where another begins.
Also, it appears as though you have 2 return statements. If you want to return 2 values, you should encompass it within an object. To get around this, there are two simple solutions that come to mind. You can make the odd_even() function access global variables (not recommended)...or you can return an array (any number of values back) or a tuple (exactly 2, but this is python specific).
Below is an implementation of both:
import random
# Declare global variables outside the scope of any function
odd = 0
even = 0
#-------------------------------------------------------------------------------
def main():
nums = [1,2,3,4,5,6,7,8,9,10]
return_value = odd_even(nums)
# Get the individual values back
o = return_value[0]
e = return_value[1]
# You can use the global variables
print("List had ", odd, "odds and ", even, "evens.")
# Or you can get the array back
print("List had ", o, "odds and ", e, "evens.")
#-------------------------------------------------------------------------------
def odd_even(given_list):
# This means we are referencing the variables odd and even that are global
global odd
global even
# Loop through the array
for x in given_list:
if x % 2 == 0:
even += 1
else:
odd += 1
return [odd, even]
#-------------------------------------------------------------------------------
main()

How to count repetitions of a recursive function?

So I have this function (example):
def monty(x):
if abs(int(x)) == 1:
print("Cool!")
print("Took %s attempts.") % (z)
elif abs(int(x)) == 0:
print("Nope.")
else:
z = z + 1
y = x - 1
monty(y)
Now, of course, 'z' has not yet been defined, so when this function is run so that the 'else' statement is called, the program returns a NameError exception.
Well, ok. Let's try making the statement this:
else:
try: z
except NameError: z = 0
else: z = z + 1
y = x - 1
monty(y)
Also assume we added the same NameError catch to the 'if' statement.
The statement always returns 'z' as 0, as the variable is utterly forgotten when 'monty' is ran again. Ok, what if we try defining z outside of 'monty' first, and drop the NameError catch?
Well, it returns a NameError again, and if we instead keep the NameError catch, it still only ever outputs 0.
So, how do I make the function increase z every time it's called validly? In other words, how can I have the program silently count how many times a function was run, to be recalled later? Let's try to avoid adding another argument to the function, for the sake of user-friendliness.
Just add z as a keyword argument:
def monty(x, _z=0):
# ...
else:
_z = _z + 1
y = x - 1
monty(y, _z)
I renamed z to _z to indicate that it is an implementation detail the end-user doesn't need to worry about. Because keyword arguments have a default, the caller of monty() doesn't have to worry about it.

(Python 2.7) Use a list as an argument in a function?

So I'm trying to learn Python using codecademy but I'm stuck. It's asking me to define a function that takes a list as an argument. This is the code I have:
# Write your function below!
def fizz_count(*x):
count = 0
for x in fizz_count:
if x == "fizz":
count += 1
return count
It's probably something stupid I've done wrong, but it keeps telling me to make sure the function only takes one parameter, "x". def fizz_count(x): doesn't work either though. What am I supposed to do here?
Edit: Thanks for the help everyone, I see what I was doing wrong now.
There are a handful of problems here:
You're trying to iterate over fizz_count. But fizz_count is your function. x is your passed-in argument. So it should be for x in x: (but see #3).
You're accepting one argument with *x. The * causes x to be a tuple of all arguments. If you only pass one, a list, then the list is x[0] and items of the list are x[0][0], x[0][1] and so on. Easier to just accept x.
You're using your argument, x, as the placeholder for items in your list when you iterate over it, which means after the loop, x no longer refers to the passed-in list, but to the last item of it. This would actually work in this case because you don't use x afterward, but for clarity it's better to use a different variable name.
Some of your variable names could be more descriptive.
Putting these together we get something like this:
def fizz_count(sequence):
count = 0
for item in sequence:
if item == "fizz":
count += 1
return count
I assume you're taking the long way 'round for learning porpoises, which don't swim so fast. A better way to write this might be:
def fizz_count(sequence):
return sum(item == "fizz" for item in sequence)
But in fact list has a count() method, as does tuple, so if you know for sure that your argument is a list or tuple (and not some other kind of sequence), you can just do:
def fizz_count(sequence):
return sequence.count("fizz")
In fact, that's so simple, you hardly need to write a function for it!
when you pass *x to a function, then x is a list. Do either
def function(x):
# x is a variable
...
function('foo') # pass a single variable
funciton(['foo', 'bar']) # pass a list, explicitly
or
def function(*args):
# args is a list of unspecified size
...
function('foo') # x is list of 1 element
function('foo', 'bar') # x is list with two elements
Your function isn't taking a list as an argument. *x expands to consume your passed arguments, so your function is expecting to be called like this:
f(1, 2, 3)
Not like this:
f([1, 2, 3])
Notice the lack of a list object in your first example. Get rid of the *, as you don't need it:
# Write your function below!
def fizz_count(lst):
count = 0
for elem in lst:
if elem == "fizz":
count += 1
return count
You can also just use list.count:
# Write your function below!
def fizz_count(lst):
return lst.count('fizz')
It must be a typo. You're trying to iterate over the function name.
try this:
def fizz_count(x):
counter = 0
for element in x:
if element == "fizz":
counter += 1
return counter
Try this:
# Write your function below!
def fizz_count(x):
count = 0
for i in x:
if i == "fizz":
count += 1
return count
Sample :
>>> fizz_count(['test','fizz','buzz'])
1
for i in x: will iterate through every elements of list x. Suggest you to read more here.

Categories