Loop printing output multiple times - python

I created a random lottery number generator for COP1000 that passes a random number 0-9 to an array of 7 integers. However, when I print the array, I get the same output 7 times. It may be a problem with one of the loops but I am unsure of where it is coming from. Any help would be greatly appreciated.
Here is the code:
import random
print("Seven lucky numbers; are you ready?")
numbers = [0,0,0,0,0,0,0]
index = 0
while index<len(numbers):
numbers[index] = random.randint(0,9)
index = index + 1
for n in numbers:
print("\nYour random lottery number is:")
print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6])

With this:
for n in numbers:
print("\nYour random lottery number is:")
print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6])
You are printing the entire list in a loop. Either loop over the list or print the whole thing, but don't do both. The easiest way to solve this and produce your desired output is to replace the above code with the following:
print("\nYour random lottery number is:")
print(*numbers)

As stated by TigerhawkT3 it seems you are confused with how to print out the values once you have pushed them into your array. (Also you would not want to put the initial print statement inside the loop unless you want it to print for every item in the list)
This link shows how to use for loops in different capacities. One way to solve your problem would be:
print("\nYour random lottery numbers are:")
for n in numbers:
print n
If you want to loop through and print out each value with some kind of string in front of all or 1 item you can use:
print("\nYour random lottery numbers are:")
for index in range(len(numbers)):
if index == len(numbers) - 1:
print "power number: ", numbers[index]
else:
print index, ' : ', numbers[index]
Lastly if you are just trying to print all the numbers with a delimiter in one print statement then seems like this maybe a duplicate of this question or this one where the solution was:
print("\nYour random lottery numbers are:")
print ', '.join(map(str, numbers))

Related

how do i keep track of how many times a number is rolled?

I am not sure how to do a school assignment. I am pretty new to python and for this project, i need to have the user input a number and have the dice roll that amount of times. but i also need to keep track of how many times each number is rolled. i have found something that i would find very helpful, but im not sure how i should do it in python. I've never used java or any other program besides python. im just not sure where to start. Any help is appreciated!
Thanks!!
link to what i have found that would come in handy:
Dice roll array and method calling
You're going to need to keep count for six different numbers. Many data structures can accommodate this. For instance, a list would work. Let's say you have a function roll() that returns a random integer between 1 and 6 inclusive. Then you could use something like this:
count = [0, 0, 0, 0, 0, 0]
rolls = 100
i = 1
while i <= rolls:
r = roll()
count[r-1] = count[r-1]+1
i = i + 1
print(count)
What this is doing is creating a list called count with six elements, representing the number of times each number on the dice has been rolled. We then run a loop for the number of times you want to throw the dice. Each time the loop is run, a random integer is generated and stored in r. For example, say on one iteration of the loop, the random integer generated is 2. Then the count[1] is incremented (note it's count[1] and not count[2] because the list is indexed from 0 to 5). Once the loop is over you can print your list, which will show how many times each number came up.
A place that I would start would be importing the random module to get random integers from 1-6 since they are on a standard dice.
import random
Now take the user input:
number = input('Enter the amount of rolls ')
You need to create a loop that runs the amount of times that the user picked, which turns out to be a quite simple "for" loop. Next, we need to create two random integers between 1 and 6 twice each time. The roll will be equal to those two random numbers added together:
for i in range(int(number)):
first = random.randint(1,6)
second = random.randint(1,6)
roll = first + second
Now, we have to keep track of each number and how many times it was rolled. The possibilities are the numbers 2 through 12. To check the count of these numbers, I would add all of the rolls to a list and then do the list.count to check each number. The code should end up being something like this:
import random
number = input('Enter the amount of rolls ')
all = []
for i in range(int(number)):
first = random.randint(1,6)
second = random.randint(1,6)
roll = first + second
all.append(roll)
for i in range(2,13):
count = all.count(i)
print(str(i) + ' appeared ' + str(count) + ' times!')
Hope this helped. I'm kind of new too so I'm in the same place as you.
To answer the question in the title, the simplest way is with a Counter. Create it at the start:
from collections import Counter
count = Counter()
Then each time you roll a die, add to the count :
result = roll()
count[result] += 1
Then at the end, you have your totals. Say for example we rolled 3 ones and 2 sixes:
print(count) # -> Counter({1: 3, 6: 2})

Python - How to sort through my list

Basically all I'm trying to do is get the list to sort and display in different ways. But it seems after I do the first print it will get "TypeError: 'int' object is not callable". I'm assuming that's because I'm at the end of the list and need to restart at the beginning? Not sure how to do that or if that's the reason.
##vars
Index = 0
NumSize = 0
NumInput = 0
ManNum = 0
##Asking for list size
NumSize = int(input("How many numbers would you like to enter?:\n====>"))
##Declaring list
Numbers = [0] * NumSize
##Collecting data
for Index in range(NumSize):
NumInput = int(input("Please enter a number:\n====>"))
Numbers[Index] = NumInput
##Getting highest number
MaxNum = max(Numbers)
##Printing list
print("::::The numbers you entered were::::")
for Numbers in Numbers:
print(Numbers)
##Sorting list small to large
Numbers.sort()
print("::::The numbers while sorted::::")
for Numbers in Numbers:
print(Numbers)
##Sorting list large to small
Numbers.reverse()
print("::::The numbers reversed::::")
for Numbers in Numbers:
print(Numbers)
##Printing largest number
print("::::Largest number::::\n",
MaxNum)
You use
for Numbers in Numbers:
print(Numbers)
You should not name your iterating variable the same name as your collection
try this
for number in Numbers:
print(number)
do not call the iterator with the same name as the collection, as you overwrite the later
for Numbers in Numbers:
this destroys "Numbers" array and after the loop "Numbers" is the last element of "Numbers" instead. Change all loops to
for number in Numbers:
Use anything instead of Numbers in your for loop,
so that
for i in Numbers:`
dosomething
If you print Numbers then you will see that it just carry last number you inserted in the list.
print Numbers
>>> #last Number of List
Use a different variable than Numbers in your loops. You can also use sorted(Numbers) and reversed(Numbers) to reduce the amount of variable assignments you have to do. If you don't plan to reuse MaxNum, you can do that directly in the print as well.
Here is the fully updated program:
##vars
Index = 0
NumSize = 0
NumInput = 0
##Asking for list size
NumSize = int(input("How many numbers would you like to enter?:\n====>"))
##Declaring list
Numbers = [0] * NumSize
##Collecting data
for Index in range(NumSize):
NumInput = int(input("Please enter a number:\n====>"))
Numbers[Index] = NumInput
##Printing list
print("::::The numbers you entered were::::")
for number in Numbers:
print(number)
##Sorting list small to large
print("::::The numbers while sorted::::")
for number in sorted(Numbers):
print(number)
##Sorting list large to small
print("::::The numbers reversed::::")
for number in reversed(Numbers):
print(number)
##Printing largest number
print("::::Largest number::::")
print max(Numbers)
The answer is already given above. But for the explanation purpose here is what is going wrong.
>>> Numbers = [1, 4 , 10, 8] #This is creating a list.
>>> for Numbers in Numbers: #Now when you are iterating it definately gives the result
... print(Numbers)
...
1
4
10
8
>>> Numbers #But now check what is in Numbers
8
>>>
You didn't wanted the above.
Note: >>> is the python interpretor prompt
As mentioned in the comment, please start writing code in pythonic way.
Which is:
You do not need to initialize variables like you did. You just need to assign them before you use them.
When you ask for the inputs. you do need to go do list[index] instead you could use append method.

Finding numbers that are multiples of and divisors of 2 user inputted numbers

I have an assignment for Python to take 2 user inputted numbers (making sure the 1st number is smaller than the second) and to find numbers that are multiples of the first, and divisors of the second.. I'm only allowed to use a while loop (new condition my teacher added today..) I've done it with a for loop:
N_small = int(input("Enter the first number: "))
N_big = int(input("Enter the second number: "))
numbers = ""
if N_small > N_big:
print("The first number should be smaller. Their value will be swapped.")
N_small, N_big = N_big, N_small
for x in range(N_small, N_big+1, N_small):
if N_big % x == 0:
numbers += str(x) + " "
print("The numbers are: ", numbers)
I'm not asking for the answer to how to do this with a while loop - but I just need a hint or two to figure out how to start doing this... Can anyone enlighten me?
Thanks
You can convert any for loop into a while loop trivially. Here's what a for loop means:
for element in iterable:
stuff(element)
iterator = iter(iterable)
while True:
try:
element = next(iterator)
except StopIteration:
break
stuff(element)
Of course that's not what your teacher is asking for here, but think about how it works. It's iterating all of the values in range(N_small, N_big+1, N_small). You need some way to get those values—ideally without iterating them, just with basic math.
So, what are those values? They're N_small, then N_small+N_small, then N_small+N_small+N_small, and so on, up until you reach or exceed N_big+1. So, how could you generate those numbers without an iterable?
Start with this:
element = N_small
while element ???: # until you reach or exceed N_big+1
stuff(element)
element ??? # how do you increase element each time?
Just fill in the ??? parts. Then look out for where you could have an off-by-one error that makes you do one loop too many, or one too few, and how you'd write tests for that. Then write those tests. And then, assuming you passed the tests (possibly after fixing a mistake), you're done.
You don't have to iterate over all the numbers, only the multiples...
small, big = 4, 400
times = 1
while times < big / small:
num = times * small
if big % num == 0: print(num)
times += 1

How to compare inputted numbers without storing them in list

Note: This is not my homework. Python is not taught in my college so i am doing it my myself from MITOCW.
So far i have covered while loop, input & print
Q) Write a program that asks the to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered it should print a message to the effect
How can i compare those 10 number without storing them in some list or something else? Coz i haven't covered that as if yet.
print "Enter 10 numbers: "
countingnumber=10
while countingnumber<=10:
number=raw_input():
if number % 2 == 0:
print "This is odd"
countingnumber=countingnumber+1
else:
print "This is even. Enter the odd number again"
i think the program will look something like this. But this has some unknown error & How can i compare all the numbers to get the largest odd number without storing those 10 numbers in the list.
print "Enter 10 numbers: "
countingNumber = 1
maxNumber = 0
while countingNumber<=10:
number=int(raw_input())
if (number % 2 == 0):
countingNumber = countingNumber+1
if (maxNumber < number):
maxNumber = number
else:
print "This is even. Enter the odd number again"
print "The max odd number is:", maxNumber
you can just define a maxnum variable and save the max in it! also you must use int(raw_input()) instead raw_input()
print "Enter 10 numbers: "
maxnum=0
for i in range(10):
number=int(raw_input())
if number%2 == 0:
print "This is odd"
if number>maxnum:
maxnum=number
else:
print "This is even. Enter the odd number again"
print "max odd is :{0}".format(maxnum)
DEMO:
Enter 10 numbers:
2
This is odd
4
This is odd
6
This is odd
8
This is odd
12
This is odd
14
This is odd
16
This is odd
100
This is odd
2
This is odd
4
This is odd
max odd is :100
Whenever I do input, I like to make sure I don't leave room for human error giving me bugs.
Because I put in extra checks I break code into a lot of separate function. This also gives code the quality of being non-coupled. ie) You can reuse it in other programs!!
def input_number():
while true:
input = raw_input("Enter Value: ")
if not input.isdigit():
print("Please enter numbers only!")
else:
return int(input)
Designing the input function in this fashion gives the code no opportunity to crash. We can now use it in a function to get odd numbers!
def input_odd_number():
while true:
input = input_number()
if input % 2 == 0:
print("Please enter odd numbers only!")
else:
return input
Now we can finally move onto the main code. We know we need ten numbers so lets make a for loop. We also now we need to hold onto the largest odd number, so lets make a variable to hold that value
def largest_odd(count = 10): // its always nice to make variables dynamic. The default is 10, but you can change it when calling!
max_odd = input_odd_number() // get the first odd number
for i in range(count - 1): // we already found the first one, so we need 1 less
new_odd = input_odd_number()
if new_odd > max_odd:
max_odd = new_odd
print("The largest odd value in '{}' inputs was: {}".format(count, max_odd)
In your solution are multiple flaws.
A syntax error: The colon in number=raw_input():.
raw_input returns a string and you have to cast it to an int.
Your while loop just runs one time, because you start with 10 and compare 10 <= 10. On the next iteration it will be 11 <= 10 and finishes.
Also you have mixed odd an even. even_number % 2 gives 0 and odd_number % 2 gives 1.
To get the biggest value you only need a additional variable to store it (See biggest_number in my solution). Just test if this variable is smaller then the entered.
You ask again if the number is odd, but you should take every number and test only against odd numbers.
A working solution is:
print "Enter 10 numbers"
count = 0
max_numbers = 10
biggest_number = None
while count < max_numbers:
number=int(raw_input("Enter number {0}/{1}: ".format(count + 1, max_numbers)))
if number % 2 == 1:
if biggest_number is None or number > biggest_number:
biggest_number = number
count += 1
if biggest_number is None:
print "You don't entered a odd number"
else:
print "The biggest odd number is {0}".format(biggest_number)
If you wonder what the format is doing after the string take a look in the docs. In short: It replaces {0} with the first statement in format, {1} with the second and so on.
here is the correct code for that:
print "Enter 10 numbers: "
countingnumber=1
MAX=-1
while countingnumber<=10:
number=int(raw_input())
if number%2==1:
if number>MAX:
MAX=number
if MAX==-1:
print "There Weren't Any Odd Numbers"
else:
print MAX
here are some notes about your errors:
1- you should cast the raw input into integer using int() function and the column after calling a function is not needed and therefor a syntax error
2- your while loop only iterates once because you initial counting number is 10 and after one iteration it would be bigger than 10 and the while body will be skipped.
3-an even number is a number that has no reminder when divided by 2 but you wrote it exactly opposite.
4- you don't need to print anything in the while loop, you should either print the biggest odd number or print "There Weren't Any Odd Numbers".
5- an additional variable is needed for saving the maximum odd number which is MAX.
Last note: in the code provided above you can combine the two ifs in the while loop in to one loop using 'and' but since you said you are a beginner I wrote it that way.

How do i order the numbers a user inputs?

I am basically wondering how i can store the users inputs and put them in order from least to greatest to help them find median mode or range.
from __future__ import division
amtnum = 0
sumofnums = 0
print "Hello, This program will help find the mean of as many numbers as you want."
useramtnum = input("How many numbers will you need to enter: ")#asks user to say how many numbers there are
while amtnum < useramtnum: #Tells program that while the amount of numbers is less than the users input amt of numbers to run.
amtnum = amtnum + 1 #Tells that each time program asks for number add one to amt of numbers
entnum = (int(raw_input("Enter a number:"))) #Asks user for number
sumofnums = entnum + sumofnums #Adds users number to all values
print "The amount of your numbers added up were:", sumofnums
print "The average/mean of your numbers were:", (sumofnums/useramtnum)
put 'em in a list and sort it
mylist = []
while ...
mylist.append(entnum)
mylist.sort()
print mylist
Utilize the basic data structure called a list!
Before your while loop, create a list (aka array)
user_input_list = []
After you get the individual number from the user in the while loop, add the input to the list (in the while loop)
user_input_list.append(entnum)
After the while loop, sort the list (it will sort in place)
user_input_list.sort()
Then the list has every input from the user in sorted order, least to greatest.
To access the last item in the list, use array accessors.
user_input_list[-1]
To access median, utilize the fact you can use the length of the list. Access the length(list)/2 item
user_input_list[int( len(user_input_list) / 2)] #int cast used to remove decimal points
I am by no means a Python expert (as in, this is like my third python program), but I think it's generally easier to call functions, be it in Python or in any other language. It makes code more readable.
These are all basic math functions, so I don't feel I deprived you of knowledge by just writing them. I did, however, leave the range function for you to write. (Since mylist is sorted, I'm sure you can figure it out.)
This allows the user to continually enter numbers and have the mean, median, and mode spit back at them. It doesn't handle non-integer input.
from collections import Counter
from decimal import *
def getMode(l):
data = Counter(l)
mode = data.most_common(1)
print "mode:", mode
def getMean(l):
length = len(l)
total = 0
for x in l:
total = total + x
mean = Decimal(total) / Decimal(length)
print "mean:", mean
def getMedian(l):
median = 0
length = len(l)
if (length % 2 == 0):
median = (l[length/2] + l[length/2 - 1])/2.0
else:
median = l[length/2]
print "median:", median
mylist = []
print "Enter numbers to continually find the mean, median, and mode"
while True:
number = int(raw_input("Enter a number:"))
mylist.append(number)
mylist.sort()
getMean(mylist)
getMedian(mylist)
getMode(mylist)
Solution to solve your problem :
Use a list : More on Lists
Example :
numbers = []
while amount < counter:
...
numbers.append(num)
print sorted(numbers)
You can take a look at modification of your code below.
numbers = []
print "Hello, This program will help find the \
mean of as many numbers as you want."
while True:
try:
counter = input("How many numbers will you need to enter: ")
except:
print "You haven't entered a number."
else:
break
amount = 0
while amount < counter:
try:
num = input("Enter a number: ")
except:
print "You haven't entered a number."
else:
amount += 1
numbers.append(num)
print "The amount of your numbers added up were:", (sum(numbers))
print "The average/mean of your numbers were:", ( (sum(numbers)) / counter)
print "My list not in order:", numbers
print "My list in order:", sorted(numbers)

Categories