I'm looking to create code which requires an integer greater than 2 to be input by a user before continuing. I'm using python 3.3. Here's what I have so far:
def is_integer(x):
try:
int(x)
return False
except ValueError:
print('Please enter an integer above 2')
return True
maximum_number_input = input("Maximum Number: ")
while is_integer(maximum_number_input):
maximum_number_input = input("Maximum Number: ")
print('You have successfully entered a valid number')
What I'm not sure about is how best to put in the condition that the integer must be greater than 2. I've only just started learning python but want to get into good habits.
This should do the job:
def valid_user_input(x):
try:
return int(x) > 2
except ValueError:
return False
maximum_number_input = input("Maximum Number: ")
while valid_user_input(maximum_number_input):
maximum_number_input = input("Maximum Number: ")
print("You have successfully entered a valid number")
Or even shorter:
def valid_user_input():
try:
return int(input("Maximum Number: ")) > 2
except ValueError:
return False
while valid_user_input():
print('You have successfully entered a valid number')
My take:
from itertools import dropwhile
from numbers import Integral
from functools import partial
from ast import literal_eval
def value_if_type(obj, of_type=(Integral,)):
try:
value = literal_eval(obj)
if isinstance(value, of_type):
return value
except ValueError:
return None
inputs = map(partial(value_if_type), iter(lambda: input('Input int > 2'), object()))
gt2 = next(dropwhile(lambda L: L <= 2, inputs))
def take_user_in():
try:
return int(raw_input("Enter a value greater than 2 -> ")) # Taking user input and converting to string
except ValueError as e: # Catching the exception, that possibly, a inconvertible string could be given
print "Please enter a number as" + str(e) + " as a number"
return None
if __name__ == '__main__': # Somethign akin to having a main function in Python
# Structure like a do-whole loop
# func()
# while()
# func()
var = take_user_in() # Taking user data
while not isinstance(var, int) or var < 2: # Making sure that data is an int and more than 2
var = take_user_in() # Taking user input again for invalid input
print "Thank you" # Success
def check_value(some_value):
try:
y = int(some_value)
except ValueError:
return False
return y > 2
Hope this helps
import str
def validate(s):
return str.isdigit(s) and int(s) > 2
str.isdidig() will eliminate all strings containing non-integers, floats ('.') and negatives ('-') (which are less than 2)
int(user_input) confirms that it's an integer greater than 2
returns True if both are True
This verifies that the input is an integer, but does reject values that look like integers (like 3.0):
def is_valid(x):
return isinstance(x,int) and x > 2
x = 0
while not is_valid(x):
# In Python 2.x, use raw_input() instead of input()
x = input("Please enter an integer greater than 2: ")
try:
x = int(x)
except ValueError:
continue
The problem with using the int() built-in shown in other answers is that it will convert float and booleans to integers, so it's not really a check that your argument was an integer.
It's tempting to use the built-in isinstance(value, int) method on its own, but unfortunately, it will return True if passed a boolean. So here's my short and sweet Python 3.7 solution if you want strict type checking:
def is_integer(value):
if isinstance(value, bool):
return False
else:
return isinstance(value, int)
Results:
is_integer(True) --> False
is_integer(False) --> False
is_integer(0.0) --> False
is_integer(0) --> True
is_integer((12)) --> True
is_integer((12,)) --> False
is_integer([0]) --> False
etc...
Related
I have been tasked with reading values inputted by a user(using a while loop) to then store them in a list/array whilst using try: except: to determine if a given input is invalid. In continuation, if the user inputs "done" as a value it will break the loop and print() the total, sum, and average of all the imputed values.
I have gotten this snippet so far:
class Input:
def __init__(self, number_input_value, total_to_be_calculated, main_value):
self.number_input_value = 0
self.total_to_be_calculated = 0.0
self.main_value = input('Enter A Number: ')
self.number_input_value1 = float(self.main_value)
def loop_get_inputs(self):
while True:
self.main_value
if self.main_value == 'done':
break
try :
self.number_input_value1
except :
print('INVAL["VAL"]')
continue
self.number_input_value = self.number_input_value1
self.total_to_be_calculated = self.total_to_be_calculated + self.number_input_value1
print ("Finished successfully!")
print (
self.total_to_be_calculated,
self.number_input_value,
self.total_to_be_calculated/self.number_input_value
)
if __name__ in '__main__':
Input
I have no clue what's wrong, because when it runs it outputs nothing.
Output:
>>>
You need create an instance of the class 'Input' and call the method:
##(self, number_input_value, total_to_be_calculated, main_value)
inp = Input(100, 1000, 10)
#call the method
inp.loop_get_inputs()
Basically:
1 - You have to initialize your class/object before using it.
2 - Having code on the construct is not recommend. You should call a public method of the class to start the "process".
3 - That try-except wasn't doing much. You can, for example, surround the string (from input()) cast to float and print INVALID if the input can't be casted.
4 - You can use += to simplify a = a + b
5 - lower() will convert user input to lowercase, meaning that DONE, done and DoNe (etc) will be considered as "quit" input.
Does this make sense?
class Input:
def __init__(self):
self.number_inputs = 0
self.total = 0.0
def run(self):
self.__get_user_values()
print(f"total: '{self.total}'")
print(f"number_inputs: '{self.number_inputs}'")
print(f"average: '{self.total / self.number_inputs}'")
def __get_user_values(self):
while True:
value = input('Enter A Number: ')
if value.lower() == 'done':
break
if self.__is_valid_input(value):
self.total += float(value)
self.number_inputs += 1
def __is_valid_input(self, value) -> bool:
try:
float(value)
return True
except ValueError:
print('INVAL["VAL"]')
return False
if __name__ in '__main__':
input_wrapper = Input()
input_wrapper.run()
I'm trying to force the user to input a number using try-except in python however it seems to have no effect.
while count>0:
count=count - 1
while (length != 8):
GTIN=input("Please enter a product code ")
length= len(str(GTIN))
if length!= 8:
print("That is not an eight digit number")
count=count + 1
while valid == False:
try:
GTIN/5
valid = True
except ValueError:
print("That is an invalid number")
count=count + 1
Actually, if the user inputs for example a string, "hello"/5 yields a TypeError, not a ValueError, so catch that instead
You could try to make the input value an int int(value), which raises ValueError if it cannot be converted.
Here's a function that should do what you want with some comments:
def get_product_code():
value = ""
while True: # this will be escaped by the return
# get input from user and strip any extra whitespace: " input "
value = raw_input("Please enter a product code ").strip()
#if not value: # escape from input if nothing is entered
# return None
try:
int(value) # test if value is a number
except ValueError: # raised if cannot convert to an int
print("Input value is not a number")
value = ""
else: # an Exception was not raised
if len(value) == 8: # looks like a valid product code!
return value
else:
print("Input is not an eight digit number")
Once defined, call the function to get input from the user
product_code = get_product_code()
You should also be sure to except and handle KeyboardInterrupt anytime you're expecting user input, because they may put in ^C or something else to crash your program.
product code = None # prevent reference before assignment bugs
try:
product_code = get_product_code() # get code from the user
except KeyboardInterrupt: # catch user attempts to quit
print("^C\nInterrupted by user")
if product_code:
pass # do whatever you want with your product code
else:
print("no product code available!")
# perhaps exit here
I created the following python code for an exercise in Python for informatics. The code will run, but will not recognize an input form the user that is larger than 1 as numeric. Any assistance would be appreciated.
def isfloat(string):
try:
float(string)
if float(string) == True:
return True
except ValueError:
return False
user_input = input('Please enter a real number. Type \"done\" to exit and tally your entries \n> ')
data = 0
count = 0
while isfloat(user_input) == True:
data = data + float(user_input)
count = count + 1
user_input = input("Please enter another value \n> ")
isfloat(user_input)
else:
if (isfloat(user_input) == False) and (user_input == "done"):
print("The sum of your entries is: " + str(data))
print("The number of entries was: " + str(count))
exit()
else:
print("The entry was not a numeric value \n")
print("The sum of your valid entries is: " + str(data))
print("The number of valid entries was: " + str(count))
exit()
This is ridiculous:
if float(string) == True:
That's checking if the float converted value is equal to True (which is numerically 1).
Just check for the exception and go:
def isfloat(string):
try:
float(string)
except ValueError:
return False
else:
return True
The problem lies in the fact that float(string) will never return True; it will always return a number of type float or it will raise a ValueError if the input cannot be converted to a float.
To fix this, you'll need to remove your if statement, and simply return True after calling float(string) in your isfloat function. If float(string) raises a ValueError, isfloat returns False as you would expect; otherwise, it will proceed and return True.
def isfloat(string):
try:
float(string)
return True
except ValueError:
return False
The problem is with your isfloat. You shouldn't compare the result of float with True. Instead do something like:
def isfloat(string):
try:
float(string)
return True
except ValueError:
return False
You don't need to actually do anything with the return value of float. If that call doesn't trigger an error -- you have a float, so just return True.
It might be tempting to use the line
if float(string): return True
That would almost work but would misclassify "0"
I'm currently just toying around with defining functions and I'm getting this error. I'm just trying to make an easy function where the user inputs 2 numbers and then it multiplies them together. Also please explain what I'm doing wrong as simply as possible. (I'm a noob)
def userinput():
while True:
try:
number = int(input("Number: "))
break
except ValueError:
print("NOPE...")
def multiply(x,y):
z = x * y
print(z)
while True:
x = userinput()
y = userinput()
multiply(x,y)
again = input("Again? ")
if again == "No" or again == "no":
break
else:
pass
In your function userinput(), you never return number, so python default to return None. Thus, when you pass x and y to multiply(), you are trying to do None * None, hence the error.
return number after the try/except structure in userinput()
If you also want to check for floats, you can do:
while True:
number = input("Number: ")
try:
return int(number)
except ValueError:
try:
return float(number)
except ValueError:
print("NOPE...")
I'm trying to find a way to fix this syntax error. I can't seem to find it to make the program run correctly.
This is my code below
wrong = 0
test = raw_input("Please enter a 4 digit integer:")
def start(test):
if test.isdigit():
if wrong(test)==True:
print 'Invalid input. Four integers must be entered.'
else:
numbers = []
for a in test:
digits.append(a)
a=calc(int(digits[0]))
b=calc(int(digits[1]))
c=calc(int(digits[2]))
d=calc(int(digits[3]))
code = str(c)+str(d)+str(a)+str(b)
print 'The encrypted integer is:',code
else:
print 'You input wrong. Use numbers only.'
def calc(num):
num+=7
num%=10
return num
def error(test):
if len(test)<4 or len(test)>4:
return True
else:
return False
start(test)
AND the fixed is ...
digits = 0
wrong = 0
test = raw_input("Please enter a 4 digit integer:")
def start(test):
if test.isdigit():
if wrong(test)==True:
print 'Invalid input. Four integers must be entered.'
else:
numbers = []
for a in test:
digits.append(a)
a=calc(int(digits[0]))
b=calc(int(digits[1]))
c=calc(int(digits[2]))
d=calc(int(digits[3]))
code = str(c)+str(d)+str(a)+str(b)
print 'The encrypted integer is:',code
else:
print 'You input wrong. Use numbers only.'
def calc(num):
num+=7
num%=10
return num
def wrong(test):
if len(test)<4 or len(test)>4:
return True
else:
return False
start(test)
You've called a function named wrong() but defined a function named error(). Is that the problem you're seeing?
Don't you mean if error(test)? 'wrong' is not a function.