how to print getValidInteger? python - python

I'm a beginner in the Python language. I have my getValidInteger function which is:
def getValidInteger():
isValid = False
#initialize strInput
strInput = ""
while (not isValid):
#get string input from the user
strInput = input('Enter an integer: ')
isValid = IsValidInteger(strInput)
if (not isValid):
print('Invalid integer was entered: try again')
#after exiting the loop return strInput cast to an int
return int(strInput)
However, I cannot call that function in the line code below. It shows Typererror: TypeError: getValidInteger() takes 0 positional arguments but 1 was given
setSizeSmall = um.getValidInteger('Enter a small size of each subset:')
I want the output to look like :
Enter a small size of each subset:

I dont know what is your IsValidInteger() function but it doesn't seem to take arguments.
Instead, you can use the isdigit() method like this
def getValidInteger():
isValid = False
#initialize strInput
strInput = ""
while (not isValid):
#get string input from the user
strInput = input('Enter an integer: ')
isValid = strInput.isdigit()
if (not isValid):
print('Invalid integer was entered: try again')
#after exiting the loop return strInput cast to an int
return int(strInput)

Related

Python3 mask-string

I am trying to solve an exercise in python3 and I can't get it to work.
I have this code:
def mask_string(string3):
"""Mask string"""
s = string3[-4:].rjust(len(string3), "#")
masking_string = ""
string3_length = len(s)
result = multiply_str(masking_string, string3_length) + s
return result
def multiply_str(string3, masking_string):
"""Mulitply string"""
new_multiply_str = string3 * int(masking_string)
return new_multiply_str
And I am running it like this:
elif choice == "10":
string3 = input("Enter a string that will replace all of the caracters with # exept the 4 last ones: ")
print(marvin.mask_string(string3))
masking_string = input("Enter number: ")
print(marvin.multiply_str(string3, masking_string))
And I get this error when I run it:
line 131, in multiply_str new_multiply_str = string3 * int(masking_string)
ValueError: invalid literal for int() with base 10: ''
Would really appreciate some help, and please dumb it down a lot when explaining because I am new to python and still do not understand a lot of how to do things.
line 131, in multiply_str new_multiply_str = string3 * int(masking_string)
ValueError: invalid literal for int() with base 10: ''
Therefore your masking_string was "" which is not a valid number (integer or not). You must have pressed enter without entering a number.
If you want to prevent this, wrap your input routine in a loop and only return when you have a number:
def get_int():
while True:
x = input("Number: ")
try:
return int(x)
except ValueError:
print(f"Invalid input {x}, try again...")

Validation for int(input()) python

def is_digit(x):
if type(x) == int:
return True
else:
return False
def main():
shape_opt = input('Enter input >> ')
while not is_digit(shape_opt):
shape_opt = input('Enter input >> ')
else:
print('it work')
if __name__ == '__main__':
main()
So when the user input a value that is not an integer, the system will repeat the input(). Else, it does something else. But it won't work, may I know why?
Check this. Input always returns a string. So isdigit() is better to use here. It returns True if all characters in a string are digits and False otherwise.
return x.isdigit() will evaluate to True/False accordingly, which will be returned
def is_digit(x):
return x.isdigit()
def main():
shape_opt = input('Enter input >> ')
while not is_digit(shape_opt):
shape_opt = input('Enter input >> ')
else:
print('it work')
if __name__ == '__main__':
main()
An easy way to test if an string is an int is to do this:
def is_digit(x):
try:
int(x)
return True
except ValueError:
return False
You must use try except when trying to convert to int.
if it fails to convert the data inside int() then throw the exception inside except which in your case with makes the loop continue.
def is_digit(x):
try:
int(x)
return True
except:
return False
def main():
shape_opt = input('Enter input >> ')
while not is_digit(shape_opt):
shape_opt = input('Enter input >> ')
else:
print('it work')
if __name__ == '__main__':
main()

Latest String value assigned to a variable is not returned by the function in python

In the Below code i am trying to get the user input until it matches the value in the 'type_details' dictionaries.
But the function is returning the invalid input but not the correct value entered finally
Enter the preferred Type:fsafs
Please Choose the Type available in the Menu
Enter the preferred Type:Cup
Traceback (most recent call last):
File "C:\Users\Workspace-Python\MyFirstPythonProject\Main.py", line 186, in <module>
typeprice = type_details[typeValue]
KeyError: 'fsafs'
Below is the code
type_details = {'Plain':1.5,
'Waffle':2,
'Cup':1}
def getType():
type = input("Enter the preferred Type:")
if not ValidateString(type):
print("Type is not valid")
getType()
else:
check = None
for ct in type_details:
if ct.lower() == type.lower():
check = True
type=ct
break
else:
check = False
if not check:
print("Please Choose the Type available in the Menu")
getType()
return type
typeValue = getType()
typeprice = type_details[typeValue]
How about something simple as this?
Get user input, check if it's in dictionary, return if so else continue in the infinite loop.
type_details = {'Plain':1.5,
'Waffle':2,
'Cup':1}
def getType():
while True:
user_in = input("Enter the preferred Type: ")
if user_in in type_details:
return user_in
user_in = getType()
print(f'You entered: {user_in}')
print(f'Type Price: {type_details[user_in]}')
Each time getType() is called (even inside itself) a new local variable type is created whose content is lost if it isn't returned to the calling function.
The content of type in the calling getType() isn't modified.

Function returns "NoneType" after error check for one input, but not in another

Both functions use the same check(x) function and almost identical to each other, except the argument the second function have to take in order to use print.
Entering int as inputs showed no problem.
However, if alphabets were entered, the return result of enter_num() becomes NoneType, but this does not happen in enter_amount().
Where and how did it went wrong?
def check(x): #check if user input is integer
try:
int(x)
return True
except ValueError:
return False
def enter_num(): #get user input for lotto numbers
x = input("buy num:")
if check(x) == True: #check int
x = int(x)
return x
else:
print("Please enter integer")
enter_num()
def enter_amount(x): #get user amount of the lottos
print(x) ##if enter_num errored once, this will show None##
y = input("How many?")
if check(y) == True: #check int
y = int(y)
print("%s for %s copies" % (x,y))
return y
else:
print("Please enter integer")
enter_amount(x)
buy_num = enter_num()
amount = enter_amount(buy_num)
You never return the recursive result from enter_num():
def enter_num():
x = input("buy num:")
if check(x) == True:
x = int(x)
return x
else:
print("Please enter integer")
enter_num() # ignoring the return value
# so None is returned instead
The same applies to enter_amount(); it too ignores the recursive call.
You need to explicitly return the recursive call result, just like you would for any other expression:
def enter_num():
x = input("buy num:")
if check(x) == True:
x = int(x)
return x
else:
print("Please enter integer")
return enter_num() # ignoring the return value
Do the same for enter_amount(); change the last line to return enter_amount(x).
You really should not be using recursion however; all the user has to do is hold the ENTER key for a short amount of time for your code to end up breaking the recursion limit. See Asking the user for input until they give a valid response for better techniques; a while loop would be fine here.
There is also no need to test for == True; if already tests for truth:
if check(x):
I'd also inline the check test; no need to convert to int() twice if the string can be converted. The following won't run out of recursion depth, but just returns int(x) directly if x contained a convertible value, or prints an error message otherwise and loops right back to ask for the number again:
def enter_num():
while True:
x = input("buy num:")
try:
return int(x)
except ValueError:
print("Please enter integer")

How to redo an input if user enters invalid answer

I'm new to programming, and I was wondering how I can repeat an input section, if the user types in invalid data.
I want the application to just repeat the input section, instead of having to run the function all over again and making the user type everything all over again.
My guess is that I would have to change the "return main()" into something else.
condition = input("What is the condition of the phone(New or Used)?")
if condition not in ["New", "new", "Used", "used"]:
print("Invalid input")
return main()
gps = input("Does the phone have gps(Yes or No)?")
if gps not in ["Yes", "yes", "No", "no"]:
print("Invalid input")
return main()
You can make a method to check it in a loop:
def check_input(values, message):
while True:
x = input(message)
if x in values:
return x
print "invalid values, options are " + str(values)
You can generalise the code to use a message prompt and a validating function:
def validated_input(prompt, validate):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = validate(value)
return value
eg:
>>> def new_or_used(value):
... return value.lower() in {"new", "used"}
>>> validate_input("New, or used?", new_or_used)
Or, simpler, but less flexible, pass in the valid values:
def validated_input(prompt, valid_values):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = value.lower() in valid_values
return value
And use:
>>> validate_input("New, or used?", {"new", "used"})
You could even use the valid values to create the input prompt:
def validated_input(prompt, valid_values):
valid_input = False
while not valid_input:
value = input(prompt + ': ' + '/'.join(valid_values))
valid_input = value.lower() in valid_values
return value
Which gives a prompt:
>>> validate_input("What is the condition of the phone?", {"new", "used"})
What is the condition of the phone?: new/used
Here is a good reading about Control Flows.
Also in your case, you can use strip() and lower() for user inputs.
>>> 'HeLLo'.lower()
'hello'
>>> ' hello '.strip()
'hello'
Here is the solution for Python 3:
while True:
condition=input("What is the condition of the phone(New or Used)?")
if condition.strip().lower() in ['new', 'used']:
break
print("Invalid input")
while True:
gps=input("Does the phone have gps(Yes or No)?")
if gps.strip().lower() in ['yes','no']:
break
print("Invalid input")

Categories