Python user must only enter float numbers - python

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)

Related

Counting down the user inputs

Basic python learning:
I am asked to write a program that makes a list of 15 integer entries (size) the user inputs. For each input, the program should give the number of integers remaining to input. In the end, the program should list the 15 entries, and tell the user he is done.
With the code below, I get the list and the final report, but can't really figure out how to count down, print the remaining entries, and tell the user he is done.
my_list = []
for _ in range(15):
try:
my_list.append(int(input('Enter size: ')))
except ValueError:
print('The provided value must be an integer')
print(my_list)
One thing to figure out is "what to do if the user inputs something that is not a valid integer?" You can solve that by keeping asking the user for an input until it's a valid number.
You can do that using a while loop with a boolean variable:
good_int = False
while not good_int:
try:
num = int(input(f'Enter an integer: '))
good_int = True
except ValueError:
print('I said int, gorramit!!')
Now that we have that, there is a lot of approaches you can take here.
One of the interesting things a for loop can do is count backwards.
You can try:
my_list = []
for i in range(15, 0, -1):
good_int = False
while not good_int:
try:
my_list.append(int(input(f'Enter size for iteration {i}: ')))
good_int = True
except ValueError:
print('The provided value must be an integer')
print("Aight, you're done. This is the list:")
print(my_list)
Or... probably what is better, use a variable to store the number of tries (15) and don't consider a "valid try" until the user inputted a valid integer.
my_list = []
tries = 15
while tries > 0:
try:
my_list.append(int(input(f'Enter size for iteration {tries}: ')))
tries = tries - 1 # Or just tries -= 1
except ValueError:
print('The provided value must be an integer')
print("Aight, you're done. This is the list:")
print(my_list)
Since you don't want the loop to repeat a fixed number of times, but instead need it to repeat until you have 15 values, you should consider using a while instead of a for.
my_list = []
while len(my_list) < 15:
try:
my_list.append(int(input('Enter size: ')))
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')
It may be a good idea to inform the user how many values they still have to enter:
my_list = []
while len(my_list) < 15:
try:
my_list.append(int(input(f'Enter size ({15 - len(my_list)} left): ')))
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')
You're going to need to use a counter variable, which simply keeps track of the amount of numbers left for the program to receive. You will print it out after every input, and then subtract 1 from the variable. I added a check to make sure that we don't print out "You have to input 0 more numbers" since that isn't what we really want to do.
my_list = []
numbers_left = 15
for _ in range(15):
try:
my_list.append(int(input('Enter size: ')))
numbers_left = numbers_left - 1
if numbers_left != 0:
print("You have to input " + str(numbers_left) + " numbers to complete the program.")
except ValueError:
print('The provided value must be an integer')
print(my_list)
You can print with f strings and the deincrement the number for each for loop. I am not sure about the try and for loop isn't this better?
EDIT: Changed the for loop and gives errors on string vals.
my_list=[]
len_val=15
val=0
while val<len_val:
try:
my_list.append(int(input("Enter size:")))
val+=1
print(f"{(len_val-val)}to go!")
except ValueError:
print("Enter an integer")
print(len(my_list))
range(14, 0, -1) will do the job for you.
my_list = []
for i in range(14, 0, -1):
try:
my_list.append(int(input('Enter size: ')))
print(f'{i} to go')
except ValueError:
print('The provided value must be an integer')
print(my_list)
If you have ValueError during the execution. I would suggest using a while loop. Like this
my_list = []
size = 15
while len(my_list) < size:
try:
my_list.append(int(input(f'Enter size : ')))
print(f'{size-len(my_list)} to go')
except ValueError:
print('The provided value must be an integer')
print(f'You are done: {my_list}')

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

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()

exception handling mistake

So I have a condition for accepting only a negative value for a variable and it should also not raise a value error.
My code goes like this ->
try:
x = int(input("Enter -ve value : "))
while x >= 0:
print("Error wrong value!")
x = int(input("Enter -ve value : " )
except ValueError:
print("Error wrong value!")
x = int(input("Enter -ve value : "))
while x >= 0:
print("Error wrong value!")
x=int(input("Enter -ve value : " )
The only problem with this approach is that, suppose I press enter without entering a value for the first time. It takes me to the "except" condition and it works fine but if I enter a blank value again my code stops because of value error. How do I stop this from happening? Is there a more efficient way of writing this code without importing any modules?
Thank you for your time and efforts! I wrote this question on the mobile app so sorry if it causes any inconvenience!
You could try it like this:
x = 0
while x >= 0:
try:
x = int(input("Enter -ve value : "))
except ValueError:
print("Error wrong value!")
x = 0
This will achieve what you are asking for in that it will keep prompting you to enter a number while x >= 0 and will also ensure the exception handling is always carried out on each input too.

Python3: creating error for input of negative

Taking an intro course and need to create an over/under guessing game. I want to fine-tune my user inputs by creating an error if someone inputs a negative or non-integer. I have the non-integer error reporting correctly, and the negative loops back correctly, but the negative will not print my error message.
#Number of plays
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
except ValueError:
print ("Integer numbers only please.")
except:
if x <=0:
print ("Positive numbers only please.")
i = get_plays("\nHow many times would you like to play?")
print ("The game will play " +str(i)+" times.")
Separately, if I wanted to use a similar setup to produce an error for any negative non-integer number between 1 and 20, how would this look?
Try:
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
if x <=0:
print("Positive numbers only please.")
continue
if x not in range(20):
print("Enter a number between 1 - 20.")
continue
return x
except ValueError:
print("Integer numbers only please.")
It will accept only positive numbers between 1 to 20
The problem is this section
except:
if x <=0:
Empty except clauses trigger on any error that hasn't been caught yet, but negative numbers don't trigger an exception. You want something like this instead. Notice that in the try clause we can just proceed as if x is an int already, because we can assume that no ValueError was thrown.
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
if x <=0:
print ("Positive numbers only please.")
else:
return x
except ValueError:
print ("Integer numbers only please.")

Is there a better way to check if input is digit? input could be int or float

Wondering if there is a better way to do this. Python is my first programming language.
while True:
amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ')
# seperate dollars and cents.
amount_list = amount_per_month.split(".")
# checking if int(str) is digit
if len(amount_list) == 1 and amount_list[0].isdigit() == True:
break
# checking if float(str) is digit
elif len(amount_list) == 2 and amount_list[0].isdigit() and amount_list[1].isdigit() == True:
break
else:
raw_input('Only enter digits 0 - 9. Press Enter to try again.')
continue
Just try to make it a float and handle the exception thrown if it can't be converted.
try:
amount_per_month = float( raw_input('What is the monthly cost?') )
except (ValueError, TypeError) as e:
pass # wasn't valid
TypeError is redundant here, but if the conversion was operating on other Python objects (not just strings), then it would be required to catch things like float( [1, 2, 3] ).
You could try casting the input to a float, and catching the exception if the input is invalid:
amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ')
try:
amt = float(amount_per_month)
except ValueError:
raw_input('Only enter digits 0 - 9. Press Enter to try again.')
use regex
r'\d+.\d+|\d+'
http://docs.python.org/library/re.html

Categories

Resources