Global list doesn't contain value at another function - python

I want to make a global list and I saved a value in my global list (def rand()).
Whatever I save, my saved value doesnt include at another function except rand().
What am I missing?
sayi = []
def rand():
global sayi
initial = 1000
for i in range(1000,10000):
initial +=1
sayi.append(initial)
print sayi[43]
def main():
rand()
print len(sayi) # Shows 0 but I have added value at rand funct. with append funct.
main()

I'm going to assume you're new to python. INDENTATION MATTERS. Not trying to be mean, but I've noticed that trips a lot of people up. Here's your modified code.
sayi = []
def rand():
global sayi
initial = 1000
for i in range(1000,10000):
initial +=1
sayi.append(initial)
print sayi[43]
def main():
rand()
print len(sayi) # Shows 0 but I have added value at rand funct. with append funct.
main()
you have everything working, your indentation is just a little off.

Related

Why does my code only work when running the first function but the second function gives me a referenced before assignment variable?

I've tried changing the name of the variable thinkig that was the issue but that didn't fix it. I'm trying to calculate the additive persistence and multiplicative persistence and the additive and multiplicative roots of a number entered into the get_numbers function. For the additive_calculator and multiplicative_calculator functions whichever one I call first works, but the second one gives me an error at the print statement saying that the value of of the root, which I called total and total2 in this case, gives me a referenced before assignment error. I have no idea what to do to fix this error.`enter code here
from functools import reduce
def get_numbers():
num = (int(input("Please enter an integer(negative integer to quit):")))
nums = [int(a) for a in str(num)]
return(nums)
nums = get_numbers()
print(nums)
def additive_calculator(nums):
print("Additive loop")
counter = 0
while len(nums) > 1:
for num in nums:
len(nums)
total = 0
total = sum(nums)
list.clear(nums)
nums = [int(a) for a in str(total)]
print("sum:", total)
print(len(nums))
counter = counter + 1
print("Additive persistence", counter,",", "Additive Root:", total)
print("DONE")
def multiplicative_calculator(nums):
print("multiplicative loop")
counter = 0
while len(nums) > 1:
for num in nums:
len(nums)
total2 = 0
total2 = reduce(lambda x, y: x*y,(nums))
list.clear(nums)
nums = [int(a) for a in str(total2)]
print("sum:", total2)
print(len(nums))
counter = counter + 1
print("multiplicative persistence", counter,",", "multiplicative Root:", total2)
print("DONE")
multiplicative_calculator(nums)
additive_calculator(nums)
If you assign to a variable anywhere in a function, that variable is considered a local variable (unless declared global or nonlocal). It doesn't matter if you actually do the assignment when the function runs; it suffices that there is some statement in the function that assigns to it.
For example, in the function below, you assign to the variable a only if the argument b is true, but a is still a local variable if you don't assign to it (when b is false).
def f(b):
if b:
a = "foo"
return a
f(True) # -> "foo"
f(False) # error
It's the same with loops. If you assign to a variable in the body of a loop, or the variable in a for loop, that variable is a local variable even if you don't execute the body of the loop. If you execute the body, the variable is assigned to, and it is safe to read it, but if you do not execute the body, the variable isn't initialised, and it is an error to read it.
def f(x):
for a in x:
pass
return a
f([1, 2, 3]) # -> 3
f([]) # error
In your code, if nums is empty, total2 is never assigned to. It is still a local variable because there is an assignment to it in the code--it doesn't matter that the statement is never executed--but it is an error to read the variable if you haven't assigned to it.
The fix is simple: make sure you initialise total2 regardless of whether you enter the loop body or not.
def multiplicative_calculator(nums):
print("multiplicative loop")
counter = 0
total2 = 0 # move initialisation of total2 here
while len(nums) > 1:
# same code as before...
# when you get here, total2 is initialised whether you
# entered the loop or not.
print("multiplicative persistence", counter,
",", "multiplicative Root:", total2)

Write a function which squares a number and then use it to write a function which takes three integers and returns the sum of their squares

Im new to python and cant figure out how to get these functions to call themselves. It asks for an input but no matter what gives 0 as the output. Can someone help debug?
userinput = input("Enter three numbers: ")
userinput = userinput.split(',')
finalsum = 0
finaldata = []
def formatinput(x):
sqrdata = []
for element in x:
sqrdata.append(int(element))
return(sqrdata)
def findsquare(x):
return (x*x)
def sumthesquares(y):
for element in y:
temp = findsquare(element)
finaldata.append(int(temp))
finalsum = finalsum + temp
return finalsum
def findthesquares(userinput):
finalsum = sumthesquares(formatinput(userinput))
print(finalsum)
Have you actually tried running your code? From what you've posted, it looks like you never actually call your functions...
They're defined, but you're missing the actual calls, like formatinput(userinput).
For future reference, if you put something like print("Got here!") into your functions, you can test that they're being called.

Setting up a simple function in Python

I'm trying to write a function which takes my input as amount of dicerolls, gets a random number between 1,6 for that amount of dicerolls, and then appends these to a list.
I've tried different return messages, but I can't seem to to make it append to a list, and can't really think of what else I can do with my code.
terninger = []
def terning_kast(antal_kast = int(input("Hvor mange terningekast? "))):
for x in range(antal_kast, 0, -1):
resultat = random.randint(1, 6)
terninger.append(resultat)
return resultat
print(terninger)
I'm expecting the code to append the random number 1,6 into my list above (terninger), but I'm only receiving an empty list.
you forgot to call your function => terning_kast()
terninger = []
def terning_kast(antal_kast = int(input("Hvor mange terningekast? "))):
for x in range(antal_kast, 0, -1):
resultat = random.randint(1, 6)
terninger.append(resultat)
return resultat
print('before', terninger)
terning_kast() # this is the line which you have missed
print('after', terninger)
There are few points that you need to correct in your logic. Meantime, following is probably that you want.
import random as rnd
def terning_kast(count):
terninger = []
for x in range(count, 0, -1):
resultat = rnd.randint(1, 6)
terninger.append(resultat)
return terninger
if __name__ == "__main__":
cnt = input("Hvor mange terningekast? ")
if cnt.isdigit():
print(terning_kast(int(cnt)))
else:
print("Invalid entry")
In order to use the random module, first you need to import it into your module.
Though you are appending the generated random number to list, you never attempt to return that list. What you are returning is the last instance of result from the randint(x,y) function call.
You are defining your function as part of your module/script. In order to execute that function, you must either call it within module or import it to some other module. If you look at my example the if __name__ == "__main__": instruct the python interpreter to run your script if you were to execute from same module. If you were to consume this module (importing) from some other then you don't need to mentioned this if __name__ == "__main__":

How do I use a list from a different function?

cards1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v']
def piles(cards1):
print("You must remember what card is yours!")
pile = [[],[],[]]
first = 0
second = 1
third = 2
for i in range (7):
pile[0].append(cards1[first])
pile[1].append(cards1[second])
pile[2].append(cards1[third])
first += 3
second += 3
third += 3
print(pile)
return(pile)
piles(cards1)
def sorting_piles():
sorted_piles = []
final_pile = []
which_pile = int(input("Which card is your pile in, 1,2 or 3?"))
for i in range (2):
while which_pile not in(1,2,3):
which_pile = int(input("Invalid input. Which card is your pile in, 1,2 or 3?"))
if which_pile == (1):
sorted_piles.append(pile[2,0,1])
elif which_pile == (2):
sorted_piles.append(pile[2,1,0])
else:
sorted_piles.append(pile[1,2,0])
print("This is now the new pile:",sorted_piles)
for i in range(7):
final_pile.append(sorted_piles[0][i-1])
for i in range(7):
final_pile.append(sorted_piles[1][i-1])
for i in range(7):
final_pile.append(sorted_piles[2][i-1])
print("Your card is:",final_pile[10])
return(final_pile)
sorting_piles()
Whenever I run this code, the first function runs perfectly and I am able to input which pile my card is in but after I input, I get this error message:
NameError: name 'pile' is not defined
How do I make the second function recognise the list 'pile'? Thanks
You have no variable that is catching the output being returned from the function definition. You need this :
pile = piles(cards1)
pile = piles(cards1)
You can use the return value .
Also pile[2,0,1] does not work with list.You can use (pile[2], pile[0],pile[1]).Append a tuple or list
You need to assign the return value of piles to a variable, then pass that to sorting_piles as an argument:
def sorting_piles(pile):
...
pile = piles(card1)
sorting_piles(pile)
This is a scoping issue. The pile variable defined in your piles function only exists in here, in this scope.
It looks like you're trying to access it from a different scope, inside your other function, where it doesn't exist.
You can simply create a global reference to the return value from your function like the other answers said:
pile = piles(cards1)

Python passing local variables for modification in function

and I'm trying to figure out how I would go about passing local variables to a function and then returning the modified values. I've written the code below:
def main():
change = 150
coins = 0
quarter = 25
while (change >= quarter):
change = change - quarter
coins += 1
print(coins)
if __name__ == "__main__":
main()
But I'd like to be able to extract the modification of the change and coins variables like so:
def main():
change = 150
coins = 0
quarter = 25
while (change >= quarter):
count (change, coins, quarter)
def count(change, count, n):
change = change - n
count += 1
return change, count
if __name__ == "__main__":
main()
However, I know this isn't the way to do it. From what I understand, there could be an issue with trying to return multiple variables from the function, but it also seems like there an issue when I try to even modify only the change variable within the count function.
I would really appreciate any advice.
You're returning two values from count(), so you should capture those values when you call it:
while (change >= quarter):
change, coins = count(change, coins, quarter)
Modifying ch and co inside count() will not affect the outer values change and coins.

Categories

Resources