Issue
The task is to delete an object from an array within another array (a touple if i'm correct). To bugproof i would need to check whether the index is actually valid. This means ranges from 0 to 4 (so input should be greater 0 smaller 4) and obviously not be a string or float of any kind.
I have tried to do that with my def function. i obviously want loopx to only be false if indeed both of the above mentioned criteria are met. otherwise i would want to jump to except. I felt like if that is what I've done but now been stuck for over an hour.
#Write a Python program to delete an existing item from the array
#function used to check for valid input
def valuecheck(checker):
loopx = True
while loopx:
try:
if checker == int(checker) and (checker>0 and checker<4):
#first it checks if the input is actually an integer
#checker = int(checker)
#checks if the input index number is within range of the array
loopx = False
else:
checker = input("Value isn't a valid input, try again: ")
return(checker)
#if input isn't an integer the below prompt is printed
except:
checker = input("Value isn't a valid input, try again: ")
#the example array is defined and printed
myarray = ['i', [1, 3, 5, 7, 9]]
print(myarray[1])
#input defined and checked by the loop
deletion = input("Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: ")
deletion = valuecheck(deletion)
#pop is then used to remove the value with index "deletion" from the array
myarray[1].pop(deletion)
#finally the new array is printed
print ("This is the new array:",myarray[1])
Solution
Here is a version of the valuecheck()
function that should do what you want:
def valuecheck(checker):
while True:
try:
checker = int(checker)
if checker > 0 and checker < 4:
return checker
checker = input("Value must be between 1 and 3, try again: ")
except:
checker = input("Value must be an integer, try again: ")
The main difference to your code is that the value in checker
is converted to an integer before it is tested to check if it's in the range 1-3. That operation will throw an exception if checker
doesn't contain the string representation of a valid integer.
Rather than using the loop variable loopx
, the function simply returns when it finds a valid value.
Answered By - CryptoFool
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.