def() function screws with my indentation - python

I'm writing a basic script that scans files and moves them if they fit some criteria set by the user.
I have tried complying with what it wants but that just ends up with every line of code being indented one more than the other.
def check():
#code simplication
for i in range(2):
if fileScanDestination == '':
noValue(moveFrom)
else:
#exits
if fileMoveDestination == '':
noValue(moveTo)
else:
#exits
if specialFileExtension == '':
str(specialFileExtension) == 'nil'
else:
#exits
if fileNameSpecial == '':
str(fileNameSpecial) == str('nil')
else:
#exits
def p(text):
print(text)
#setting up tkinter
# getting variable data
p('Please enter the path for the files you would like to sort.')
fileScanDestination == str(input())
This should just have to be indented once, then exit. But since it wants to indent every new line, which just looks bad.

Try putting some pass instructions after the else statements, or some return's if you say it should exit.
You could even shorten the whole thing by doing:
if any([
fileScanDestination == '',
fileMoveDestination == '',
specialFileExtension == '',
str(specialFileExtension) == 'nil',
str(fileNameSpecial) == str('nil'),
fileNameSpecial == ''
]):
return

Related

"list index out of range" exception (Python3)

I keep getting a list index out of range exception when I check the length of the list a. The error pops up for either the if or elif part of the second if statement, depending on what the user inputs. I know that when the user input is split the list is created correctly because I print it out... So I'm a little lost about why I'm getting that error.
if __name__ == '__main__':
for line in sys.stdin:
s = line.strip()
if not s: break
if (str(s) is "quit") == True: quit()
elif (str(s) is "quit") == False:
a = s.split()
print(a)
if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)
else: print("Invalid Input. Please Re-enter.")
The first method is: (The methods it calls in the if statement just print things out at the moment)
def first(self, a = list()):
word = a[0]
if word is ls:
ls(a[1])
elif word is format:
form(a[1]) # EDIT: was format
elif word is reconnect:
reconnect(a[1])
elif word is mkfile:
mkfile(a[1])
elif word is mkdir:
mkdir(a[1])
elif word is append:
append(a[1], a[2])
elif word is delfile:
delfile(a[1])
elif word is deldir:
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
Other methods:
def reconnect(one = ""):
print("Reconnect")
def ls(one = ""):
print("list")
def mkfile(one = ""):
print("make file")
def mkdir(one = ""):
print("make drive")
def append(one = "", two = ""):
print("append")
def form(one = ""):
print("format")
def delfile(one = ""):
print("delete file")
def deldir(one = ""):
print("delete directory")
def quit():
print("quit")
sys.exit(0)
The problem seems to be the definition of first(). You invoke it as a function:
if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)
But you define it as a method:
def first(self, a = list()):
The array of command and argument gets put into self and a is always an empty list which you attempt to index and fail. Also, you shouldn't use a mutable type like list() as a default value unless you're certain what you are doing. I suggest simply:
def first(a):
As far as your __main__ code goes, simplify:
if __name__ == '__main__':
for line in sys.stdin:
string = line.strip()
if not string:
break
if string == "quit":
quit()
tokens = string.split()
length = len(tokens)
if 2 <= length <= 3:
first(tokens)
else:
print("Invalid Input. Please Re-enter.")
Real issue:
To solve your error you have to remove the self parameter of the first function
def first(a=list())
Basically the self is only used for object orientation creating methods.
Function like yours can't use self otherwise you will passing the first parameter to self not to a which you want to.
My second issue I can point out is that, You are trying to compare using is between a string and a function.
def first(a = list()):
word = a[0]
if word is "ls":
ls(a[1])
elif word is "format":
format(a[1])
elif word is "reconnect":
reconnect(a[1])
elif word is "mkfile":
mkfile(a[1])
elif word is "mkdir":
mkdir(a[1])
elif word is "append":
append(a[1], a[2])
elif word is "delfile":
delfile(a[1])
elif word is "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
Extra
The is function on built in operations in Python. is compare the equity of the objects.
But this expression:
if (str(s) is "quit") == True:
Can be simpler like:
if str(s) == "quit":
Or:
if str(s) is "quit":
The == True is meaningless either == False you can use not more pythonicly.

Why dont my functions work?

This is python 3, this code basically checks if a word is the same when read backwards. When i execute this through Visual Studio, nothing happens, and I get the prompt to press any key to continue...
if "__name__" == "__main__":
StartProgram()
def StartProgram():
Input = AskForDataSimple()
print(CheckIfPalindrome(Input))
def AskForDataSimple():
print("Please input the line to test.")
In = input()
return In
def CheckIfPalindrome(x):
if x[::-1] == x:
return True
else:
return False
Please note that this simpler version actually works:
x = input()
if x[::-1] == x:
print(True)
else:
print(False)
if "__name__" == "__main__":
Change this to
if __name__ == "__main__":
__name__ is a variable containing name of this module. You need these line so that your main logic would be used only if this file is executed directly, not when imported as a module by another code.
Still it won't work, because you need to define the function you call before these lines: move these lines to the end of the file.
Also, this
def CheckIfPalindrome(x):
if x[::-1] == x:
return True
else:
return False
can be replaced with
def CheckIfPalindrome(x):
return x[::-1] == x
Move main function to bottom of file and try it
if __name__ == "__main__":
StartProgram()

Python 3.4.2:My infinite function while loop is not working

My infinite while loop is not working as I expected it:
def main():
print("Type 1 to create a file")
print("Type 2 to read a file")
print("Type 3 to append a file")
print("Type 4 to calculate total of file")
print("Type 5 to end the program")
choice=input("Select a number:")
if choice == '1':
file_create(filename)
elif choice == '2':
read_file(filename)
elif choice == '3':
append_file(filename)
elif choice == '4':
add_numbers(filename)
filename=input("Give a name to your file:")
while main():
# ...
This executes the main once, but it does not loop.
Mr.Anyoneoutthere, Sylvain is absolutely correct. Since you don't understand it, I'll explain.
A loop needs a conditon:- True OR False.
So when you say:-
while True:
print('World')
is the same as:-
a = 100
while a == 100:
print('poop')
Since a == 100 would evaluate to 'True', and start a loop because you let the value remain constant, and start an infinite loop. But you can directly put the evaluation, i.e., 'True', so as to directly start an infinite loop.
As you have put:-
while main():
print('World')
So now think... while main()... main() what?... the compiler does not get any code to evaluate something into 'True' or 'False' and the loop never starts!
So your required correct code is:-
while True:
main()
def main():
# ...
# <- no return statement
while main():
# Something
The while loop loops as long as the condition is true. Here, as your main() function does not have a return statement, it doesn't return anything explicitly. So Python behave as if it were returning None. None is not true. So the condition is false and you don't execute the body even once.
What about something like that (assuming you need to execute main() until the user wants to quit):
def main():
# ...
print("Type 9 to quit")
choice=input("Select a number:")
if choice == '9':
return False
# Handle other cases
if choice == '1':
file_create(filename)
elif choice == '2':
# ...
return True
On the other hand, as suggested by #thiruvenkadam in a comment below, you could keep your main as it was written in your question, but really write an infinite loop:
while True:
main()
But that way, if you want to terminate your program gracefully , you will have to rely on some other mechanism like using exceptions...

Exploring a maze (using python 2.7)

I have done everything on my homework except a one step.
I did it in a different way, but it gave kind of right answer somehow.
Anyway, I have to explore a maz, so I went all the way through and got everything completely right, except part (Q COMMAND) of this task.
I need to use string method .upper()
2.2.6 The Top-Level Interface
interact() is the top-level function that denes the text-base user interface
as described in the introduction.
Note that when either the user quits or
when the finish square is found, the interact function should exit.
def interact():
mazefile = raw_input('Maze File: ')
maze = load_maze(mazefile)
position = (1, 1)
poshis = [position]
while True:
#print poshis, len(poshis)
print 'You are at position', position
command = raw_input('Command: ')
#print command
if command == '?':
print HELP
elif command == 'N' or command == 'E' or command == 'S'or command == 'W':
mov = move(maze, position, command)
if mov[0] == False: #invalid direction
print "You can't go in that direction"
elif mov[1] == True:#finished
print 'Congratulations - you made it!'
break
else: #can move, but not finished
position = mov[2]
poshis.append(position)
elif command == 'R': # reseting the maze to the first pos
position = (1, 1)
poshis = [position]
elif command == 'B': # back one move
if len(poshis) > 1:
poshis.pop()
position = poshis[-1]
elif command == 'L': # listing all possible leg dir
toggle = 0
result = ''
leg_list = get_legal_directions(maze, poshis[-1])
for Legal in leg_list:
if toggle:
result += ', '
result += Legal
else:
result += Legal
if not toggle:
toggle = 1
print result
elif command == 'Q': #quiting
m = raw_input('Are you sure you want to quit? [y] or n: ')
if m == 'y':
break
#print 'Are you sure you want to quit? [y] or n: '
#if raw_input == 'y':
# break
else: #invalid input
print 'Invalid Command:', command
Your question isn't particularly clear, but I'm guessing that the 'problem' is that if a user were to answer "Y" instead of "y" when asked if they are sure they want to quit, then the loop will continue.
If that is the problem, you should merely replace the line:
if m == 'y':
break
with:
if m.upper() == 'Y':
break
Because regardless of whether the user types "y" or "Y", the loop will still be broken out of.

Revisiting Functions In Python 3

In my script I have four functions that work like this:
def function_four():
# Does Stuff
function_one()
def function_three():
# Does Stuff
function_two()
def function_one():
usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
if usr_input == '1':
function_three()
elif usr_input == '2':
sys.exit()
else:
print("Did not recognise command. Try again.")
function_one()
def function_two():
usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
if usr_input == '1':
function_four()
elif usr_input == '2':
function_three()
elif usr_input == '3':
sys.exit()
else:
print("Did not recognise command. Try again.")
function_one()
I need to know if this will cause the problem I think it will: the functions never closing, causing lots of open functions (and, presumably, wasted memory and eventual slow-down) to appear, never to disappear until the user quits the script. If true, then this would most likely be bad practise and inadvisable, meaning that there must be an alternative?
Whenever you have Python code that is:
Recalling The Same Function So That If The User Does Not Chose One Of The Other Statements Then They Can Try Again Rather Than The Program To Stop Working,
you are almost always better off replacing the recursive call with a loop. In this case the recursion is completely unnecessary, probably wastes resources and arguably makes the code harder to follow.
edit: Now that you've posted the code, I'd suggest recasting it as a state machine. The following page provides a summary of Python modules that could be useful: link.
Even without any additional modules, your code lends itself to a simple non-recursive rewrite:
import sys
def function_four():
# Does Stuff
return function_one
def function_three():
# Does Stuff
return function_two
def function_one():
usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
if usr_input == '1':
return function_three
elif usr_input == '2':
return None
else:
print("Did not recognise command. Try again.")
return function_one
def function_two():
usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
if usr_input == '1':
return function_four
elif usr_input == '2':
return function_three
elif usr_input == '3':
return None
else:
print("Did not recognise command. Try again.")
return function_two
state = function_one
while state is not None:
state = state()
Note that the functions no longer call each other. Instead, each of them returns the next function to call, and the top-level loop takes care of the calling.

Categories