checking if the input is int >=0 using if statement - python

IDnum = input("\nprompt: ")
if int(IDnum) >= 0 :
if int(IDnum) in T.keys() :
print("ID number(s) that {} will contact is(are) {}.".format(int(IDnum),T[int(IDnum)]))
else :
print("Entered ID number {} does not exist.".format(int(IDnum)))
else:
break
It's actually a while loop, receiving ID numbers and checking whether the numbers are in the file.
I'd like to make it discern whether the input is an integer >= 0 and if it's anything else, (eg. space,enter,characters,float,etc) break the loop.
How can I do this using if statements?
I have tried
if IDnum == '' or IDnum == ' ' or int(IDnum) < 0 :
but as you know, it cannot cover all the other cases.

T = {1: 1, 2: 2}
while True:
IDnum = input("\nprompt: ")
try:
num = int(IDnum)
if num < 0:
raise ValueError('Negative Integers not allowed')
except ValueError: # parsing a non-integer will result in exception
print("{} is not a valid positive integer.".format(IDnum))
break
if num in T:
print("ID number(s) that {} will contact is(are) {}.".format(num,T[num]))
else:
print("Entered ID number {} does not exist.".format(num))
Thanks to #adirio and #moses-koledoye for the suggested improvements.

Do the check with a try-except statement.
def is_pos_int(IDnum):
''' Check if string contains non-negative integer '''
try:
number = int(IDnum)
except ValueError:
return False
if number >= 0:
return True
else:
return False
For example
is_pos_int('1 ') # notice the space
Out[12]: True
is_pos_int('-1')
Out[13]: False
is_pos_int('1.0')
Out[15]: False
is_pos_int('word')
Out[16]: False
Then:
while True:
if not is_pos_int(IDnum):
break
else:
val = int(IDnum)
if val in T.keys() :
print("ID number(s) that {} will contact is(are) {}.".format(val, T[val]))
else :
print("Entered ID number {} does not exist.".format(val))

Related

How can I make it so that the program loops until the conditions are met?

I was trying to make it so that my program will keep asking the user to input a certain value and if the user doesn't it keeps asking until they do.
I tried to use "while" instead of "if" but I know I'm probably missing something, somewhere.
def terrain(surface):
surface = raw_input("What surface will you be driving on? ")
if surface == "ice":
u = raw_input("what is the velocity of the car in meters per second? ")
u = int(u)
if u < 0:
u = raw_input("Velocity must be greater than 0")
return
if u == 0:
u = raw_input("Velocty must be a number greater than zero")
return
a = raw_input("How quickly is the vehicle decelerating? ")
a = int(a)
if a > 0:
print ("Deceleration cannot be a positive integer")
return
else:
s1 = u**2
s2 = 2*.08*9.8
s = s1/s2
print "This is how far the vehicle will travel on ice: "
print ("The vehicle will travel %i meters before coming to a complete stop" % (s))
terrain("ice")
The problem is you are using return after checking the condition which causes the function to return None you have to use break instead of return with while loop instead of if to achieve this. A better way to validate and get data is below
class ValidationError(Exception):
pass
def validate_and_get_data_count(x):
if int(x) < 0:
raise ValidationError("Cannot be less than 0")
return int(x)
def validate_and_get_data_name(x):
if len(x) < 8:
raise ValidationError("Length of name cannot be less than 8 chars")
elif len(x) > 10:
raise ValidationError("Length of name cannot be greater than 10 chars")
return x
validators = {
"count": validate_and_get_data_count,
"name": validate_and_get_data_name
}
data = {}
params = [
("count","Please enter a count: "),
("name","Please enter a name: "),
]
for param in params:
while True:
x = input(param[1])
try:
data[param[0]] = validators[param[0]](x)
break
except ValidationError as e:
print(e)
print(data)
What the above code does is for every param in params list it runs a while loop checking for every validation condition defined in its validator if valid it breaks the while loop and proceeds to next param and repeats the same process again

Can you use break to validate input in python?

Like using this to validate that an input is only alpha-numeric:
while True:
str = input('')
if str.isalnum():
break
else:
print("Please include only alpha-numeric characters.\n")
This code has worked for all instances that I have tested it in, but is this bad practice?
That's fine. Here is a note, however: you can find out if the while loop exited with a break or without one by using else:
x = 0
while x < 4:
x += 1
else:
print("no break")
# prints no break
If you break, however:
x = 0
while x < 4:
x += 1
if x == 2:
break
else:
print("no break")
# Does not print
you can abstract it further
def verified_input(prompt='',test_condition=lambda x:1,err_message="Please Enter Valid Input"):
while True:
result = input(prompt)
if test_condition(result):
return result
print( err_message )
def verified_alnum(prompt,err_message="Please enter Only alpha numerics"):
return verified_input(prompt,lambda x:x.isalnum(),err_message)
result = verified_alnum("Enter Password:","A password must be only letters and numbers")
this allows you to create any number of test conditions quickly and relatively verbosely

Division by zero error when adding rogue value without any data

Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()

checking whether representation of number in a given base is valid

i have written this code which checks whether a number is correctly represented in a given base. for all the invalid cases it gives false but for true ones it says string index out of range.
def check(n,a,i=0):
if int(n[i])>=a :
return False
else:
return check(n,a,i+1)
n = str(input('enter no:'))
a =int(input('enter base:'))
print(check(n,a,i=0))
The pythonic way:
def is_base_x(num_string, base):
for single_char in num_string:
if int(single_char) >= int(base):
return False
return True
As #ooga pointed out, you need to check when i is larger than the length of your number, you can make it like:
def check(n,a,i=0):
if len(n) <= i:
return True
if int(n[i])>=a :
return False
else:
return check(n,a,i+1)
n = str(input('enter no:'))
a = int(input('enter base:'))
print(check(n,a,i=0))
It would be better if it could check bases above 10. Something like this:
import string
def check(num, base, i = 0):
if i >= len(num):
return True
if not num[i].isdigit():
val = string.ascii_lowercase.find(num[i].lower())
if val == -1 or val + 10 >= base:
return False
elif int(num[i]) >= base:
return False
return check(num, base, i + 1)
while True:
num = raw_input('Enter number: ')
if len(num) == 0: break # null string breaks
base = int(raw_input('Enter base: '))
print(check(num, base))

How to get a valid answer when asking for a number or a letter

def main ():
input('press enter to begin testing...')
counter = 0
total = 0;
value = int( input ("Enter temp: or q to quit " ))
maxval = value
minval = value
while value:
counter += 1
total += value
if value > maxval:
maxval = value
if value < minval:
minval = value
value = int( input ("Enter temp: or q to quit "))
print ( 'Total is: ', total)
print ('Counter is: ', counter)
if counter != 0:
print ('Average is: ', total / counter)
print ('Minimum is: ', minval)
print ('Maximum is: ', maxval)
The problem is when asking for a temp or q to quit since it is an int q is not accepted since it is a str.
I tried asking separate questions but then it doesnt correctly count the loops. Then I tried ord ('q') which is 113. I'm not sure how to get this to apply successfully or if there is a better way.
Instead of converting the value directly to an int, you should first check its contents:
value = input ("Enter temp: or q to quit ")
if value == 'q':
return
value = int(value)

Categories