Validating int numbers in a certain range. Python-3.x [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am making this game where the user has to choose from 5 options. So, he must type any number from 1 to 5 to choose an option. Now here is the problem I am facing, I just can't figure out a way in which the user cannot type in any other character except the int numbers from 1 to 5, and if he does type in a wrong character, how should I show his error and make him type in the input again? Here is what I've tried:
def validateOpt(v):
try:
x = int(v)
if int(v)<=0:
x=validateOpt(input("Please enter a valid number: "))
elif int(v)>5:
x=validateOpt(input("Please enter a valid number: "))
return x
except:
x=validateOpt(input("Please enter a valid number: "))
return x
Here validateOpt is to validate the number for the option, i.e., 1,2,3,4,5. It works fine, but whenever I type 33,22, 55, or any other int number from 1 to 5 twice (not thrice or even four times, but only twice), it doesn't show any error and moves on, and that, I suppose, is wrong. I am just a beginner.

You can do this with a while loop, something like this should be a good start:
def getValidInt(prompt, mini, maxi):
# Go forever if necessary, return will stop
while True:
# Output the prompt without newline.
print(prompt, end="")
# Get line input, try convert to int, make None if invalid.
try:
intVal = int(input())
except ValueError:
intVal = None
# If valid and within range, return it.
if intVal is not None and intVal >= mini and intVal <= maxi:
return intVal
Then call it with something like:
numOneToFive = getValidInt("Enter a number, 1 to 5 inclusive: ", 1, 5)

use a while loop instead of recursion, you can check the user data and return if its valid, although you might want to consider a break out clause should the user want to exit or quit without a valid input.
def get_input(minimum, maximum):
while True:
try:
x = int(input(f"please enter a valid number from {minimum} to {maximum}: "))
if minimum <= x <= maximum:
return x
except ValueError as ve:
print("Thats not a valid input")
value = get_input(1, 5)

Use for loop in the range between 1 and 5

Try this code, it will keep prompting user till he enters 5, note that this may cause stackoverflow if recursion is too deep:
def f():
x = input("Enter an integer between 1 and 5:")
try:
x = int(x)
if x<=0 or x>5:
f()
except:
f()
f()

Related

How To Keep Trying New Inputs in Try and Except Format [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 months ago.
I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to keep trying until they guess it right.
Right now, my code only allows the user to input one ValueError. I don't want this, I want to keep inputting until I guess the number. Attached is my code. Any help is greatly appreciated!
ex:
I want to input errors ("a", 4.20, "hello") and still have them count as guesses until I guess the number
"a" > 4.20 > "hello" > 26 => Guessed it in 3 tries
def guess(n):
secret_number = 26
if n < secret_number:
return print("Too low!")
elif n > secret_number:
return print("Too high!")
def try_exp():
try:
n = int(input("What is your guess? "))
return n
except ValueError:
n = int(input("Bad input! Try again: "))
return n
def counter():
print("Guess the secret number! Hint: it's an integer between 1 and 100... ")
n = try_exp()
i = 0
while n != 26:
guess(n)
i += 1
n = try_exp()
print(f"You guessed it! It took you {i} guesses.")
counter()
Instead of making try_exp like that, you can use a while loop that will first ask for input, and if the input is valid, then it will break out of the while loop. This is one way to implement it:
def try_exp():
first_input = True
while True:
try:
if first_input:
n = int(input("What is your guess? "))
return n
else:
n = int(input("Bad input! Try again: "))
return n
except ValueError:
first_input = False
In this, we go through an infinite loop, and we have a flag that designates whether it is the first guess or if they have already guessed before. If it is the first guess, we ask them for input, and if it is the second guess, we tell them that they gave incorrect input and ask for more input. After receiving correct input, the function returns n. If the input is incorrect which is when it is not an integer, we set first_input as false. Then, the while loop loops again. It will keep on waiting for input until they submit an integer.

How do I sum numbers from user input in python?(only if they are even numbers)

I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")

Does While loop ends when the program return value?

I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!

Python User input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm writing a game that prompts the user to input the number of rows. The problem I'm having is how do I get the program to keep prompting the user until they enters a whole number. If the user enters a letter or a float such as 2.5, the int value will not work, and thus I cannot break out of the loop. The program crashes. The int is essential so that I can check the number. The input must be even, it must be greater then or equal to 4 and less then equal to 16. Thanks!
def row_getter()->int:
while True:
rows=int(input('Please specify the number of rows:'))
if (rows%2 == 0 and rows>=4 and rows<=16):
return rows
break
You're on the right path, but you want to use a try/except block to try and convert the input to an integer. If it fails (or if the input is not in the given bounds), you want to continue and keep asking for input.
def row_getter()->int:
while True:
try:
rows=int(input('Please specify the number of rows:'))
except ValueError:
continue
else: # this runs when the input is successfully converted
if (rows % 2 == 0 and >= 4 and rows <= 16):
return rows
# if the condition is not met, the function does not return and
# so it continues the loop
I guess the pythonic way to do it would be:
while True:
try:
rows = int(input('Please specify the number of rows:'))
except ValueError:
print("Oops! Not an int...")
continue
# now if you got here, rows is a proper int and can be used
This idiom is called Easier to Ask Forgiveness than Permission (EAFP).
Could also make isint helper function for reuse to avoid the try/except in main parts of code:
def isint(s):
try:
int(s)
return True
except ValueError:
return False
def row_getter()->int:
while True:
s = input('Please specify the number of rows:')
if isint(s):
rows = int(s)
if (rows % 2 == 0 and rows >= 4 and rows <= 16):
return rows

Python user must only enter float numbers

I am trying to find out how to make it so the user [only enters numbers <0] and [no letters] allowed. Can someone show me how I would set this up. I have tried to set up try/catch blocks but I keep getting errors.
edgeone = input("Enter the first edge of the triangle: ")
I think you want numbers only > 0, or do you want less than zero? Anyway to do this you can using try/except, inside a while loop.
For Python 3, which I think you are using?
goodnumber = False
while not goodnumber:
try:
edgeone = int(input('Enter the first edge of the triangle:'))
if edgeone > 0:
print('thats a good number, thanks')
goodnumber = True
else:
print('thats not a number greater than 0, try again please')
except ValueError:
print('Thats not a number, try again please')
hope this helps.
you must use except handler for this case :
try:
value = int(raw_input("Enter your number:"))
if not ( value < 0 ):
raise ValueError()
except ValueError:
print "you must enter a number <0 "
else:
print value #or something else
Also This question already has an answer here: Accepting only numbers as input in Python
You can do like this.
i = 1
while(type(i)!=float):
i=input("enter no.")
try:
int(i):
except:
try:
i = float(i)
except:
pass
print(i)

Categories

Resources