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.
Related
//I started learning python 2 weeks ago and right now stack with this problem for a few days. I need somobody to give me a hint or something close to solution. Thank you.Here is my code.
from math import sqrt
# Write your solution here
number = int(input("Please type in a number:"))
while True:
if number > 0:
print(sqrt(number))
break
if number == 0:
print("Invalid number")
break
if number < 0:
print("Exiting...")
break
//Expected output example
Please type in a number: 16
4.0
Please type in a number: 4
2.0
Please type in a number: -3
Invalid number
Please type in a number: 1
1.0
Please type in a number: 0
Exiting..
the first break statement always breaks out of the loop, so you never reach the second (and third if). you may want to indent it to be part of the if statements' bodies:
from math import sqrt
# Write your solution here
number = int(input("Please type in a number:"))
while True:
if number > 0:
print(sqrt(number))
break
if number == 0:
print("Invalid number")
break
if number < 0:
print("Exiting...")
break
Also, if you want to continue the loop until 0 is read, you may want to remove the first two break statements and move the input reading into the function:
from math import sqrt
# Write your solution here
while True:
number = int(input("Please type in a number:"))
if number > 0:
print(sqrt(number))
if number == 0:
print("Invalid number")
if number < 0:
print("Exiting...")
break
The conditions of the if's are mutually exclusive, so only one statement can be entered at a time.
In more complex scenarios, if you only want to enter one if statement, you may want to use elif or continue:
from math import sqrt
# Write your solution here
while True:
number = int(input("Please type in a number:"))
if number > 0:
print(sqrt(number))
continue # continue with next loop iteration, skip anything below
elif number == 0: # only check condition, if first loop condition was false
print("Invalid number")
elif number < 0:
print("Exiting...")
break
EDIT: John Gordon rightfully pointed out, that your cases for exit and invalid number are swapped. To make sure this is a complete solution, I will also incorporate this change:
from math import sqrt
# Write your solution here
while True:
number = int(input("Please type in a number:"))
if number > 0:
print(sqrt(number))
elif number < 0:
print("Invalid number")
elif number == 0:
print("Exiting...")
break
We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')
I have an assignment to create a program where a user guesses a random 5 digit number. What i have works except for one part. When a user enters a number that is longer than 5 digits its just supposed to print this is too long and move on to the next try. For what i have it instead prints the error and stops the game. Is there away that i can fix this?
while not userguess:
uniquedigits_found = 0
tries += 1
guess = str(input("Enter your 5 digit attempt: "))
if len(guess) < 5:
print("this is too short")
elif len(guess) > 5:
print("this is too long")
The solution is simple: just add two continue statements:
if len(guess) < 5:
print("this is too short")
continue
elif len(guess) > 5:
print("this is too long")
continue
These will cause execution to instantly continue on to the next pass through the while loop, skipping over the code that triggers the index error.
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: '))
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..')