I'm very new to python, in fact, to programming in general. I'm trying to do a program that compares three numbers and determines which one is smaller. I got the code done, but now i need to make it only accept numbers, and still running when it finds a literal value. For example, code will be ok if you put any number, but when you type a string value it crashes. here is the code
num1=0;
num2=0;
num3=0;
num1=int((raw_input("Type below the first number \n")));
num2=int((raw_input("Type below the second number\n")));
num3=int((raw_input("Type below the third number \n")));
if (num1<num2) and (num1<num3):
print "%i is the smallest number of all three"% num1;
elif (num2<num1) and (num2<num3):
print "%i is the smallest number of all three"% num2;
elif (num3<num2) and (num3<num1):
print "%i is the smallest number of all three"% num3;
elif (num1==num2) or (num1==num3) or (num2==num3):
print "Two equal numbers have been written.";
A simple while loop. You may put this in a function.
while True:
try:
num1=int((raw_input("Type below the first number \n")))
break
except ValueError: # catch the *specific* exception
print("Enter numbers only")
Read more on exceptions:
Handling Exceptions in Python
The most important point is probably to separate concerns, ie. keeping user input separate from validation. You've gotten a couple of good solutions using exceptions. Here is a solution that manually validates the input:
def is_int(strval):
"""A string represents an int if all characters are digits.
Returns True if strval represents a valid int, otherwise False.
"""
for ch in strval:
if not ch.isdigit(): # if '0' <= ch <= '9':
return False
return True
def read_int(prompt='Type number: '):
"""Read one integer from user.
"""
while True:
val = raw_input(prompt)
if is_int(val):
return int(val, 10) # the 10 is the radix (base)
else:
print 'That is not a number.., try again'
numbers = []
for pos in 'first', 'second', 'third':
numbers.append(read_int('Type %s number: ' % pos))
to use the exception handling code, all you have to do is change is_int:
def is_int(strval):
try:
int(strval, 10)
except ValueError:
# int() raised an exception, so strval is not an int
return False
else:
# int() didn't raise an exception, so it is an int
return True
it is also possible to be a bit more concise when finding the smallest:
def smallest(a, b, c):
if b > a < c: # if a is less than both b and c..
return a
if a > b < c:
return b
if a > c < b:
return c
return "Error: two of the numbers must be equal!"
you can call it like so:
smallest(numbers[0], numbers[1], numbers[2])
but Python has a shorthand that does exactly that which looks like:
smallest(*numbers)
def getNumber(i):
try:
num = int(raw_input("type in number %s : " %i))
return num
except Exception as e:
print('This is not a valid number')
return getNumber(i)
numbers = []
for i in range(1,4):
numbers.append(getNumber(i))
print(numbers)
You can simply add the input getting code in try except block and handle the ValueError exception with some meaningful code.
try:
num1=int((raw_input("Type below the first number \n")));
num2=int((raw_input("Type below the second number\n")));
num3=int((raw_input("Type below the third number \n")));
except ValueError:
print "Please enter integer only."
exit(-1)
Related
I want to write a function that checks if a syntax is correct. The part of the syntax I struggle with is this one:
< number >: := 2 | 3 | ...
I have defined it as:
def number(q):
letter = q.dequeue()
if int(letter) >= 2:
return
raise error("Number must be greater than 2")
Where the input is q (Linked queue) containing characters. What this
function is supposed to do is check whether the integer in the input is greater than two. The integers could be "2","100", "12" and so on. However, what I think my function does is it only looks for the first integer that comes up in the input and that's why It doesn't work the way it's supposed to.
The way it's supposed to work: if the function finds a "0" in the beginning of the input(ex:H010) it should give the error "Number must be greater than 2". But for every other case, if the digits start with anything that isn't "0" the function should read through every digit of the input before deciding if the number is bigger or smaller than two.
If I were to write the input "H122", the function should be able to read the whole number "122" and and not only the first which is "1".
My question is, how do I make this work?
Assuming you get the entire string, you can do it this way:
def validate(q):
word = q.dequeue()
if word[0] != 'H':
raise error("Does not start with H.")
if not word[1:].isdigit():
raise error("Value is not numeric.")
val = int(word[1:])
if val < 2:
raise error("Number must be greater than or equal to 2.")
return val
I'm not entirely sure about what type q is, or what the H in the string represents for example, but this should work for the cases outlined in the question:
def number(q):
nums = filter(str.isdigit, q)
try:
first_num = next(nums)
except StopIteration:
raise error('Enter a string with numbers')
if first_num == '0':
raise error("Number must be greater than 2")
return int(''.join([first_num, *nums]))
# raises errors
# number('abc')
# number('H012')
assert number('abc123') == 123
assert number('aaaaah123heeeellllpp45') == 12345
assert number('H122') == 122
assert number('2') == 2
assert number('100') == 100
I am trying to write a program that does the following in python:
accept three arguments: a prompt, a low acceptable limit, and a high acceptable limit;
if the user enters a string that is not an integer value, the function should emit the message Error: wrong input, and ask the user to input the value again;
if the user enters a number which falls outside the specified range, the function should emit the message Error: the value is not within permitted range (min..max) and ask the user to input the value again;
if the input value is valid, return it as a result.
I don't want to use if-else. I am learning catching exceptions in python. i want to use try-except
I have written the following code
def readint(prompt, min, max):
try:
theNum = int(input(prompt))
if theNum in range(min, max+1):
return theNum
except ValueError:
return "Error: wrong input. The value is not within the permitted range (-10..10)"
readint(prompt, min, max)
v = readint("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)
The output prints out any number in the mentioned range but when a number not within the range is entered, the output says "The number is: None" and it does not re-prompt me to enter another number
min and max are keywords in python. I would avoid using them as variable names.
def readint(prompt, minimum, maximum):
while True:
try:
value = int(input(prompt))
assert minimum <= value <= maximum
prompt = "Try again: "
except ValueError:
print("Error: Not an integer")
except AssertionError:
print("Error: Value not within range")
else:
break
return value
minimum = -10
maximum = 10
value = readint(f"Enter a number between {minimum} and {maximum}: ", minimum, maximum)
Here's a typical retry loop that uses try/except:
def thing_to_retry():
while True:
try:
return thing()
except SomeError as e:
print("Whoopsie! Error: {}".format(e))
Since the try/except is within the loop, any exception you catch will cause another loop iteration. Success will cause the function to return from the loop.
def readint(prompt, min, max):
doIt = True
while doIt:
try:
userInput = int(input(prompt))
if userInput in range(min, max+1):
doIt = False
return userInput
else:
raise AssertionError
except ValueError:
print("Error: wrong input.")
except AssertionError:
print("The value is not within the permitted range (-10..10)")
except:
doIt = True
v = readint("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)
I created a row of Fibonacci numbers. At the beginning is desired input the number to specify the size of Fibonacci series, in fact the size of the row. The number is required to be an integer number >=2.
The outcome is printing out all Fibonacci number until the last number of the row, with their respective indices within the row! After that it's required to take out a slice of the row, and the outcome is to print out all numbers within the slice with their respective indices.
I successfully mastered to exclude all values that do not fall within range specified, but however I had not succeed to exclude numbers and other inputs of undesired types, example would like to exclude float type of an input variable, and string type of an input variable.
I specified that undesirable types of an input variable are float and string! However it reports me an error! How to overcome that, or by another words how to specify the requirement to exclude a floating variable as well as string variable to not report me an error?
The code:
while True:
n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))
if n < 2:
print('This is not valid number! Please enter valid number as specified above!')
continue
elif type(n)==float: # this line is not working!
print('The number has to be an integer type, not float!')
continue
elif type(n)==str: # this line is not working!
print( 'The number has to be an integer type, not string!')
continue
else:
break
def __init__(self, first, last):
self.first = first
self.last = last
def __iter__(self):
return self
def fibonacci_numbers(n):
fibonacci_series = [0,1]
for i in range(2,n):
next_element = fibonacci_series[i-1] + fibonacci_series[i-2]
fibonacci_series.append(next_element)
return fibonacci_series
while True:
S = int(input('Enter starting number of your slice within Fibonacci row (N>=2):'))
if S>n:
print(f'Starting number can not be greater than {n}!')
continue
elif S<2:
print('Starting number can not be less than 2!')
continue
elif type(S)==float: # this line is not working!
print('The number can not be float type! It has to be an integer!')
continue
elif type(S)==str: # this line is not working!
print('Starting number can not be string! It has to be positive integer number greater than or equal to 2!')
continue
else:
break
while True:
E = int(input(f'Enter ending number of your slice within Fibonacci row(E>=2) and (E>={S}):'))
if E<S:
print('Ending number can not be less than starting number!')
continue
elif E>n:
print(f'Ending number can not be greater than {n}')
continue
elif E<2:
print('Ending number can not be greater than 2!')
continue
elif type(E)==float: # this line is not working!
print('Ending number can not be float type! It has to be an integer type!')
continue
elif type(E) ==str: # this line is not working!
print(f'Ending number can not be string! It has to be positive integer number greater than or equal to {S}')
continue
else:
break
print('Fibonacci numbers by index are following:')
for i, item in enumerate(fibonacci_numbers(n),start = 0):
print(i, item)
fibonacci_numbers1 = list(fibonacci_numbers(n))
print('Fibonacci numbers that are within your slice with their respective indices are following:')
for i, item in enumerate(fibonacci_numbers1[S:E], start = S):
print(i, item)
Solved :-) simply add try except block in ur code like the following:
while True:
try:
num = int(input("Enter an integer number: "))
break
except ValueError:
print("Invalid input. Please input integer only")
continue
print("num:", num)
upvote & check :-)
at the first line
n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))
you're converting the input to int, so whatever the user provides it will be converted to an int.
if you want your code to be working, replace it with this
n = input('Please enter the size of Fibonacci row - positive integer number(N>=2)!')
Use an try/except/else to test the input. int() raises a ValueError if a string value isn't strictly an integer.
>>> while True:
... s = input('Enter an integer: ')
... try:
... n = int(s)
... except ValueError:
... print('invalid')
... else:
... break
...
Enter an integer: 12a
invalid
Enter an integer: 1.
invalid
Enter an integer: 1.5
invalid
Enter an integer: 1+2j
invalid
Enter an integer: 5
>>>
If you need to check type, isinstance is usually better, e. g.:
if isinstance(var, int) or isinstance(var, str):
pass # do something here
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!
I want to check if the input is a number(float with 0,one or two decimals) and greater than 0
def getnumber():
print ( "write a number: \n")
isValid = False
while not isValid:
try:
number = float(raw_input().replace(",","."))
if number >= 0:
isValid=True
else:
print ("Number not valid")
isValid = False
getnumber()
except:
print ("Number not valid")
return number
I have the following problems:
1- I don't know how to check if there are only two decimals
2- The code doesn't return the number if first I introduce a negative number
Does anyone know how to fix it?
Thanks a lot
The reason why your code isn't working with negative numbers is because the function calls itself recursively when the number is negative, but the value of isValid is always false after that call, so the loop repeats.
There isn't really any need for the Boolean variable.
That leaves you with the issue of detecting two decimal places. In order to be able to do that at string level you would have to retain the string that you converted to a floating-point number. Supposing you store it as s you could use some test like len(s) > 3 and s[-3] == '.'` to verify it.
This would give you a solution like:
def getnumber():
while True:
try:
s = raw_input("Write a number:").replace(",",".")
number = float(s)
if number >= 0 and len(s) > 3 and s[-3] ==".":
return number
else:
print("Negative or not two decimal places")
except Exception:
print("Invalid number")
print(getnumber())