While loop is not breaking even after the condition is satisfied - python

I've provided the code below.
What is want to do is run the first input box where it will check the condition if true it will go for next input(), but if not it will run the code again. The problem is first input() is running fine, but second one is not getting out of the loop where I'm checking if the input is integer or not
class AC ():
def __init__(self):
self.owner=input("Enter The Name: ")
while True:
if self.owner.isalpha():
self.balance=(input("Enter The Amount: "))
def lol():
while True:
if self.balance.isdigit():
break
else:
print("Enter The Amount: ")
lol()
break
else:
AC()
break

The problem is that your lol() function is never being called for, so it will stay in the first while-loop indefinitely.

lol() function is never being called as Tim said
input() function return string value you can change str to float
try this:
`
def __init__(self):
self.owner = input("Enter The Name: ")
while True:
if self.owner.isalpha():
self.balance = input("Enter The Amount: ")
def lol():
while True:
try:
self.balance = float(self.balance)
except ValueError:
break
if self.balance.isdigit():
break
else:
lol()
else:
AC()
break

Related

How to ensure user input is alpha letters only using try and except

How can I ensure user input is alphabet letters only, and that the user is unable to continue until they have entered alphabet letters only? My below code picks up if user input is not alpha, but allows the user to continue anyway. What am I missing? Please help.
def inputdata(self):
while True:
try:
self.name = input('\nEnter your full name:')
if self.name.isalpha():
print('Data is valid')
# return self.name
break
else:
raise TypeError
except TypeError:
print('Please enter letters only.')
return False
Remove statement return False, it means return from your function, not loop again.
It looks like there is still something wrong, like Cancel button, and close button of input window will break your script (KeyboardInterrupt: Operation cancelled)
Try this
class Person():
def __init__(self):
self.name = self.input_data()
def input_data(self):
while True:
try:
name = input("\nEnter you full name:")
if name.isalpha():
print("Data is valid")
break
except:
pass
print('Please enter letters only.')
return name
person = Person()
print(person.name)

How to check is an input that is meant to be an integer is empty(in python)?

def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = int(input(output_message))
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)
As you can see here the code is supposed to check if an input is an integer and it is above a certain value which by default is 0, but could be changed.
When the user inputs random letters and symbols it see that there is a value error and returns "Integers only!(Please do not leave this blank)".
I want to be able to check if the user inputs nothing, and in that case only it should output "This is blank/empty", the current way of dealing with this is to not check at all and just say "Integers only!(Please do not leave this blank)", in case there us a value error. I want to be able to be more specific and not just spit all the reasons at once. Can anyone please help me?
Thanks in advance.
You could do something like this :
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!", above=0, error_3="Please do not leave this blank"):
while True:
user_input = input(output_message)
try:
user_input = int(user_input)
if user_input >= above:
return user_input
break
else:
print(error_1.format(above))
except ValueError:
if(not user_input):
print(error_3)
else:
print(error_2)
I moved the input outside the try/except block to be able to use it in the except ! This worked fine for me, I hope this is what you needed.
You could just break the input and the conversion to int into two steps, like this:
def aboveIntegerInput(output_message="Enter your number: ", error_1="Please enter a number above {}!", error_2="Integers only!(Please do not leave this blank)", above=0):
while True:
try:
user_input = input(output_message)
if not user_input:
print("Please do not leave this blank")
continue
user_input = int(user_input)
if user_input >= above:
return int(user_input)
break
else:
print(error_1.format(above))
except ValueError:
print(error_2)

How to simulate series of user input in Python

Let's say we have a function like this
def function():
while True:
user_input = input("enter a number: ")
if user_input == "0":
print("finish")
break
print("the number is " + user_input)
And in the main() we call the function
function()
Then it will ask for user input until it gets a "0".
What I want to do is like have something can store all the input, and automatically give it to the console. So, I don't need to manually type them in the console.
Please note that I'd like to have the function not accepting arguments and use something_taken_as_input without passing it as an argument.
something_taken_as_input = ["1","2","3","0"]
function()
# enter a number: 1
# enter a number: 2
# enter a number: 3
# enter a number: 0
# finish
# all done by the program, no manually typing!
A fun way to do this would be to pass the input method to the function.
This way, you can do this:
def function(inp_method):
while True:
user_input = inp_method("enter a number: ")
if user_input == "0":
print("finish")
break
print("the number is " + user_input)
if you want to take input from the user,
call it like this:
function(input)
otherwise, define a class with the data you want to input:
class input_data:
def __init__(data):
self.data = data
self.count = 0
def get(self, str = ""):
if(self.count == len(self.data)):
return 0
else:
count+=1
x = self.data[count-1]
and call function using:
d = input_data(["1", "2", "3", "0"])
function(d.get)
Fundamentally, you are just passing the method through the parameters of the function.

break outside the loop error in python

I'm created simple bank programme where i create four methods for the transaction. below is my code. the problem is it shows an error that "break outside the loop".
kindly help, I'm new to python.
bal=0
def deposit():
global bal
amount=input('Enter Deposit Amount: ')
bal=bal+amount
def withdraw():
global bal
amount=input('Enter Withdraw Amount: ')
bal=bal-amount
def checkbal():
global bal
print bal
def conti():
c=raw_input('Do You Wana Continue y/n....')
if c=='y':
main()
else:
break
def main():
print '---Welcome To ABC Bank---'
print 'Enter 1 For Deposit:'
print 'Enter 2 For Withdraw:'
print 'Enter 3 For Balance Check:'
print 'Enter 4 For Exit:'
choice= input('Enter Your Choice :')
if(choice==1):
deposit()
elif(choice==2):
withdraw()
elif(choice==3):
checkbal()
else:
print 'Invalid Entry'
conti()
main()
break outside the loop
it means you use break not inside a loop. break is only used inside a loop when you want to stop the iteration.
So, in this code:
def conti():
c=raw_input('Do You Wana Continue y/n....')
if c=='y':
main()
else:
break # should be exit()
If you want to exit from program if user choose not to continue, then break should be exit()
or return if you just want to exit from conti() function. (But it means you still go to main() function)
def conti():
c=raw_input('Do You Wana Continue y/n....')
if c=='y':
main()
else:
break
You can use return statement in place of break because break will come outside the loop whereas return will return you to main function else if you want to come out of program you can simply use exit()

Python Noob: Input returning as none

Im still very new when it comes to python so be easy on me. Whenever I test this code it comes back with "None" instead of the input entered. Any idea why it could be happening?
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
def main():
while(1):
landValue = inputLandValue()
print(landValue)
doMoreStuff = input('Do you want to continue? y/n ')
if(doMoreStuff.lower() != 'y'):
break
main()
input()
You indented your return value line too far. It is part of the except: handler, so it is only executed when you have no value! It should be outside the while loop:
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
or replace the break with return value:
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
return value
except:
print('Please enter a whole number (10000)')
You should really only catch ValueError however; this isn't Pokemon, don't try to catch'm all:
except ValueError:
You can fix your problem by just putting 'return value' in place of the break in main().

Categories