# Inport functions.
from random import randint
from random import seed
# Generate numbers. The first seed is based off of how many milliseconds have passed since Epoch (1970). Aka theres no way to perfectly predict this.
seed(randint(0,100))
x = randint(0,100)
seed(randint(0,100))
y = randint(0,100)
seed(randint(0,100))
z = randint(0,100)
seed(randint(0,100))
a = randint(0,100)
seed(randint(0,100))
b = randint(0,100)
list = [a,b,x,y,z]
# Input number.
input = int(input('Input a whole number from 0 - 100.'))
# Simple check loop. 5 times since theres 5 numbers.
for x in list:
'# If input matches first item in list
if input == list[0]:
'# Set Y to 1 than stop looping.
Y = 1
break
else:
'# Otherwise delete the first item in the list and try again.
Y = 0
del list[0]
# Than if Y is one print bingo, otherwise print try again.
if Y == 1:
print('Bingo!')
else:
print('Try again.')
This py3 code always prints 'Try again.' I've tried forcefully setting x to 9 but it doesn't work, can anyone diagnose this? I've made sure it was properly indented in codesculpter3, anyone know why it doesn't work?
There were quite a few errors (see the comments). But in particular, you have used list and input as variables. The code is also appending a list that it is iterating over, which can lead to errors (hint: if you ever do this, then create a new list).
This is a "pythonic" version of the code that would work:
import random
# random list of 5 numbers (0 to 100)
my_list = [random.randint(0,100) for x in range(5)]
got_it = 0 # variable for correct guess
for x in my_list:
y = int(input('Input a whole number from 0 - 100.'))
if y == x:
got_it = 1
print('bingo !')
break
if got_it == 0:
print('try again')
Related
This question already has answers here:
How to append multiple values to a list in Python
(5 answers)
Closed 7 months ago.
Begginer Question, So i have this problem where i receive a lot of inputs in different lines like:
Inputs:
1
2
0
2
1
And i want to sum them or store them in any kind of list to Sum them latter, how can i do this?
I mean, i could store a variable for each one of them like:
a1 = int(input())
a2 = int(input())
ax = int(input())
....
and then
result = a1+a2+ax...
print(result)
but that's not pratical. Someone can explain me on how to store and sum them in a list?
i think that i could do something like this too
x = int(input())
and use
x += x
Just use python lists:
inputlist = []
for i in range(5):
inputlist.append(int(input))
result = sum(inputlist)
Note, I just put a 5 there to ask for 5 values. Ask however many inputs you want.
you could use a while loop, or a for loop for it. If you are provided the number of inputs in advance in a variable x, you can start with a for loop.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
answer = 0
for i in range(x):
answer += int(input())
print("Answer is", answer)
If you do not know the amount of inputs in advance, you can implement a while loop that will take input until a non-integer input is given.
answer = 0
while True:
x = input()
try:
x = int(x) # Tries to convert the input to int
except ValueError: # If an error occurs, ie, the input is not an integer.
break # Breaks the loop and prints the answer
# If all goes fine
answer += x
print("Answer is", answer)
And obviously, we also have a classic alternate to all this, which is to use python list, these can store numbers and we can process them later when printing the answer. Although, I would have to say if the number of input is large, then the most efficient manner is to use either of the above solution due to their memory footprint.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
inputs = []
for i in range(x):
inputs.append(int(input()))
print("Answer is", sum(inputs))
I'm also a beginner, but here's a solution I came up with:
new_list = []
for entry in range(10):
new_list.append(int(input()))
print(sum(new_list))
How can I transfer the list that I take from the user as unknown amount of integers?
f.sum(i[0],i[-1])
def sum(*args):
total=0
for a in args:
total+=a
if a is "q":
break
print(total)
while True:
print("sum")
y = input("Number: ")
if int(y) is 0:
print(i)
f.sum(i[0],i[-1])
break
i.append(int(y))
Can not take unknown amount in f.sum(args) part
Given 2,3,5
Expected: 10
Result: 5
With i[0], i[1]
I think your main problem resides in what you are passing to the function. You are sending the first and last element, but (I think) you want to send the list:
while True:
i = []
print("sum")
y = int(input("Number: "))
if y == 0:
print(i)
print_sum(i)
break
i.append(y)
Also, it doesn't make sense to check in the sum if a value "q", because you are assuming (when you add) they are integers:
# Renamed to "print_sum", since I would expect "sum" to return it, and not print it
def print_sum(*args):
total=0
for a in args:
total+=a
print(total)
Note: I wrote this in the comments initally, but I thought it would be clearer in a comment.
Edit: Do you have to implement your own sum? Python already has one
I am trying to write a program in Python that will take out each bit from a list and add it to a variable.
Example:
x = list(range(0, 11))
y = raw_input("Enter your number: ")
So I want y to add itself to each bit from 0-11.
Why? Let's say I want the a sum of 10 so I wrote in y the number 5, so now I want it to find the correct number in the list that will equal to a sum of 10.
You don't need to build the list at all (in fact, in Python 2.x, range gives you a list already). I think what you want is something like:
target = 10 # set target
y = raw_input("Enter your number: ") # get string input, e.g. '5'
y = int(y) # convert to an actual integer number, e.g. 5
for x in range(1, target+1): # loop through numbers
if x + y == target: # test whether we reached the target
print("Need to add {0} to {1} to get {2}.".format(x, y, target)) # win!
break # stop looping
Although bear in mind that you're simply working out x such that:
x == target - y
which you can calculate directly.
Note that in programming "bit" has a specific meaning; you should refer to the things in lists as "items", "values" or "objects".
i am trying to generate a list consisting of 0's based off of user prompt. if they enter a one then the one index will be replaced with a one, if they enter a two the two index will be replaced with a one, etc. i am able to generate a random list of one's and zero's but i am having trouble with the input.
here is what i have so far:
import random
def askTheUser():
number = input("Do you want to roll again? Pick a number or numbers thru 0 and 5:")
myList = []
aList = [1,0]
for i in range(5):
myList.append(random.choice(aList))
if number == 1:
return myList[1] = 0
if number == 2:
return myList[2] = 0
return myList
print(askTheUser())
I think you are replacing by 0 not 1, also input is taking string not int so try to cast it
and list index is 0 based so the right code should be:
import random
def askTheUser():
number = input("Do you want to roll again? Pick a number or numbers thru 0 and 4:")
myList = []
aList = [1,0]
for i in range(5):
myList.append(random.choice(aList))
myList[int(number)] = 1
return myList
print(askTheUser())
I am not sure what exactly your program should do. I tried to follow description more than your code (expected input and output would be welcome).
Here is my piece:
from __future__ import print_function # make it work also in python 2.x
import random
def askTheUser():
# don't use magic numbers, use 'constant-like' variables
MAX = 5
# try to avoid too long lines if possible
msg = "Do you want to roll again? " +\
"Pick a number or numbers thru 0 and {}: ".format(MAX)
# you should use raw_input() for asking user, input() is very unsafe
number = raw_input(msg)
# initialize with random [0,1]
myList = [random.randint(0,1) for i in range(MAX)]
try:
# you need to convert string to int
i = int(number, 10)
# negative indexes can be valid ;o)
# let's not allow for that in this case, throwing error
if i < 0:
raise IndexError
myList[i] = 1
# you may expect ValueError if string was not valid integer
# or IndexError if it was beyond range (0, MAX)
except (IndexError, ValueError):
print ("That was wrong value:", number) # if you want, message user
pass
finally:
return myList
if __name__ == '__main__':
print(askTheUser())
If you want to accept multiple values at once, you should use split() on input and process them in loop.
Good luck.
I'm very new to Python and I hope for some help or guides by asking here.
Here's the problem:
Write a program that estimates the average number of drawings it takes before the user’s numbers are picked in a lottery that consists of correctly picking six different numbers that are between 1 and 10. To do this, run a loop 1000 times that randomly generates a set of user numbers and simulates drawings until the user’s numbers are drawn. Find the average number of drawings needed over the 1000 times the loop runs.
I tried to create something (below), but I just can't think of how to get those average number. Also it seems the loop is not good. Any help or solution? thank you in advance.
from random import randint
from random import choice #???
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
x = 0
randomlotterylist = []
while not x>1000:
lottery = []
for i in range (6):
lot.append(randint(1,10))
randomlotterylist.append(lottery)
x = x + 1
#Next.. ????
First, you want to know your theoretical average number of drawings, that's (1/10)^6 assuming no repetition allowed. Therefore on average every 1,000,000 tries you'd hit the correct number. That is only if the order matters but I assume in your case the order does not matter, so def your average is less than that...
from random import randint
def number_of_tries_before_hitting_jackpot(user_number):
n_tries = 0
while True:
random_number = set([randint(1,10) for i in range(1,7)])
if user_number == random_number:
return n_tries
else:
n_tries+=1
def ask_user_his_number():
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
return set(userlist)
n_tries_list = []
for x in range(1,1001):
user_number = ask_user_his_number()
print user_number
tmp = number_of_tries_before_hitting_jackpot(user_number)
print tmp
n_tries_list.append(tmp)
avg_number_drawings = reduce(lambda x, y: x + y, n_tries_list) / len(n_tries_list)
print avg_number_drawings
This code is not what I'd do in the sense that the user needs to input its 6 numbers 1,000 times (v annoying for the user). You could change the ask_user_his_number function to a function that just randomly selects a set of 6 numbers.
by using random module, for loop, list in short without defining fuction.
from random import *
user_num=[]
count=0
for i in range(6):
random_num=randint(1,10)
user_num+=[random_num]
user_num.sort()
for j in range(1000):
picked=[]
for k in range(6):
pick_num=randint(1,10)
picked+=[pick_num]
picked.sort()
if picked==user_num:
count+=1
print("the avg darwing is: ",count, count/1000)