# generate a random number between 1 and 99 sgenrand.randint(1,99) # your code goes here
print("Enter coins that add up to 81 cents, one per line.")
#promp the user to start entering coin values that add up to 81
coin = (sgenrand.randint(1,99))
number1 = ("Enter first coin: ")
sum = 0
number1 = eval(input("Enter first coin: "))
while number1 != coin:
if number1 != coin:
number1 = eval(input("Enter next coin: "))
im stuck in this while loop. I want to have it that the user can hit enter without an answer and breaks out of the loop. after he breaks out, the sum of numbers he previously added is calculated, and if the sum isn't 81. tells the user he didn't reach target value, tells him what value he reached and asks if he wants to start over!
I like doing homework, I really do:
import random as sgenrand
def oneRound():
target = sgenrand.randint(1, 99)
print('Enter coins that add up to {} cents, one per line.'.format(target))
total = int(input('Enter first coin: '))
while True:
s = input('Enter next coin: ')
if not s: break
total += int(s)
if total == target:
print('Well done.')
return True
print('You reached {}.'.format(total))
return input('Do you want to start over? [y/*] ') != 'y'
while not oneRound(): pass
Related
I'm having an issue with my program. I'm working on a program that lets you play a small game of guessing the correct number. The problem is if you guess the correct number it will not print out: "You guessed it correctly". The program will not continue and will stay stuck on the correct number. This only happens if you have to guess multiple times. I've tried changing the else to a break command but it didn't work.
Is there anyone with a suggestion?
This is what I use to test it:
smallest number: 1
biggest number: 10
how many times can u guess: 10
If you try to guess the correct number two or three times (maybe more if u need more guesses) it will not print out you won.
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
#while loop until the guess is the same as the random number
while guess != x:
#this is if u guessed to much u get the error that you've guessed to much
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else: print("\n \nYou Lost, You've guessed", x, "times\n")
break
#this part is not working, only if you guess it at the first time. it should also print this if you guessed it in 3 times
else: print("You guessed it correctly", x)
test = (input("this is just a test if it continues out of the loop "))
print(test)
The main issue is that once guess == x and count < amount you have a while loop running that will never stop, since you don't take new inputs. At that point, you should break out of the loop, which will also conclude the outer loop
You can do it simply by using one while loop as follows:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#this is if u guessed too much u get the error that you've guessed too much
while count <= amount:
guess = int(input("guess the number: "))
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
if guess!=x:
print("\n \nYou Lost, You've guessed", count, "times\n")
As Lukas says, you've kind of created a situation where you get into a loop you can never escape because you don't ask again.
One common pattern you could try is to deliberately make a while loop that will run and run, until you explicitly break out of it (either because the player has guessed too many times, or because they guessed correctly). Also, you can get away with only asking for a guess in one part of your code, inside that while loop, rather than in a few places.
Here's my tweak to your code - one of lots of ways of doing what you want to:
import random
#counts the mistakes
count = 0
#asks to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#asks how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#while loop until the guess is the same as the random number
while True:
if count < amount:
guess = int(input("guess the number: "))
#this is if u guessed to much u get the error that you've guessed to much
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("\n \nYou Lost, You've guessed", x, "times\n")
PS: You got pretty close to making it work, so nice one for getting as far as you did!
This condition is never checked again when the guessed number is correct so the program hangs:
while guess != x:
How about you check for equality as the first condition and break out of the loop if true:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
if guess == x:
print("You guessed it correctly", x)
else:
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("You guessed too many times")
So the code before behaved properly before my "while type(number) is not int:" loop, but now when the user presses 0, instead of generating the sum of the list, it just keeps looping.
Would really appreciate some help with this! Thank you!
List = []
pro = 1
while(pro is not 0):
number = False
while type(number) is not int:
try:
number = int(input("Please enter a number: "))
List.append(number)
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
ans = 0
print(Sum)
Actually, this should keep looping forever for all numbers the user may input, not just zero.
To fix this, you can just add this break condition after (or before, it doesnt really matter) appending:
number = int(input("Please enter a number: "))
List.append(number)
if number == 0:
break
So I got it to work, when written like this:
List = []
pro = 1
while(pro is not 0):
while True:
try:
number = int(input("Please enter a number: "))
List.append(number)
break
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
pro = 0
print(Sum)
But I don't really understand how this is making it only take int values, any clarification would be really helpful, and otherwise thank you all for your help!
I'm guessing that you want to end while loop when user inputs 0.
List = []
pro = 1
while pro is not 0:
try:
number = int(input("Please enter a number: "))
List.append(number)
# This breaks while loop when number == 0
pro = number
except ValueError:
print("Please only enter integer values.")
Sum = 0
for i in List:
Sum += i
print(Sum)
EDIT: I have also cleaned the unnecessary code.
Put if number == 0: inside while type(number) is not int: loop like this:
List = []
while True:
try:
number = int(input("Please enter a number: "))
if number == 0:
Sum = 0
for i in List:
Sum = i + Sum
print(Sum)
break
List.append(number)
except ValueError:
print("Please only enter integer values.")
User types an integer number (smaller than 100, bigger than 0)
If user types 0, the program ends. In case of numbers that are 100 or bigger, or that are -1 or smaller, it shows INVALID, and prompts user to keep entering number.
a = int(input('Enter a number: '))
total =0
keep = True
while keep:
if a ==0:
print('Thanks for playing.. goodbye')
break;
else:
while a>99 or a <0:
print('INVALID')
a = int(input('Enter a number: '))
total = total + a
print(total)
a = int(input('Enter a number: '))
Just putting normal numbers and getting the sum, I enter 0, then it stops, but when I enter 100, INVALID shows up, then I enter 0, the program doesn't end and it keeps showing me INVALID.
Any suggestions will be appreciated. Thanks!
I think this is a more pythonic approach
total =0
while True:
a = int(input('Enter a number: '))
if a == 0:
break
if a>99 or a <0:
print('INVALID')
else:
total = total + a
print(total)
print('Thanks for playing.. goodbye')
When using your code, the result is :
Enter a number: 100
INVALID
Enter a number: 0
0
Enter a number: 0
Thanks for playing.. goodbye
And I think your code may should be:
a = int(input('Enter a number: '))
total =0
keep = True
while keep:
if a ==0:
print('Thanks for playing.. goodbye')
break;
else:
while a>99 or a <0:
print('INVALID')
a = int(input('Enter a number: '))
if a ==0:
print('Thanks for playing.. goodbye')
break;
total = total + a
print(total)
a = int(input('Enter a number: '))
You may procide your requirement more detail.
At your code, the else never breaks the loop so it only sums the total after it has exitted that 2nd loop, but that 2nd one doesn't have a behaviour for 0. You should try to keep it simple with just one loop.
total =0
while True:
a = int(input('Enter a number: '))
if a == 0:
print('Thanks for playing.. goodbye')
break
else:
if a > 99 or a < 0: # You don't need a second while, just an if.
print('INVALID')
else:
total = total + a
print(total)
Identation is key at python, be careful with it.
Also cleaned a bit your code. As example: Since you get into a loop with the while there is no need to use 2-3 different inputs in and out of the loop, just add it once at the beginning inside of the loop.
You are in while loop of else conditional since you entered 100 at first and you can't get out of there unless you enter a number satisfies 0 <= a <= 99. You can make another if statement for a == 0 to exit the while loop just below a = int(input('Enter a number')) of else conditional.
I think it is good to check where you are in while loop using just one print(a). For example, just before if-else conditional or just before while of else conditional. Then, you can check where it gets wrong.
a = int(input('Enter a number: '))
total = 0
keep = True
while keep:
\\ print(a) here to make sure if you are passing here or not.
if a == 0:
print('Thanks for playing.. goodbye')
break;
else:
\\ print(a) here to make sure if you are passing here or not.
while a > 99 or a < 0: \\You are in while loop since you entered 100 at first and you can't get out from here unless you enter a: 0 <= a <= 99.
print('INVALID')
a = int(input('Enter a number: '))
if a == 0:
print('Thanks for playing.. goodbye')
break;
total = total + a
print(total)
a = int(input('Enter a number: '))
I'm working on some homework which requires me to do the following:
Write a program that receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing input. After the user presses the enter key, the program should print the sum of the numbers, the product of the numbers, and the average of the numbers.
Run your program with the following inputs:
1, 2, 3, 4, 5, 6, 7, 8
2, 24, 11, 1, 4, 10
Enter no number
Here is what I have so far, but my numbers are not coming out correctly. Can someone tell me what I'm doing wrong. I'm a beginner so, if you could speak in the simplest terms possible, that would be great.
Take numbers from user until the user presses "Enter"
calculate the sum, product, and average of the numbers entered
display the results
#main program start
def main():
#initialize variables
count = 0
sum = 0.0
product = 1.0
data = input("Enter a number or press Enter to quit: ")
while True:
#request input from user
data = input("Enter a number or press Enter to quit: ")
#set up the termination condition
if data == "":
break
#convert inputs into floats
number = float(data)
#calculate sum, product, and average
sum += number
product *= number
average = sum / number
#display results
print("The sum is", sum)
print("The product is", product)
print("The average is", average)
#main program end
main()
Not sure what you mean the values are wrong. Nothing seems off except the average.
If you want the average, you need a list to collect the values. Try writing your algorithm by hand, and you'll see what I mean.
data = input("Enter a number or press Enter to quit: ")
numbers = []
while True:
#request input from user
data = input("Enter a number or press Enter to quit: ")
#set up the termination condition
if data == "":
break
#convert inputs into floats
numbers.append(float(data))
# these can all be done outside and after the while loop
count = len(numbers)
if count > 0:
_sum = sum(numbers)
product = 1.0
for n in numbers:
product *= n
average = _sum / float(count)
#display results
print("The sum is", _sum)
print("The product is", product)
print("The average is", average)
else:
print("Nothing was entered")
You don't have all the numbers since you are entering the numbers one at a time. It would be best to have the user enter a list like this:
def main():
average = 0
sum_nums = 0
product = 1
nums = []
while True:
data = input("Enter a number or press Enter to quit: ")
if data == ""
sum_nums = sum(nums)
for num in nums:
num *= product
average = sum_nums/len(nums)
print("The sum is {},".format(sum_nums))
print("The product is {}.".format(product))
print("The average is {}.".format(average))
else:
nums.append(data)
continue
It works by entering all the inputs into a list. The only way to exit an input is by using enter so if the input is nothing then it can only be the Enter key. Once the enter key was hit, I got all the values and printed them.
numbers = []
print("enter key to stop")
while(True):
num = input("enter a number :")
if num:
numbers.append(int(num))
elif(num == ''):
break
sum_num =0
for num in numbers:
sum_num += num
avg = sum_num / len(numbers)
print(sum_num)
print(avg)
My assignment is to add up a series of numbers using a loop, and that loop requires the sentinel value of 0 for it to stop. It should then display the total numbers added. So far, my code is:
total = 0
print("Enter a number or 0 to quit: ")
while True:
number = int(input("Enter a number or 0 to quit: "))
print("Enter a number or 0 to quit: ")
if number == 0:
break
total = total + number
print ("The total number is", total)
Yet when I run it, it doesn't print the total number after I enter 0. It just prints "Enter a number or 0 to quit", though it's not an infinite loop.
The main reason your code is not working is because break ends the innermost loop (in this case your while loop) immediately, and thus your lines of code after the break will not be executed.
This can easily be fixed using the methods others have pointed out, but I'd like to suggest changing your while loop's structure a little.
Currently you are using:
while True:
if <condition>:
break
Rather than:
while <opposite condition>:
You might have a reason for this, but it's not visible from the code you've provided us.
If we change your code to use the latter structure, that alone will simplify the program and fix the main problem.
You also print "Enter a number or 0 to quit:" multiple times, which is unnecessary. You can just pass it to the input and that's enough.
total = 0
number = None
while number != 0:
number = int(input("Enter a number or 0 to quit: "))
total += number # Same as: total = total + number
print("The total number is", total)
The only "downside" (just cosmetics) is that we need to define number before the loop.
Also notice that we want to print the total number after the whole loop is finished, thus the print at the end is unindented and will not be executed on every cycle of the while loop.
You should sum the numbers inside the loop even if they aren't zeros, but print the total after the loop is over, not inside it:
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
break
print ("The total number is", total)
If the number is 0, the first thing you are doing is break, which will end the loop.
You're also not adding the number to the total unless it's 0, which is not what you're after.
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
break
print ("The total number is", total)
You were very near, but you had some indentation problem.
Firstly, why all these print statements? I guess you are trying to print it before taking input. For this, the below line will be enough.
number = int(input("Enter a number or 0 to quit: "))
Secondly, differentiate between what you want to do, when only the number==0 and what to do in every iteration.
You want to use the below instruction in every iteration as you want every number to be added with total. So, keep it outside if block.
total = total + number
And when number==0, you first want to print something and then break the loop.
if number == 0:
print ("The total number is", total)
break
Make sure you are adding with total first and then checking the if condition, because once you break the loop, you just can't add the number to total later.
So, the solution could be like that,
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
print ("The total number is", total)
break
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
if number == 0:
break
total = total + number
print("The total number is", total)
If you put break before your other code, then the loop will be ended and your code after that break will not run.
And by the way, you can use try...except to catch the error if user didn't enter a number:
total = 0
while True:
try:
number = int(input("Enter a number or 0 to quit: "))
except ValueError:
print('Please enter a number')
continue
if number == 0:
break
total = total + number
print("The total number is", total)