Checking user input via raw_input method - python

I'm trying to use raw_input to get input from the user, i want to catch the instances where the user may enter a number. I've been searching threw stack overflow and various other websites and i haven't come across anything that made much sense to me. Since raw_input always returns a string is it even possible to catch such an instance?
class Employee(object):
def __init__(self,name,pay_rate,hours):
self.name = name
self.pay_rate = pay_rate
self.hours = ("mon","tues","wed","thursday","friday","saturday","sunday")
def __str__(self):
return self.name
#property
def weekly_total(self):
return sum(self.hours)
#classmethod
def from_input(cls):
while True:
try:
name = raw_input("Enter new employee name\n")
except ValueError:
print("\n This is a integer ")
continue
else:
break
while True:
try:
pay = input("Enter pay rate ")
except ValueError:
print("You must enter a value ")
continue
else:
break
while True:
try:
hours = input("Enter a tuple for days monday through sunday ")
except ValueError:
print("use must enter a tuple with 7 integer values")
continue
else:
break
return cls(name,pay,hours)
employee = Employee.from_input()
print str(employee)

I would split this into separate functions; there are neater ways to do this, but I have made them as similar as possible so you can see the process:
def get_int_input(prompt):
while True:
s = raw_input(prompt)
try:
i = int(s)
except ValueError:
print "Please enter an integer."
else:
return i
def get_non_int_input(prompt):
while True:
s = raw_input(prompt)
try:
i = int(s)
except ValueError:
return s
else:
print "Please don't enter an integer."

Related

Using var() to instantiate object from user input. Syntax error

I've made these classes and now I'm trying to make a function that allows you to instantiate a new object from data a user inputs. But I'm getting syntax errors with using var()
The class structure is that there is one main with two sub-classes. The main, "Gokemon" is:
class Gokemon:
def __init__(self,NAME,TYPE,HEALTH,POWER): #Contructor #Mayb think about using dict key words
self._Name = str(NAME)
self._Type = str(TYPE) #Water, Earth, Fire or Flying. Used in Battle() to allow adders
self._HP = int(HEALTH) #Health Points
self._DP = int(POWER) #Power Points - attacking power
and the two sub-classes are named "Tame" and "Wild".
class Tame(Gokemon):
def __init__(self,NAME,TYPE,HEALTH,POWER):
Gokemon.__init__(self,NAME,TYPE,HEALTH,POWER)
self._Owner = ""
self._Time = 0 #How long have they owned it
class Wild(Gokemon):
def __init__(self,NAME,TYPE,HEALTH,POWER):
Gokemon.__init__(self,NAME,TYPE,HEALTH,POWER)
The function for making the new object by user input is as follows:
def NewGokemon():
n = input("What's its name?: ")
while True:
t = input("what's its type?: ")
if t == "Water" or t == "Fire" or t=="Earth" or t =="Flying":
break
else:
print("please try again, the types include:\nFire\nWater\nEarth\nFlying")
while True:
h = input("How many Health Points(HP) does it have")
try:
int(h)/2
except ValueError:
print("Sorry please input a numerical value")
else:
break
while True:
p = input("How many Health Points(HP) does it have")
try:
int(p)/2
except ValueError:
print("Sorry please input a numerical value")
else:
break
while True:
dom = input("Is the Gokemon tame(input t) or wild(input w)?")
if dom =="t":
return var()[n] = Tame(n,t,h,p)
if dom == 'w':
return var()[n] = Wild(n,t,h,p)
The function is fine until at the bottom, when im compiling to execute my Editor (VS code) says.
File "c:\Users\rufar\Desktop\python\little projects\Gokemon - learning class\Gokemon.py", line 38
return var()[n] = Tame(n,t,h,p)
^
SyntaxError: invalid syntax
What am i doing wrong? Is there a better way of doing this?
replaced the whole bit with vars() with this:
while True:
dom = input("Is the Gokemon tame(input t) or wild(input w)?")
if dom =="t":
globals()[n] = Tame(n,t,h,p)
return n
elif dom == 'w':
globals()[n] = Wild(n,t,h,p)
return n
else:
print("Did not understand input")
And now it works fine.

Try-Except ErrorCatching

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

Try- except ValueError loop

def enterNumber():
number = input("Please enter a number to convert to binary. ")
while True:
try:
int(number)
convertDenary()
except ValueError:
enterNumber()
def convertDenary():
binaryNumber = ['','','','','','','','']
print(enterNumber())
if enterNumber() > 128:
enterNumber() - 128
binaryNumber[0] == 1
enterNumber()
The Try- Except ValueError does loop as I intend it to however, it won't break. I've tried adding in break under the int(number), removing the while True: and added in the convertDenary() to see if it will force the subroutine to stop and start the other but it still doesn't work.
I get an infinite loop of "Please enter a number to convert to binary."
Any ideas?
def convertToBinary(number):
if number > 1:
convertToBinary(number//2)
elif number<1:
enterNumber()
print(number % 2,end = '')
def enterNumber():
number = (input("Please enter a number to convert to binary : "))
try:
convertToBinary(int(number))
except Exception as e:
print(e)
enterNumber()

How can I make a Validation Try and Except Error for this?

I have this code as shown below and I would like to make a function which has a try and except error which makes it so when you input anything other than 1, 2 or 3 it will make you re input it. Below is the line which asks you for your age.
Age = input("What is your age? 1, 2 or 3: ")
Below this is what I have so far to try and achieve what I want.
def Age_inputter(prompt=' '):
while True:
try:
return int(input(prompt))
except ValueError:
print("Not a valid input (an integer is expected)")
any ideas?
add a check before return then raise if check fails:
def Age_inputter(prompt=' '):
while True:
try:
age = int(input(prompt))
if age not in [1,2,3]: raise ValueError
return age
except ValueError:
print("Not a valid input (an integer is expected)")
This may work:
def Age_inputter(prompt=' '):
while True:
try:
input_age = int(input(prompt))
if input_age not in [1, 2, 3]:
# ask the user to input his age again...
print 'Not a valid input (1, 2 or 3 is expected)'
continue
return input_age
except (ValueError, NameError):
print 'Not a valid input (an integer is expected)'

Python 2.7 try and except ValueError

I query user input which is expected to be an int by using int(raw_input(...))
However when the user doesn't enter an integer, i.e. just hits return, I get a ValueError.
def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
while True:
#Test if valid row col position and position does not have default value
if rangeRows.count(rowPos) == 1 and rangeCols.count(colPos) == 1 and inputMatrix[rowPos][colPos] == defaultValue:
inputMatrix[rowPos][colPos] = playerValue
break
else:
print "Either the RowCol Position doesn't exist or it is already filled in."
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
return inputMatrix
I tried to be smart and use try and except to catch the ValueError, print a warning to the user and then call the inputValue() again. Then it works when the user enters return to the query but falls over when the user correctly then enters an integer
Below is the part of the amended code with the try and except:
def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
try:
rowPos = int(raw_input("Please enter the row, 0 indexed."))
except ValueError:
print "Please enter a valid input."
inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue)
try:
colPos = int(raw_input("Please enter the column, 0 indexed."))
except ValueError:
print "Please enter a valid input."
inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue)
A quick and dirty solution is:
parsed = False
while not parsed:
try:
x = int(raw_input('Enter the value:'))
parsed = True # we only get here if the previous line didn't throw an exception
except ValueError:
print 'Invalid value!'
This will keep prompting the user for input until parsed is True which will only happen if there was no exception.
Instead of calling inputValue recursively, you need to replace raw_input with your own function with validation and retry. Something like this:
def user_int(msg):
try:
return int(raw_input(msg))
except ValueError:
return user_int("Entered value is invalid, please try again")
Is something like this what you're going for?
def inputValue(inputMatrix, defaultValue, playerValue):
while True:
try:
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
except ValueError:
continue
if inputMatrix[rowPos][colPos] == defaultValue:
inputMatrix[rowPos][colPos] = playerValue
break
return inputMatrix
print inputValue([[0,0,0], [0,0,0], [0,0,0]], 0, 1)
You were right to try and handle the exception, but you don't seem to understand how functions work... Calling inputValue from within inputValue is called recursion, and it's probably not what you want here.

Categories

Resources