Adding Sums in Python - python

I have to make a code where user inputs numbers of which the sum will add up to 1001. But it can't go over that amount or it resets back to zero. The only issue I'm having is getting it so the code will print a "Congratulations" message when the user gets to 1001. This is my code so far.
I'm new to Python and would appreciate any help offered!
EDIT
So far I have this and it's working for adding the sums.
print ("Want to play a game? Add numbers until you reach 1001!")
print ("Current total is 0!")
total=0
while total < 1001:
store=raw_input("Enter a number!")
num=int(store)
total=total+num
print total
print ("Congratulations! You won!")
The only problem I've having now is that the user can enter numbers over 1001 and still get the congratulations message.
should I put something like
if total > 1001:
print ("Oops! Too Far! Start Again!")

In your case, you have while 1001 > 0, which is always true, so you get an infinite loop. Additionally, while 1001 == sum will also produce an infinite loop, considering that once you get there, you are never changing sum. The following is a simplified and fixed version of your code:
#sum is a function, so name it something else, I chose sum_ for simplicity's sake
while sum_ != 1001:
#instead of using an intermediate, I just combined the two lines
num=int(raw_input("Enter a number!"))
#This is equivalent to sum = sum + num
sum_ += num
print sum_
#Need to reset if sum_ goes above 1001
if sum_ > 1001:
sum_ = 0
#By the time you get here, you know that _sum is equal to 1001
print ("Congratulations! You won!")

Both of your while-loops will run forever since their conditions will always evaluate to True (actually, you will never even get to the second because the first will run forever).
Here is a fixed version of your script:
print "Want to play a game? Add numbers until you reach 1001!"
print "Current total is 0!"
# Don't name a variable `sum` -- it overrides the built-in
total = 0
# This will loop until `total` equals 1001
while total != 1001:
store = raw_input("Enter a number!")
num = int(store)
# This is the same as `total=total+num`
total += num
print total
# If we have gone over 1001, reset `total` to 0
if total > 1001:
print "Oops! Too Far! Start Again!"
total = 0
# When we get here, the total will be 1001
print "Congratulations! You won!"

Related

Python psychic guessing game repeats 10 times

I want it so it will randomly generate a number between 1-10 and the user will input their guess. It will then output if it is right or wrong, after 10 rounds it will tell them how psychic they are. I have done most of it but I cannot get it to randomly generate 10 numbers instead it generates 1 number and you can just input that number and get it correct every time if you find that number
import random
score=0
random=(random.randint(1,10))
for index in range(10):
guess=int(input("Choose a number between 1 and 10:"))
if random==guess:
score+=1
print ("Correct, Next")
else:
print ("Incorrect, Next")
if score==10:
print("Final score:Super mystic")
elif score>=7:
print("Final score:Good")
elif score>=5:
print ("Final score:You need more practice")
else:
print ("Final score:Dont become a psychic")
You need to put the random=(random.randint(1,10)) inside the for loop for it to change with every loop:
for index in range(10):
random=(random.randint(1,10))
guess=int(input("Choose a number between 1 and 10:"))
Then the rest of the code

Running into issues with looping the calculation of # of digits in a number

My assignment requires me to take in an input, determine how many digits are in said input, then spit it back out. we are not allowed to use string conversion in order to determine the length of the input. I've managed to get that to work properly. My issue is that I'm supposed to have it repeat in a loop until a sentinel is reached. Here's my code so far.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = 1
final = 0
num = int(input("Enter a number: "))
while num != 0:
num = num //10
count += 1
print("There are", count, "digits in", num)
I'm also seeming to have trouble with having my input integer print properly, but it might just be my ignorance there. I've cut out what my attempts at looping it were, as they all seemed to just break the code even more. Any help is welcome, even criticism! Thank you in advance!
Firstly, that is a strange way to get the digits in the number. There's no need to modify the actual number. Just cast the int back to a string and get the length (don't just keep the original string, it could have spaces or something in it which would throw off the count). That is the number of digits.
Secondly, you can do all the work in the loop. There's no need for setup variables, incrementing, a second loop, or anything like that. The key insight is the loop should run forever until you break out of it, so you can just use "while True:" for the loop, and break if the user inputs "0".
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
def find_digits(num):
count = 0
while num != 0:
num = num //10
count += 1
return count
count += 1
# loop forever
while True:
# hang onto the original input
text_input = input("Enter a number: ")
# cast to int - this will throw an exception if the input isn't int-able
# you may want to catch that
num = int(text_input)
# the number of digits is the length of the int as a string
num_digits = find_digits(num)
if num == 0:
print("Goodbye.")
# "break" manually ends the loop
break
# if we got to this point, they didn't input 0 and the input was a number, so
# print our response
print(f"There are {num_digits} digits in {num}.")
The problem with printing the input integer correctly is, that you first save it in the num variable and then constantly change it in your while loop. So the original input is lost of course and in the end it always prints the 0, that ends up in num after the while loop finishes.
You can easily fix it, by saving the input value to another variable, that you don't touch in the loop.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = int(input("Enter a number: "))
numcopy = num
while numcopy != 0:
numcopy = numcopy // 10
count += 1
print("There are", count, "digits in", num)
Counting is better done with Python builtin functions.
len(str(num))
will give you number of digits in your number.

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

How do I check if a value is in a list and then have a variable storing the score increase by 10 each time

I have created the following code, but would like the score to increase each time that I is in Y, and then display the increased score, allowing the user to enter their guess 8 times.
Y = ["Treasure", "Hi", "Hey", "whoops", "OK", "Hello"]
count=0
while count<9:
I = str(input("Enter your guess"))
if I in Y:
score=+10
print('Your score is:',score)
else:
print("I don't understand")
Two main issues with your current code:
You don't set an initial value for score prior to entering the loop.
You use =+ instead of += to try and increment the score.
This makes an unfortunate combination of mistakes, because score = +10 does not throw an error while score += 10 (the correct way) would have given NameError. See the changes below. Beyond that, you then get an infinite loop by not incrementing the count on each loop.
Y = ["Treasure", "Hi", "Hey", "whoops", "OK", "Hello"]
count=0
score = 0 # Set an initial score of 0, before the loop
while count<9:
I = str(input("Enter your guess"))
if I in Y:
score =+ 10 # Change to += to increment the score, otherwise it's always 10
print('Your score is:',score)
else:
print("I don't understand")
count += 1
One thing that is needed to complete the logic is to increment the count by 1 at the end. The incremental operator is += and not =+. Another thing is the variable score will need to be initialized at the start. So the final code with comments about the missing parts is shown below.
Y = ["Treasure", "Hi", "Hey", "whoops", "OK", "Hello"]
count = 0
score = 0 # initialize the score
while count<9:
I = str(input("Enter your guess: "))
if I in Y:
score+=10 # increment the score
print('Your score is: %s' % score)
else:
print("I don't understand")
count += 1 # increment the count
Your while loop is an infinite loop. Incrementing count by 1 will make it a definite loop. Also, initialize the score variable to zero. That should work things out.

Am I allowing 3 guesses or 2?

I am learning Python on Codecademy, and I am supposed to give the user 3 guesses before showing "you lose". I think my code allows 3 entries, but the website shows "Oops, try again! Did you allow the user 3 guesses, or did you incorrectly detect a correct guess?" unless the user guesses correctly within 3 trials. Can someone tell me what's wrong?
from random import randrange
random_number = randrange(1, 10)
count = 0
# Start your game!
guess= int(raw_input("Please type your number here:"))
while count < 2:
if guess==random_number:
print "You win!"
break
else:
guess=int(raw_input("Please guess again:"))
count+=1
else:
print "You lose!"
print random_number
Your loop will indeed ask the user for three guesses. (As can be trivially seen by running the code—ignore those other answers telling you to change the loop condition, that's the wrong solution.)
The problem with your loop is a more subtle one: because of the way it's structured, the third guess is never tested! You can see this by setting random_number to a constant and guessing wrong twice, then right on the last try; you still lose.
Your best bet is to use a more straightforward loop structure, where the asking and the checking happens in the same iteration of the loop.
for attempt in xrange(3):
guess = int(raw_input("Please enter a number: "))
if guess == random_number:
print "You win!"
break
print "Wrong! Try again."
else:
print "You lose! The number was", random_number
If you want a different prompt on the second and subsequent guesses, try this:
prompt = "Please enter a number"
for attempt in xrange(3):
guess = int(raw_input(prompt + ": "))
if guess == random_number:
print "You win!"
break
prompt = "Wrong! Try again"
else:
print "You lose! The number was", random_number
You need while count <= 2. Your count starts at 0. Then it goes through the body of your loop once. Then it gets incremented to 1. Then it goes through your loop body another time. Finally, once it increments to 2, your while condition evaluates to false, and the loop body doesn't execute a third time.
Be careful with corner cases when you're setting up conditions. :)
The condition should be:
while count < 3:
To make it easier to understand, I suggest you start the counter in count = 1 and write the condition like this:
while count <= 3:
Now it's more clear that exactly 3 repetitions are allowed. But let's see why your code was wrong:
count starts at 0, and it's true that 0 < 2, so we enter the loop
At the first failed attempt, count gets incremented to 1, and it's true that 1 < 2 so we enter the loop once more
At the second failed attempt, count gets incremented to 2, and it's no longer true that 2 < 2 so we exit the loop
So you see, only two attempts were being considered.

Categories