def search():
try:
option=input("\n\nWhta do you want to search by ('A' for account type, 'B' for balance): ")
if option.lower()=='a':
option_2=input("\n\nWhat type of account do you want to view ('C' for current,'S' for savings): ")
if option_2.upper()=="C":
inFile=open("account.dat","rb")
acc_det=pickle.load(inFile)
for x in acc_det:
if x.rettype()=="C":
print("\n\n\tACCOUNT HOLDER LIST\n\n")
print(60*"=")
print("%-10s"%"A/C No.","%-20s"%"Name","%-10s"%"Type","%-6s"%"Balance")
print(60*"=","\n")
x.report()
except EOFError:
print("Enter Valid Statement")
"""*****************************************************************************
THE MAIN FUNCTION OF PROGRAM
*****************************************************************************"""
intro()
while True:
print(3*"\n",60*"=")
print("""MAIN MENU
1. New Account
2. Deposit Amount
3. Withdraw Amount
4. Balance Enquiry
5. All Account Holder List
6. Close An Account
7. Modify An Account
8. Exit
9. Filter Accounts
""")
The code gives an indentation error right after the last triple quote. I can't figure out why, but the error goes away if I remove the "try" clause. Why is this happening ?
Edit : I have edited in the next part of the code, where I call in the main function
In python, after every ":" and newline, there needs to be an indentation of atleast one space or tab character.
In your above program, you have declared a function search(), and have a semi-colon after it, so in the next line, you need to indent the statements inside the function.
So, you will have to indent try: and except: statements, and recursively keep indenting the code blocks present in the try/except clauses
I can see two critical section in regards of indentation:
try: and except EOFError: have the same indentaion as def search():
Your print statements are indented by 8 spaces
maybe here is a problem :
def search():
try:
try this:
def search():
try:
do def search() and try: have same level of indentation?
Related
I am trying to make an input that would prevent a user entering an input like this "QWERTY" this "qwerty" or this "QW3RTY"
The input is for names so I want to make sure that it would need the user to have a capital letter at the start of their name "John" not "john"
I have tried to loop the question using while True: try and attempted to use .isalpha and .title but I couldnt seem to make it work
while True:
try:
name = input(str("What is your name? "))
if name is not name.isalpha:
print("Please Enter a Valid name")
continue
if name is not name.title:
print("Please have a capital letter at the start of your name!")
continue
else:
break
I expected for the if statements to work but it comes up with invalid syntax.
Your logic is faulty ... but you've replicated it, even though the first if failed. Correct your problems one at a time, rather than trying to write the whole program at once.
name is a string; name.isalpha is a function.
A string cannot ever be identical to a function.
I think what you want is
if name.isalpha():
Also, try requires an except clause to catch exceptions. Again, add program features individually. That way, when you hit an error, you'll be fixing only that one error.
See this lovely debug blog for help.
Implementing features one at a time is a much better place to start than to try to catch everything all at once. Also, make sure to call your functions, otherwise, they will be truthy:
if str:
print("True!")
else:
print("False!")
True!
# compared to
if str():
print("True!")
else:
print("False!")
False!
Functions are objects, and will not act Falsey.
while True:
name = input("What is your name? ") # no need for str function here
# you can wrap this whole thing in a
# try/except for ValueError
try:
if name.isupper() or name.islower() or not name == name.title():
raise ValueError("Please include proper capitalization")
elif not name.isalpha():
raise ValueError("Use only alphabetical characters, please")
else:
break
except ValueError as e:
print(e)
I'm still kind of learning Python, but my friend who has programmed in Python before says this should work fine, but it wont?
All code before this was the beginning story for this basic "escape the room" game I'm making. The code up until here works, (basic print functions describing the game).
I give the player the scenario that they're in a room and they can do one of two things:
def intro_room_input():
intro_action = input("What would you like to do? (Please enter either: 1 or 2) ")
return intro_action;
These two functions are for when they choose 1 or 2, the next if/elif function runs these functions
If they choose 1:
def intro_room_result1():
print(
"""
(Story stuff for the result of option 1. Not important to the code)
""")
return;
This function will play out if they choose 2
def intro_room_result2():
print(
"""
(Story stuff for the result of option 2. Not important to the code)
""")
return;
This will be the function for taking the player's input and continuing the story from there.
def intro_action_if(string):
if string == "1":
intro_room_result1()
elif string == "2":
intro_room_result2()
else:
print("I'm sorry, that wasn't one of the options that was available..."+'\n'+
"For this action, the options must be either '1' or '2'"+'\n'+
"Let me ask again...")
intro_room_input()
intro_action_if(string)
return;
that last intro_room_input runs fine, it re-runs the previous input, but when you actually enter 1 or 2, it doesn't do anything with them. It doesn't want to re-run the if/elif/else function to give the results.
finally I have a main that runs everything:
def main():
string = intro_room_input()
intro_action_if(string)
return;
main()
Please help, I have no idea what's wrong with this code!?
The problem is in your intro_action_if(). When you are calling the function to get values again, you forgot to change the string value.
ie,
#intro_room_input() #wrong
string = intro_room_input() #right
intro_action_if(string)
As you can see, even though in your code you asked for the user input and returned it, you forgot to reassign string with the returned value. Hence it kept the same input you had given previously and passed that old value to intro_action_if().
I am making a calculator (using tkinter) and I need to have a limit so if the user enters an input of more than 999, an error message appears and the numbers are not calculated (it is a school project). When I run the script from below, at school it just appears with a blank GUI and on my home computer it says 'unindent does not match any outer indentation level'. How can I solve this?
Thanks
P.S. I am using Python 3.3.2
def calc(self):
try:
self.display.set(self.validate_result(eval(self.display.get())))
self.need_clr = True
except:
showerror('Operation Error', 'Illegal Operation')
self.display.set('')
self.need_clr = False
def validate_result(self, result):
if result >= 1000:
raise ValueError('result too big!')
else:
return result
Python uses indentation to distinguish levels of scope.
Here all your code seems to be entirely indented, so Python thinks all your code is in an inner scope, and tries to find the outer scope that contains it, but there isn't any.
You should try with this indentation :
def calc(self):
try:
...
def calc(self):
try:
...
Edit : also, you seem to have other indentation problems in the second function. You must align except with try, and there is one space missing before if result >= 1000:.
Alright so I'm trying to basically prevent someone from typing a string value into the field:
#User selection
print("Which program would you like to run?")
print("(Type '9' if you wish to exit the menu)")
selection = int(input())
print()
#Security statement followed by case statement
while selection <= 0 or selection >= 10:
try:
print("That is an invalid selection, please input a proper selection.")
print("Which program would you like to run?")
selection = int(input())
print()
except ValueError:
print("Cmon man")
Plain and simple, it's not running. I've tried reorganizing everything and I haven't found a proper solution. Been looking around for almost an hour now. No help to the issue. Any kind souls?
Ignore the case statement portion btw, that's not even written yet.
P.S. Just keep getting usual "String isn't a number durr" response
("ValueError: invalid literal for int() with base 10: 'why'")
P.P.S. Issue is already pointed out. I'm apparently stupidly oblivious lol... Thanks for the help.
Your try...except doesn't cover the initial user input and so the ValueError isn't actually caught.
If you enter an int outside the bounds defined (0 >= x >= 10) as the first input then you can see the try...except blocks working.
You'll need to refactor your code so that the first input request is inside your try block and the loop or wrap the existing input request in another try...except.
Also, as a side note, input() can take a string argument that will be displayed as a prompt to the user.
selection = int(input("Which program would you like to run? "))
password = raw_input("Enter password: ")
if password == "1234":
print "You logged in correctly!"
else:
print "GTFO"
Though i give different indentations the code is working fine i'm unable to figure it out.
it will not be flagged as as IndentationError, sine any block of statement has to have at lease 1 space of indent
here your if and else are two different blocks, so it was indented anyway so the interpreter throws no error
if True:
print
elif True:
print
elif True:
print
elif True:
print
else:
print
This will work without any problem
But if I try the following I will get IndendationError
if True:
print ""
print "" # has different Indentation
print ""
The Python documentation explains indentation. Here's a relevant excerpt:
At the beginning of each logical line, the line’s indentation level is
compared to the top of the stack. If it is equal, nothing happens. If
it is larger, it is pushed on the stack, and one INDENT token is
generated. If it is smaller, it must be one of the numbers occurring
on the stack
In your code, since the indentation level is larger than the top of the stack (which is 0), it is treated as a single indent. The else: line popped 2 off of the top of the stack, so the interpreter has no memory of your previous indentation level of 2. It only knows that it's higher than the 0.
Problems arise when you start mixing indentation within a block:
def foo():
if True:
return True
return False # Is this part of the if statement or not?
When the parser reaches return False, the stack contains [4, 8]. The next line has an indent of 6, which is not contained in the stack and therefore generates an IndentationError.