Sum Numbers Input - python

I'm working on a simple python script that when run allows for an input of a number, then asks if another number input is wanted, if yes, the input entry is displayed, this is repeated until the answer is no when asked if another number input is needed.
Once "no" is entered, I need to sum all the numbers that were input and output it.
This part I have working, however, the issue I am facing is when the question is asked if another input is needed, if there is anything other than "Y"/"YES"/"N"/"NO" an error is displayed, in the summed output the error count is also being included and I can't quite figure out how to exclude the errors.
Here's the script:
total = 0
num = 1
while num > 0:
if num > 0:
total = total + num
cont = input("Would you like to enter another number: ").upper()
if cont == "Y" or cont == "YES":
float(input("Please enter number: \n"))
continue
if cont == "N" or cont == "NO":
print("The total of the numbers is", total)
break
if cont != "N" and cont != "NO" and cont != "Y" and cont != "YES":
print("Invalid response. Please enter Y or N")
continue

There's a lot going on here, but I've tried to refactor your code a bit to help you understand:
# Set up total:
total = 0
# Keep asking for numbers until we answer 'NO':
while True:
# Ask user if they want to continue
cont = input("Would you like to enter another number: ").upper()
# If yes, get a number and add it to the total
if cont == "Y" or cont == "YES":
num = float(input("Please enter number: \n"))
total += num
# If no, print the total and break out of the while loop
elif cont == "N" or cont == "NO":
print("The total of the numbers is", total)
break
# Otherwise, try again.
else:
print("Invalid response. Please enter Y or N")

Related

Why won't my input statements accept values in my program?

I am making a program that generates a random number and asks you to guess the number out of the range 1-100. Once you put in a number, it will generate a response based on the number. In this case, it is Too high, Too low, Correct, or Quit too soon if the input is 0, which ends the program(simplified, but basically the same thing).
It counts the number of attempts based on how many times you had to do the input function, and it uses a while loop to keep asking for the number until you get it correct. (btw, yes I realize this part is a copy of my other question. This is a different problem in the same program, so I started it the same way.)
Anyways, I am having an issue with the last part of the program not taking any values. It is supposed to take the input for keep_playing and continue going if it is equal to 'y'. The issue is that it isn't actually making the variable equal anything(at least I don't think so.) So, whatever value I put in, it just prints the same response every time. Here is the small part of the code which isn't working, though I feel like it is something wrong with the rest of the code:
def keep_playing(attempts,keep_playing):
keep_playing = 'y'
if keep_playing == 'y':
guess(attempts)
keep_playing = str(input("Another game (y to continue)? "))
else:
print()
print("Thanks for playing")
return keep_playing
The expected output is:
Enter a number between 1 and 100, or 0 to quit: 4
Too low, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 67
Too high, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 66
Congratulations! You guessed the right number!
There were 2 attempts
Another game (y to continue)? y
Enter a number between 1 and 100, or 0 to quit: 0
You quit too early
The number was 79
Another game (y to continue)? n
Thanks for playing!
But the actual output is:
Enter a number between 1 and 100, or 0 to quit: 4
Too low, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 67
Too high, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 66
Congratulations! You guessed the right number!
There were 2 attempts
Another game (y to continue)? y
Enter a number between 1 and 100, or 0 to quit: 0
You quit too early
The number was 79
Another game (y to continue)? n
Another game (y to continue)? y
>>>
Notice how no matter what I do, it continues to run. The first part with the higher and lower works fine, however the bottom part just seems to break, and I don't know how to fix it. If anyone has any solutions that would be greatly appreciated.
Also, in case anyone wanted to see the whole thing, in case there was in issue with that, here it is:
import random
def main():
global attempts
attempts = 0
guess(attempts)
keep_playing(attempts,keep_playing)
def guess(attempts):
number = random.randint(1,100)
print('')
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
while guess != 0:
if guess != number:
if guess < number:
print("Too low, try again It's",number, "for testing purposes") #printing the number makes it easier to fix :/
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again It's",number, "for testing purposes")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
else:
print()
print("Congratulations! You guessed the right number!")
print("There were", attempts,"attempts")
print()
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing
else:
print()
print("You quit too early")
print("The number was ",number)
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing
def keep_playing(attempts,keep_playing):
keep_playing = 'y'
if keep_playing == 'y':
guess(attempts)
keep_playing = str(input("Another game (y to continue)? "))
else:
print()
print("Thanks for playing")
return keep_playing
main()
I notice a couple things here
There is some issue with the naming of your function, python thinks that keep_playing is the str variable keep_playing and not the function. In my code below I will rename the function keep_playing to keep_playing_game.
You need to pass in the parameters when you call the function keep_playing_game so the function knows what the user input and attempts are.
Why are you setting keep_playing = 'y' in the first line of your function def keep_playing_game(attempts,keep_playing)? If you remove this line, your program should run as expected based on the value the user enters and not what the function assigns keep_playing to.
I would recommend trying something like this
import random
def main():
global attempts
attempts = 0
guess(attempts)
# keep_playing(attempts,keep_playing) -> this line should be removed
def guess(attempts):
number = random.randint(1,100)
print('')
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
while guess != 0:
if guess != number:
if guess < number:
print("Too low, try again It's",number, "for testing purposes") #printing the number makes it easier to fix :/
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again It's",number, "for testing purposes")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
else:
print()
print("Congratulations! You guessed the right number!")
print("There were", attempts,"attempts")
print()
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing_game(keep_playing, attempts)
else:
print()
print("You quit too early")
print("The number was ",number)
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing_game(keep_playing, attempts)
def keep_playing_game(keep_playing, attempts):
if keep_playing == 'y':
guess(attempts)
else:
print()
print("Thanks for playing")
return
return None
main()

Loop from the start of the code until the user says stop in Python

This is the question my teacher at school has given us:
Write a Python program to accept the value of an integer N and display all the factors of N. Repeat the above for multiple integers using a user-controlled loop.
I'm not having any trouble with the main part of the code, however i don't understand how to loop it properly so that the code runs through the beginning again till the user says N at the end when prompted.
This is my code:
#this is the main part of the code
def print_factors(x):
print("The factors of",x,"are: ")
for i in range(1,x+1):
if x%i==0:
print(i)
#this is the error handling part of the code
while True:
try:
n=int(input("Please enter a number: "))
except ValueError:
print("Please enter a valid number.")
continue
else:
break
print_factors(n)
#this is the looping part where i am having trouble
N = input("Do you want to continue to find factors Y/N: ").upper()
while True:
while N not in 'YN':
if N == 'Y':
print_factors(int(input("Enter a number: ")))
elif N == 'N':
break
else:
print("Invalid input, please try again.")
N = input("Do you want to continue to find factors Y/N: ").upper()
print_factors(int(input("Enter a number: ")))
I want the code to go back to the start and ask for input again, and then ask if the user wants to continue and so on. But when I got to the end, the loop shows these results:
Do you want to continue to find factors Y/N: e
Invalid input, please try again.
Do you want to continue to find factors Y/N: y
Enter a number: 42
The factors of 42 are:
1
2
3
6
7
14
21
42
If I type something other than y, then it also works, and ends after looping only once. I want it to loop endlessly till the user gives the command to stop with a 'y' or 'Y' input and show an error message in all other cases.
I solve your problem by moving your inner while loop into the else case. Also, in the if statement N == 'Y', I insert one more N = input(...) command:
N = input("Do you want to continue to find factors Y/N: ").upper()
while True:
if N == 'Y':
print_factors(int(input("Enter a number: ")))
N = input("Do you want to continue to find factors Y/N: ").upper()
elif N == 'N':
break
else:
while N not in 'YN':
print("Invalid input, please try again.")
N = input("Do you want to continue to find factors Y/N: ").upper()
Result:
Please enter a number: 15
The factors of 15 are:
1
3
5
15
Do you want to continue to find factors Y/N: y
Enter a number: 23
The factors of 23 are:
1
23
Do you want to continue to find factors Y/N: e
Invalid input, please try again.
Do you want to continue to find factors Y/N: y
Enter a number: 32
The factors of 32 are:
1
2
4
8
16
32
Do you want to continue to find factors Y/N: n
>>>
Side note: running on Python 3.9.1, Window 10.
Maybe you would want to include the same try-catch block into the user-controlled while loop.

I need help on a python guessing game

I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")

basic looping in Python

New to this so please bear with me. I'm trying to run a loop that asks the user to input a number between 1 and 100. I want to make it to where if they enter a number outside of 100 it asks again. I was able to do so but I can't figure out if I'm using the correct loop. Also whenever I do get inbetween 1 and 100 the loop continues.
code below:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
else:
while user_input > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
I think the clearest way to do this is to start with a loop that you break out of when you finally get the right answer. Be sure to handle a bad input like "fubar" that isn't an integer
while True:
try:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
break
print("Not between 1 and 100, try again")
except ValueError:
print("Not a number, try again")
In python 3 you can use range to do bounds checking. If you do
if user_input in range(1, 101)
range will calculate the result without actually generating all of the numbers.
When your code is run, it will continue to ask for an input, even if the input given is less than 100. One way to fix this would be to do this:
try_again = 1000
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
elif user_input > 100:
while try_again > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
This code first tests if the user's input is more than 100, then runs a while statement in which the base value is more than 100. When the user inputs another value, if it is over 100, it continues, otherwise it does not.
Below is an example of a program that gets you the output that you are seeking:
attempts = 0
while True:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input > 100 or user_input < 1:
print('Please try again')
attempts += 1
continue
elif attempts >= 1 and user_input <= 100 and user_input >= 1:
print('There you go!')
break
else:
print('Nice!')
break
Start by putting your prompt for the user within the loop so that the user can be asked the same prompt if the fail to enter a number between 1 and 100 the first time. If the user input is greater than 100 or less than 1, we will tell the user to try again, we will add 1 to attempts and we will add a continue statement which starts the code again at the top of the while loop. Next we add an elif statement. If they've already attempted the prompt and failed (attempts >= 1) and if the new input is less than or equal to 100 AND the user input is also greater than or equal to 1, then the user will get the 'There you go' message that you assigned to them. Then we will break out of the loop with a break statement in order to avoid an infinite loop. Lastly we add an else statement. If the user satisfies the prior conditions on the first attempt, we will print 'Nice' and simply break out of the loop.

How to add a loop to my python guessing game?

So I am very new to python as I spend most of my time using HTML and CSS. I am creating a small project to help me practice which is a number guessing game:
guess_number = (800)
guess = int(input('Please enter the correct number in order to win: '))
if guess != guess_number:
print('Incorrect number, you have 2 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print('Incorrect number, you have 1 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print()
print('Sorry you reached the maximum number of tries, please try again...')
else:
print('That is correct...')
elif guess == guess_number:
print('That is correct...')
So my code currently works, when run, but I would prefer it if it looped instead of me having to put multiple if and else statements which makes the coding big chunky. I know there are about a million other questions and examples that are similar but I need a solution that follows my coding below.
Thanks.
Have a counter that holds the number of additionally allowed answers:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + str(tries_left if tries_left > 0 else 'no') + ' more attempts..')
If you don't know how many times you need to loop beforehand, use a while loop.
correct_guess = False
while not correct_guess:
# get user input, set correct_guess as appropriate
If you do know how many times (or have an upper bound), use a for loop.
n_guesses = 3
correct_guess = False
for guess_num in range(n_guesses):
# set correct_guess as appropriate
if correct_guess:
# terminate the loop
print("You win!")
break
else:
# if the for loop does not break, the else block will run
print("Out of guesses!")
You will get an error, TypeError: Can't convert 'int' object to str implicitly if you go with the answer you have selected. Add str() to convert the tries left to a string. See below:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + (str(tries_left) if tries_left > 0 else 'no') + ' more attempts..')

Categories