How to debug my input/while loop in Python - python

I've been trying to work with this while loop so I ask for the user input, specifically a number between 99 and 1000. I've been trying to make it so that if your input is within those perimeters, it continues, and if it's not within those perimeters, the input question repeats until it receives a valid input.
while True:
try: #lttr = level two top range
lttr = int(input('Enter a triple digit number between 100 and 1000: '))
if lttr in range(99,1000):
continue
if lttr not in range(99,1000):
break
except:
print("That's not a valid option!")

Related

Fixing While Loops Python

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 cannot get my program to stop repeating my first statement

Python just keeps repeating back to me "How many random numbers do you want?" and won't move on to the next input.
I've tried most things I could think of.
do_program = True
while(do_program):
while(True):
try:
number_of_numbers = float(input("How many random numbers do you want?"))
if(number_of_numbers < 0):
print("Negative numbers are not allowed.")
continue
except ValueError:
print("The value you entered is invalid. Please enter numerial values only.")
else:
break
while(True):
try:
lowest_number = float(input("What is the lowest random number you want?"))
if(lowest_number < 0):
print("Negative numbers are not allowed.")
continue
except ValueError:
print("The value you entered is invalid. Please enter numerial values only.")
else:
break
while(True):
try:
highest_number = float(input("What is the highest random number you want?"))
if(highest < 0):
print("Negative numbers are not allowed.")
continue
except ValueError:
print("The value you entered is invalid. Please enter numerial values only.")
else:
break
import random
print("The numbers were written to randomnum.txt.")
def main():
for count in range(number_of_numbers):
number = random.randint(lowest_number, highest_number)
print(number)
main()
Right now I just want to focus on getting to my second and third input statements.
After successfully reading number_of_numbers the code breaks out of the inner while(True) loop and then resumes the outer while(do_program) loop. This causes the same code to be executed over and over. Perhaps rework your code to process the input before returning to the main loop?

Break a for loop that is prompting input to list?

I'm trying to make a simple program that accepts input of 'sales amounts' individually for each day of the week then totals the values and displays them.
I have a loop that accepts 7 inputs, but I would like the user to be able to enter 'q' to break the loop if they have less than 7 inputs.
Here's what I have:
sales = []
for i in range(0, 7):
sales.append(input("> "))
if 'q':
break
It is giving me a NameError, but I've tried a variety of things.
I've done if sales/input/raw_input == "q":.
I've also set q equal to a variable, but that terminated my loop after one iteration.
store the input in a variable so you can reuse it without requiring the user to re-enter the value
user_input = input("> ")
if user_input == "q":
break
sales.append(user_input)

how to limit input in while loop need serious looking into

how can i limit the input for srj imbetween 1 and 0 and it just restarts the whole program
def gen0(): # input all the initial data
while True: # this will loop infinitely if needed
try: # this will try to take a float from the user
j=int(input('how many juveniles are there in generation 0? '))
srj=float(input('what is the survival rate of juveniles '))
break # if the user gives a number then break the loop
except ValueError: #if the user does not give a number then the user will be told to retry
print("Sorry, there was an error. Please enter a positive number")
Since you are breaking within a try/except, you can simple raise a ValueError if the data is incorrect.
if srj > 1.0 or srj < 0.0:
raise ValueError
put the if statement if srj > 1 or srj < 0:gen0() before the break line
:^)

How to repeat getting user's input and keep track of it?

I have a question about input loops and keeping track of it.
I need to make a program that will keep track of all the grades of a class. The thing is that the class size varies every semester, so there is no fixed number assigned to the number of students.
The program will stop taking input when a student enters a grade of -1.
while True:
grade = int(input("Test: "))
if grade < 0:
break
How can I make it so that it keeps track of every single input?
You could use a list comp with iter and get the user to enter -1 to end the loop:
grades = [int(grade) for grade in iter(lambda:input("Enter grade or -1 to exit: "), "-1")]
iter takes a sentinel that will break the loop when entered, so as soon as the user enters -1 the loop will end.
When taking input and casting you should really use a try/except to validate what the users inputs:
grades = []
while True:
try:
grade = int(input(""Enter grade or -1 to exit: ""))
except ValueError:
# user entered bad input
# so print message and ask again
print("Not a valid grade")
continue
if grade == -1:
break
grades.append(grade) # input was valid and not -1 so append it
grades = [] # initialize an empty list
while True:
grade = int(input("Test: "))
if grade < 0:
break
else:
grades.append(grade) # add valid values to the list

Categories