Reputation: 13
The input wont prompt when I run the program. How do I fix this?
import sys
def main():
# Initialize list and determine length
string_list = raw_input("Enter your strings to be sorted: ").split(' ')
string_list.sort()
length = len(string_list)
# If there are more than one strings to sort, print the list
# Otherwise break
if length > 1:
print(string_list)
elif length < 0:
print("Enter more than one string to sort")
return sys.exit()
Upvotes: 1
Views: 524
Reputation: 11605
You need to call your function. As it is it is not executing anything but closing immediately. In this case you can call your execute it with main()
:
import sys
def main():
# Initialize list and determine length
string_list = raw_input("Enter your strings to be sorted: ").split(' ')
string_list.sort()
length = len(string_list)
# If there are more than one strings to sort, print the list
# Otherwise break
if length > 1:
print(string_list)
elif length < 0:
print("Enter more than one string to sort")
return sys.exit()
main()
When you create a function you create code that is never executed unless it is called. This is useful when creating modules for example because it does not execute it immediately.
It seems you are used to another language because unlike some (C++/C/Java) you do not need to use a function for structural purposes but rather to not call code or clarity.
Also Python automatically stops executing. Unlike (once again C/C++) you do not need to return anything.
In the case of:
if length > 1:
print(string_list)
elif length < 0:
print("Enter more than one string to sort")
return sys.exit()
Rather than printing (which might be considered bad practice) you can return the string:
if length > 1:
return string_list
elif length < 0:
return "Enter more than one string to sort"
Now to get it to print you can use print(main())
You should also ensure to end in either a plain if
or an else
statement. Ending with a elif
can return strange errors.
If you still need those two loops you could add an else
statement at the end and using the pass
function that does nothing:
if length > 1:
return string_list
elif length < 0:
return "Enter more than one string to sort"
else: pass
Once you move on to modules, you may want to execute code that can be executed and is also a module. This is where the other answer helps.
if __name__ == '__main__':
main()
This specifies if the name of the script (try running print(__name__)
in a script) is the main file (i.e. it's not getting called by another script) then only then will it execute by itself. Otherwise if imported main()
will not run.
Upvotes: 2
Reputation: 66
The standard idiom is useful here:
if __name__ == '__main__':
main()
Upvotes: 5