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__":
Related
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.
I have made this short questionnaire:
from random import randint
def pancakes():
q = raw_input("Do you like pancakes?")
if q == "yes":
print("Great!")
elif q == "no":
print("Hmmm...")
def french_toast():
q = raw_input("Do you like french toast?")
if q == "yes":
print("Oh!")
elif q == "no":
print("Same here!")
def random():
num = 2
while num > 0:
random = randint(1, 2)
if random == 1:
num = num -1
pancakes()
elif random == 2:
num = num -1
french_toast()
random()
My goal here was to get the questions in a random order. But sometimes the same question will be asked twice since it's randomly chosen.
So how can I make it ask the same question only once?
Instead of a while loop, I'd suggest you use a for loop in conjunction with random.sample. Create a list of functions before-hand to provide to sample:
from random import sample
funcs = [french_toast, pancakes]
for func in sample(funcs, len(funcs)):
func()
this will now loop through all functions randomly selecting a function in each iteration.
Alternatively, you could shuffle the list (performs in-place) with random.shuffle and then iterate through it, that will be faster too (though, speed shouldn't be the biggest concern here):
from random import shuffle
funcs = [french_toast, pancakes]
shuffle(funcs)
for func in funcs:
func()
Put these in a function if so required:
from random import shuffle
# use *funcs for passing arbitrary number of
# functions as positional arguments.
def call_funcs_randomly(funcs):
shuffle(funcs)
for func in funcs:
func()
and call them:
call_funcs_randomly([french_toast, pancakes])
As a comment noted, don't use random as a function name, it has the possibility of masking the module random leading to odd looking errors.
I would use random.sample Link. Just create a list of indices to your questions and sample 2 of them.
EDIT:
additionally, you could use random.shuffle Link:
random.shuffle(questions)
for question in questions:
# process your random question once
how about this for your last question (random is not a good name! you might overwrite the module of the same name [although you are fine the way do do it right now])
def random_questions():
eligible_questions = [pancakes, french_toast]
while eligible_questions:
question = random.choice(eligible_questions)
eligible_questions.remove(question)
question()
put the questions in a list, select one with random.choice, remove it from the list and execute it. stop if the question list is empty. this way every question is selected exactly once.
this is easily extended if you want to add more questions.
on second thought: the shuffle version in Jim Fasarakis-Hilliard's answer is a lot cleaner!
Working with random functions and doing 3 things with 3 different functions, the first gives me values from 1,10 randomly displayed in a list of 10 integers. The second gives me a list values 1,10 and squares them. Then last but not least the third singles out numbers that can be divided by three. The problem is my program is not running while on eclipse the program has no errors, yet my program terminates without printing anything. Please help me...
import random
def main():
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
if __name__ == '__main__':
main()
You are just calling main() not any of the functions nested inside main(),
Using if __name__ == '__main__': does not magically call all your functions.
If your main function was like:
def main():
squareint_()
div3()
rand10()
then you would be calling the other functions as it is, main does nothing or returns nothing.
As far as your methods go, squares.append(random.randint(0,10))**2 is not valid, you cannot use ** on a list method.
It needs to be inside the paren squares.append(random.randint(0,10)**2)
Also num is a list so you cannot use if num % 3 == 0:
You could use something like:
def div3():
divlist = []
num = range(1,10)
for n in num: # loop over the list elements
if n % 3 == 0:
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
There are two current problems with the code:
You're defining your functions inside main(), which is allowed but it's not very good coding practice. If you do this, then you can only ever use these functions from inside main().
You're not actually calling any of your functions, you're just defining them. They need to be called with rand10(), squareint_() or div3().
Try this bit of code instead, which fixes both issues:
import random
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
def main():
rand10()
squareint_()
div3()
if __name__ == '__main__':
main()
Of course, if your functions are invalid, then they will need to be fixed on their own. This just solves the issue of nothing happening when you execute your code. Now when you run the project in Eclipse, you'll see some errors and be able to fix them properly.
I am making a serial key generator for a school exercise, and I am running into a small problem. When I run the program, and type in I want to make 20 serial keys, the program will make twenty of the same keys. The cause of this is in the for loop making variables every time it passes by. (The v{0} thing)
I can not figure out how to use another method to read all the values in a list, and create variables out of them.
My code:
import random, sys
class Application:
def __init__(self):
global i
i = int(input("How many serial codes do you want to create?\n"))
print("")
self.main(i)
def main(self, i):
seq = "ABCDFGHJIKLMNOPQRSTUVWXYZ1234567890"
store = []
for z in range(0, i):
for x in range(0, 5):
first = random.choice(seq)
second= random.choice(seq)
third = random.choice(seq)
fourth =random.choice(seq)
fifth = random.choice(seq)
serial = first + second + third + fourth + fifth
store.append(serial)
for y, item in enumerate(store):
setattr(sys.modules[__name__], 'v{0}'.format(y), item)
create = v0 + "-" + v1 + "-" + v2 + "-" + v3 + "-" + v4
print(create)
print("\nCreated", i, "serial keys!")
if __name__ == '__main__':
app = Application()
You are doing some very funky stuff there that is totally not necessary.
This loop is your problem:
for y, item in enumerate(store):
setattr(sys.modules[__name__], 'v{0}'.format(y), item)
You are setting the same 5 global variables over and over again, overwriting the previous version. Your use of setattr(sys.modules[__name__], ..) is totally not needed when you have the globals() function giving you the global namespace as a dictionary. But setting global variables to solve a simple problem is like using a shotgun to catch one gnat.
Your code could be vastly simplified:
def main(self, count):
seq = "ABCDFGHJIKLMNOPQRSTUVWXYZ1234567890"
for i in range(count):
print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)))
print("\nCreated {} serial keys!".format(count))
Sample printed output for count set to 5:
LWLGX-F6MNR-9YIZC-H23TK-TIGB9
YALYY-4ZARO-8H9BV-YMHVD-HFFGP
JNA5R-65GT1-TZ3BM-PNMZI-56NM3
39VCY-MLZ98-SU1PP-PYMX7-RZJQZ
76LGC-VF5MG-LK7C4-XPUSO-H0B97
You may find it useful to print store at the end for debugging purposes. You continually append to the list, but only ever read the first five elements.
The use of global variables is a bit odd to me, but the underlying problem is the way you're using the list.
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.