Limiting user from 0-100 in input function - python

How to create a program that limiting user in input function from 0-100 only. We need to ask user to for their grade in 4 tests after that if the user does not have taken any of those test it shows INC.

while True:
score = float(input('Enter your score: '))
if not 0 <= score <= 100:
continue
else:
break

while True:
score = input('Enter your score: ')
if not (0 <= score <= 100):
continue
else:
break

Related

Store input in a 2-dimensional list - Python 3x - BMI program

I am new to Python just FYI. I am taking input as patients name, patient ID number, height, and weight which I have functional code for calculating their Body Mass Index. The user can continue storing input until they "quit" or enter a negative value for patientID.
Problem: I also need to store these inputs in a 2-dimensional list (list of lists) then be able to out put a report of all patients names followed by their BMI number, plus state the category (obese, underweight etc) that I already calculated. Below is all my code that works so far (although not pretty):
# Give the user input options.
print("\nWelcome to patient entry. What would you like to do?")
# Set an initial value for choice other than the value for 'quit'.
choice = ''
# Start a loop that runs until the user enters the value for 'quit'.
while choice != 'q':
# Give all the choices in a series of print statements.
print("\n[1] Enter Patient Info.")
print("[q] Enter q to quit.")
# Ask for the user's choice.
choice = input("\nWhat would you like to do? ")
# Respond to the user's choice.
if choice == '1':
patient_name = (input("Enter patient name: "))
patient_id = int(input("Enter patient ID number: "))
while True:
height = int(input("Enter your height in inches: "))
try:
val = int(height)
if val < 0: # if not a positive, ask for input again
print("Sorry, input has to be a positive number, try again")
break
except ValueError:
print("That's not an number!")
while True:
weight = int(input("Enter your weight in pounds: "))
try:
val = int(weight)
if val < 0: # if not a positive int, ask for input again
print("Sorry, input has to be a positive number, try again")
continue
break
except ValueError:
print("That's not an number!")
# CDC formulat--https://www.cdc.gov/nccdphp/dnpao/growthcharts/training/bmiage/page5_2.html
BMI = ((float(weight) / float(height) ** 2) * 703)
# print(f"Your BMI is {BMI}")
print("Your BMI is: {0} and you are: ".format(round(BMI, 2)), end='')
# conditions
if (BMI < 16):
print("severely underweight")
elif (BMI >= 16 and BMI < 18.5):
print("underweight")
elif (BMI >= 18.5 and BMI < 25):
print("Healthy")
elif (BMI >= 25 and BMI < 30):
print("overweight")
elif (BMI >= 30):
print("severely overweight")
elif choice == 'q':
print("\nThanks for playing. See you later.\n")
exit()
else:
print("\nI don't understand that choice, please try again.\n")
patient_name = (input("Enter patient name: "))
patient_id = int(input("Enter patient ID number: "))
while True:
height = int(input("Enter your height in inches: "))
try:
val = int(height)
if val < 0: # if not a positive, ask for input again
print("Sorry, input has to be a positive number, try again")
continue
break
except ValueError:
print("That's not an number!")
while True:
weight = int(input("Enter your weight in pounds: "))
try:
val = int(weight)
if val < 0: # if not a positive int, ask for input again
print("Sorry, input has to be a positive number, try again")
continue
break
except ValueError:
print("That's not an number!")
First, you need to create a list in which you can add other lists containing patient data.
myList = []
Now, once you have taken all the required inputs for a single patient in 1 iteration of a loop, its time to create a new list (sub-array). I also noticed that you need category as well but after your calculation, you are only printing it. So, create a variable and store it as well.
subList = [patient_name, patient_id, height, weight] #add remaining values as well
Finally, add the subList to the myList to create a 2 dimensional list like this:
myList.append(subList)
To iterate over this 2-d list, you can do something list this:
for patientData in myList:
print(patientData)

Two while loops that run simultaneously

I am trying to get the first while True loop to ask a question. If answered with a 'y' for yes, it continues to the second while test_score != 999: loop. If anything other than a y is entered, it should stop.
Once the second while loop runs, the user enters their test scores and enters 'end' when they are finished and the code executes, the first "while True" loop should ask if the user would like to enter another set of test scores. If 'y' is entered, then it completes the process all over again. I know the second one is a nested while loop. However, I have indented it, in PyCharm, per python indentation rules and it still tells me I have indentation errors and would not run the program. That is the reason they are both lined up underneath each other, below. With that said, when I run it as it is listed below, it gives the following answer:
Enter test scores
Enter end to end the input
==========================
Get entries for another set of scores? y
Enter your information below
Get entries for another set of scores? n
((When I type in 'n' for no, it shows the following:))
Thank you for using the Test Scores application. Goodbye!
Enter test score: 80 (I entered this as the input)
Enter test score: 80 (I entered this as the input)
Enter test score: end (I entered this to stop the program)
==========================
Total score: 160
Average score: 80
When I answered 'y', it started a continual loop. When I answered 'n', it did give the print statement. However, it also allowed me to enter in my test scores, input end and execute the program. But, it also did not ask the user if they wanted to enter a new set of test scores. Any suggestions on where I am going wrong?
print("The Test Scores application")
print()
print("Enter test scores")
print("Enter end to end input")
print("======================")
# initialize variables
counter = 0
score_total = 0
test_score = 0
while True:
get_entries = input("Get entries for another set of scores? ")
if get_entries == 'n':
print("Thank you for using the Test Scores application. Goodbye!")
break
else:
print("Enter your information below")
continue
counter = 0
score_total = 0
test_score = 0
while test_score != 999:
test_score = input("Enter test score: ")
if test_score == 'end':
break
elif (int(test_score) >= 0) and (int(test_score) <= 100):
score_total += int(test_score)
counter += 1
elif test_score == 999:
break
else:
print("Test score must be from 0 through 100. Score discarded. Try again.")
# calculate average score
average_score = round(score_total / counter)
# format and display the result
print("======================")
print("Total Score:", score_total,
"\nAverage Score:", average_score)
The while loops should be nested to have recurring entries
print("The Test Scores application")
print()
print("Enter test scores")
print("Enter end to end input")
print("======================")
# initialize variables
counter = 0
score_total = 0
test_score = 0
while True:
get_entries = input("Get entries for another set of scores? ")
if get_entries == 'n':
print("Thank you for using the Test Scores application. Goodbye!")
break
else:
print("Enter your information below")
counter = 0
score_total = 0
test_score = 0
while test_score != 999:
test_score = input("Enter test a score: ")
if test_score == 'end':
break
elif (int(test_score) >= 0) and (int(test_score) <= 100):
score_total += int(test_score)
counter += 1
elif test_score == 999:
break
else:
print("Test score must be from 0 through 100. Score discarded. Try again.")
# calculate average score
average_score = round(score_total / counter)
# format and display the result
print("======================")
print("Total Score:", score_total,
"\nAverage Score:", average_score)
Output:
The Test Scores application
Enter test scores
Enter end to end input
======================
Get entries for another set of scores? y
Enter your information below
Enter test a score: 60
Enter test a score: 80
Enter test a score: 90
Enter test a score: 70
Enter test a score: end
======================
Total Score: 300
Average Score: 75
Get entries for another set of scores? y
Enter your information below
Enter test a score: 80
Enter test a score: 80
Enter test a score: end
======================
Total Score: 160
Average Score: 80
Get entries for another set of scores? n
Thank you for using the Test Scores application. Goodbye!

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.

Python, simple calculation

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: '))

Python help (computer guess number)

I'm learning how to program in Python and I found 2 tasks that should be pretty simple, but the second one is very hard for me.
Basically, I need to make a program where computer guesses my number. So I enter a number and then the computer tries to guess it. Everytime it picks a number I need to enter Lower or Higher. I don't know how to do this. Could anyone advise me on how to do it?
For example (number is 5):
computer asks 10?
I write Lower
computer asks 4?
I write Higher
Program:
I already made a program which automatically says Higher or Lower but I want to input Lower or Higher as a user.
from random import randit
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
You may want to put in a case for if it doesn't match you input, also I think you need a case for when the guess finally equals the number, you may want to allow an input for "Found it!" or something like that.
from random import randint
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
answer = str(input("Higher/Lower? "))
if answer == 'Higher':
min = guess
elif answer == 'Lower':
max = guess
attempts += 1
print("I needed", attempts, "attempts")
from random import randit
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
number = int(input("Number? "))
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
problem is your using a loop but inputting value once at start of app . just bring input inside the while statement hope this help
from random import randint
print('choos a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla computer wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
from random import *
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
attemps =0
guess = randint(min,max)
while guess != number:
userInput=input(str(guess)+"?")
if userInput.lower()=="lower":
max=guess
elif userInput.lower()=="higher":
min=guess
attemps += 1
guess = randint(min,max)
print("I needed", attemps, "attempts to guess ur number ="+str(guess))
output:
Number? 5
66?lower
63?lower
24?lower
19?lower
18?lower
10?lower
4?higher
9?lower
6?lower
4?higher
I needed 10 attempts to guess ur number =5

Categories