Program to accept numbers, then calculate the mean, median, and range
Clash Royale CLAN TAG#URR8PPP
up vote
4
down vote
favorite
I created a basic program that allows a user to continuously input values until he or she is satisfied; furthering, the program outputs the mean, median, and range. Then, the code gives you the option to run it again or exit.
#Mean, median, and range
from clear import *
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print('''
Great choice! Choose again or type stop the sequence.''')
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
def mean():
return 'Mean: ' + str(sum(list_one)/len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: ' + str(sum(list_one[length//2-1:length//2+1])/2)
else:
return 'Median: ' + str(list_one[length//2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
print(mean())
print(median())
print(range_())
break
else:
print('''
That's not a number or stop! Try again brudda man.
''')
def end():
while True:
q = input('Type anything and and press enter to repeat or press only 'Enter' to exit. ')
if len(q) >= 1:
main()
break
else:
exit()
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Additionally, the "clear" library that I imported is a custom library of my making which only prints out a ton of blank lines so the script "clears" and outputs are then at the bottom. If there is a better way of doing this please let me know.
I want to get familiar with what is "right" or "wrong" in terms of programming with Python. I would like my work to look professional and practice more respected coding ethics, so please be as harsh as you wish.
python beginner python-3.x statistics
New contributor
add a comment |Â
up vote
4
down vote
favorite
I created a basic program that allows a user to continuously input values until he or she is satisfied; furthering, the program outputs the mean, median, and range. Then, the code gives you the option to run it again or exit.
#Mean, median, and range
from clear import *
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print('''
Great choice! Choose again or type stop the sequence.''')
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
def mean():
return 'Mean: ' + str(sum(list_one)/len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: ' + str(sum(list_one[length//2-1:length//2+1])/2)
else:
return 'Median: ' + str(list_one[length//2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
print(mean())
print(median())
print(range_())
break
else:
print('''
That's not a number or stop! Try again brudda man.
''')
def end():
while True:
q = input('Type anything and and press enter to repeat or press only 'Enter' to exit. ')
if len(q) >= 1:
main()
break
else:
exit()
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Additionally, the "clear" library that I imported is a custom library of my making which only prints out a ton of blank lines so the script "clears" and outputs are then at the bottom. If there is a better way of doing this please let me know.
I want to get familiar with what is "right" or "wrong" in terms of programming with Python. I would like my work to look professional and practice more respected coding ethics, so please be as harsh as you wish.
python beginner python-3.x statistics
New contributor
1
You need to include your external custom libraries if you have them. We need COMPLETE CODE including any additional code libraries you wrote, includingclear
.
â Thomas Ward
28 mins ago
add a comment |Â
up vote
4
down vote
favorite
up vote
4
down vote
favorite
I created a basic program that allows a user to continuously input values until he or she is satisfied; furthering, the program outputs the mean, median, and range. Then, the code gives you the option to run it again or exit.
#Mean, median, and range
from clear import *
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print('''
Great choice! Choose again or type stop the sequence.''')
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
def mean():
return 'Mean: ' + str(sum(list_one)/len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: ' + str(sum(list_one[length//2-1:length//2+1])/2)
else:
return 'Median: ' + str(list_one[length//2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
print(mean())
print(median())
print(range_())
break
else:
print('''
That's not a number or stop! Try again brudda man.
''')
def end():
while True:
q = input('Type anything and and press enter to repeat or press only 'Enter' to exit. ')
if len(q) >= 1:
main()
break
else:
exit()
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Additionally, the "clear" library that I imported is a custom library of my making which only prints out a ton of blank lines so the script "clears" and outputs are then at the bottom. If there is a better way of doing this please let me know.
I want to get familiar with what is "right" or "wrong" in terms of programming with Python. I would like my work to look professional and practice more respected coding ethics, so please be as harsh as you wish.
python beginner python-3.x statistics
New contributor
I created a basic program that allows a user to continuously input values until he or she is satisfied; furthering, the program outputs the mean, median, and range. Then, the code gives you the option to run it again or exit.
#Mean, median, and range
from clear import *
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print('''
Great choice! Choose again or type stop the sequence.''')
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
def mean():
return 'Mean: ' + str(sum(list_one)/len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: ' + str(sum(list_one[length//2-1:length//2+1])/2)
else:
return 'Median: ' + str(list_one[length//2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
print(mean())
print(median())
print(range_())
break
else:
print('''
That's not a number or stop! Try again brudda man.
''')
def end():
while True:
q = input('Type anything and and press enter to repeat or press only 'Enter' to exit. ')
if len(q) >= 1:
main()
break
else:
exit()
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Additionally, the "clear" library that I imported is a custom library of my making which only prints out a ton of blank lines so the script "clears" and outputs are then at the bottom. If there is a better way of doing this please let me know.
I want to get familiar with what is "right" or "wrong" in terms of programming with Python. I would like my work to look professional and practice more respected coding ethics, so please be as harsh as you wish.
python beginner python-3.x statistics
python beginner python-3.x statistics
New contributor
New contributor
edited 47 mins ago
200_success
126k14146407
126k14146407
New contributor
asked 1 hour ago
Brandon
242
242
New contributor
New contributor
1
You need to include your external custom libraries if you have them. We need COMPLETE CODE including any additional code libraries you wrote, includingclear
.
â Thomas Ward
28 mins ago
add a comment |Â
1
You need to include your external custom libraries if you have them. We need COMPLETE CODE including any additional code libraries you wrote, includingclear
.
â Thomas Ward
28 mins ago
1
1
You need to include your external custom libraries if you have them. We need COMPLETE CODE including any additional code libraries you wrote, including
clear
.â Thomas Ward
28 mins ago
You need to include your external custom libraries if you have them. We need COMPLETE CODE including any additional code libraries you wrote, including
clear
.â Thomas Ward
28 mins ago
add a comment |Â
2 Answers
2
active
oldest
votes
up vote
2
down vote
Disclaimer: You asked me to be harsh, so I'm not holding back as much. I tried to though...
Welcome to Code Review! Your python code has been put through my scrutiny and I have some concerns and suggestions for improvement. Any criticisms and scrutiny are to be taken at their face value unless stated otherwise, and may include extremely harsh criticisms. I tried to avoid being overly harsh, but there are cases where I have to be harsh because of the severity of the mistakes or issues.
RED ALERT - MISSING CODE FROM PROGRAM!
Unknown Module, Code Not Available: clear
Your question could be closed because it does not have the complete code made available to us for review!
You state you wrote your own code for clear
. Guess what, we need that code too! You don't give us the code, so your program does not function at all, in any way, shape, and form. Because of this, your post violates the rules about having complete code examples and complete working code. We must have your clear
library in order to properly review your code.
The missing code for clear
aside, this is the review I have written so far:
from clear import *
: BAD FORM!
Wildcard imports are bad form! PEP8, the Style Guide for Python, explicitly discourages using wildcard imports.
To quote PEP8:
Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
You are not taking a private internal interface and republishing it for public API, so that doesn't apply. Replace any functions you're using from clear.*
with clear.FUNCTION
instead. This is so we know what module the specific bit(s) work with.
Alternatively, you can import the specific function with:
from clear import clear
... which would let you do clear()
calls like you have in your code. I have gone with this for the code example at the end.
Bad form: declaring modules inside your main() function
This isn't C, C++, or Java. You don't need to declare your functions within main()
. In fact, unless you are working with class
es and defining functions for a class, you should not be declaring your functions within a class. Take your mean
, median
, and range_
functions and declare them individually outside the main
class. Your general code structure would then look like this:
def mean():
...
def median():
...
def range_():
...
def main():
...
This is completely acceptable and in fact the proper way to do these types of declarations.
Unused Function: end()
You create the function end
but don't use it. Either leave it out entirely because its code is already written into the code that executes after main
, or replace the code after the main()
call with end()
. However, I would suggest that you do the second of these, rather than call (end) just to re-call main()
later.
You should not call main() directly, but instead use if __name__ == "__main__":
heading to call the code specifically, and call main() from within that.
This way, we can make sure that if we directly execute your Python code things properly get set or executed in sequence. While Python typically calls main()
, a lot of Python scripts and programs aren't written like Java or the likes and don't declare a main()
function. Therefore, if we write up everything under an if __name__ == "__main__":
line, we get everything inside that executed whenever we directly execute the program in Python.
This is as simple as putting all of your code that happens outside your function declarations under an if
, i.e.:
if __name__ == "__main__":
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Note that I am not using your end()
function here, because it's not worth it since we're going to just be re-executing main
anyways.
Use escape characters instead of triple-apostrophe strings when working with New Lines
You have this type of print statement at least twice:
print('''
Great choice! Choose again or type stop the sequence.''')
Functionally, this works, but from a code readability perspective, it's ugly. Replace this with escape-charactered strings instead, like:
print("nGreat choice! Chose again or type stop the sequence.")
This reads better to those of us doing the reviews.
Use string formatting rather than appending strings to other strings
Here's an example of what I'm talking about. You do this in many different places in the code:
return 'Mean: ' + str(sum(list_one)/len(list_one))
This works, but... string appending is not the nicest thing in the world. The proper way to do this nowadays, because you'll undoubtedly in the future have longer strings with multiple things needing inserted into it instead of just one thing at the end, is to use a format string. This'd be such as this:
return 'Mean: '.format(sum(list_one) / len(list_one))
This also reads slightly nicer because string casting just takes up extra characters and space. Also you'll note that with this I added some spaces around that /
- this makes math more readable, actually, to those of us doing reviews.
Use one print line instead of multiple
print
, when combined with strings and line endings and format
capable strings can actually post many things at once!
So let's take my last suggestion and turn your print
calls for mean, median, and range into one statement:
print("nn".format(mean(), median(), range_()))
We get to save some typing here, too, as well.
Consider including #!
(shebang) syntax at the first line
This way, we can call your Python code directly in command lines such as the Linux shell with ./file.py
and execute the code that way (if execute bit is set). This is not a requirement, but it's nice to have so I don't have to type python3 ./filename.py
or such to run your script.
I apologize if I was overly harsh, but you said not to hold back, and I gave you a warning early on. I tried to be as non-harsh as I could.
With all my suggestions above, you get something like this:
#!/usr/bin/python3
#Mean, median, and range
from clear import clear
def mean():
return 'Mean: ' + str(sum(list_one) / len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: '.format(sum(list_one[length // 2 - 1:length // 2 + 1]) / 2)
else:
return 'Median: '.format(list_one[length // 2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print("nGreat choice! Choose again or type stop the sequence.")
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
print("nn".format(mean(), median(), range_()))
break
else:
print("nThat's not a number or stop! Try again brudda man.")
if __name__ == "__main__":
main()
while True:
q = input("nType anything and and press enter to repeat or press only 'Enter' to exit. ")
if len(q) >= 1:
main()
else:
clear()
exit()
However, we need the code for your clear
module to be able to do a full and complete review, so this review is only partial until such time you provide us with that code.
add a comment |Â
up vote
1
down vote
On top of Thomas Ward answer, here is a short and importent comment:
More beautiful functions
Your functions are performing some mathematical computations and handling the formatting to show the result to the 2 users. These correspond to 2 concerns that could be separated.
Also, your functions rely on the list_one
global variable. It would be clearer to have this provided to the functions using an argument.
You'd have something like:
def mean(lst):
return sum(lst) / len(lst)
def range_(lst):
return lst[-1] - lst[0]
def median(lst):
length = len(lst)
mid = length // 2
if length % 2 == 0:
return sum(lst[mid-1:mid+1]) / 2
else:
return lst[mid]
...
print('Mean: ' + str(mean(list_one)))
print('Median: ' + str(median(list_one)))
print('Range: ' + str(range_(list_one)))
These are easier to understand and to reason about. There are also easier to test. This is an interesting exercise that you try to practice.
Nice catch, I did a fast review and caught the big problems rather than nitpicking in this case. +1'd!
â Thomas Ward
8 mins ago
add a comment |Â
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
2
down vote
Disclaimer: You asked me to be harsh, so I'm not holding back as much. I tried to though...
Welcome to Code Review! Your python code has been put through my scrutiny and I have some concerns and suggestions for improvement. Any criticisms and scrutiny are to be taken at their face value unless stated otherwise, and may include extremely harsh criticisms. I tried to avoid being overly harsh, but there are cases where I have to be harsh because of the severity of the mistakes or issues.
RED ALERT - MISSING CODE FROM PROGRAM!
Unknown Module, Code Not Available: clear
Your question could be closed because it does not have the complete code made available to us for review!
You state you wrote your own code for clear
. Guess what, we need that code too! You don't give us the code, so your program does not function at all, in any way, shape, and form. Because of this, your post violates the rules about having complete code examples and complete working code. We must have your clear
library in order to properly review your code.
The missing code for clear
aside, this is the review I have written so far:
from clear import *
: BAD FORM!
Wildcard imports are bad form! PEP8, the Style Guide for Python, explicitly discourages using wildcard imports.
To quote PEP8:
Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
You are not taking a private internal interface and republishing it for public API, so that doesn't apply. Replace any functions you're using from clear.*
with clear.FUNCTION
instead. This is so we know what module the specific bit(s) work with.
Alternatively, you can import the specific function with:
from clear import clear
... which would let you do clear()
calls like you have in your code. I have gone with this for the code example at the end.
Bad form: declaring modules inside your main() function
This isn't C, C++, or Java. You don't need to declare your functions within main()
. In fact, unless you are working with class
es and defining functions for a class, you should not be declaring your functions within a class. Take your mean
, median
, and range_
functions and declare them individually outside the main
class. Your general code structure would then look like this:
def mean():
...
def median():
...
def range_():
...
def main():
...
This is completely acceptable and in fact the proper way to do these types of declarations.
Unused Function: end()
You create the function end
but don't use it. Either leave it out entirely because its code is already written into the code that executes after main
, or replace the code after the main()
call with end()
. However, I would suggest that you do the second of these, rather than call (end) just to re-call main()
later.
You should not call main() directly, but instead use if __name__ == "__main__":
heading to call the code specifically, and call main() from within that.
This way, we can make sure that if we directly execute your Python code things properly get set or executed in sequence. While Python typically calls main()
, a lot of Python scripts and programs aren't written like Java or the likes and don't declare a main()
function. Therefore, if we write up everything under an if __name__ == "__main__":
line, we get everything inside that executed whenever we directly execute the program in Python.
This is as simple as putting all of your code that happens outside your function declarations under an if
, i.e.:
if __name__ == "__main__":
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Note that I am not using your end()
function here, because it's not worth it since we're going to just be re-executing main
anyways.
Use escape characters instead of triple-apostrophe strings when working with New Lines
You have this type of print statement at least twice:
print('''
Great choice! Choose again or type stop the sequence.''')
Functionally, this works, but from a code readability perspective, it's ugly. Replace this with escape-charactered strings instead, like:
print("nGreat choice! Chose again or type stop the sequence.")
This reads better to those of us doing the reviews.
Use string formatting rather than appending strings to other strings
Here's an example of what I'm talking about. You do this in many different places in the code:
return 'Mean: ' + str(sum(list_one)/len(list_one))
This works, but... string appending is not the nicest thing in the world. The proper way to do this nowadays, because you'll undoubtedly in the future have longer strings with multiple things needing inserted into it instead of just one thing at the end, is to use a format string. This'd be such as this:
return 'Mean: '.format(sum(list_one) / len(list_one))
This also reads slightly nicer because string casting just takes up extra characters and space. Also you'll note that with this I added some spaces around that /
- this makes math more readable, actually, to those of us doing reviews.
Use one print line instead of multiple
print
, when combined with strings and line endings and format
capable strings can actually post many things at once!
So let's take my last suggestion and turn your print
calls for mean, median, and range into one statement:
print("nn".format(mean(), median(), range_()))
We get to save some typing here, too, as well.
Consider including #!
(shebang) syntax at the first line
This way, we can call your Python code directly in command lines such as the Linux shell with ./file.py
and execute the code that way (if execute bit is set). This is not a requirement, but it's nice to have so I don't have to type python3 ./filename.py
or such to run your script.
I apologize if I was overly harsh, but you said not to hold back, and I gave you a warning early on. I tried to be as non-harsh as I could.
With all my suggestions above, you get something like this:
#!/usr/bin/python3
#Mean, median, and range
from clear import clear
def mean():
return 'Mean: ' + str(sum(list_one) / len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: '.format(sum(list_one[length // 2 - 1:length // 2 + 1]) / 2)
else:
return 'Median: '.format(list_one[length // 2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print("nGreat choice! Choose again or type stop the sequence.")
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
print("nn".format(mean(), median(), range_()))
break
else:
print("nThat's not a number or stop! Try again brudda man.")
if __name__ == "__main__":
main()
while True:
q = input("nType anything and and press enter to repeat or press only 'Enter' to exit. ")
if len(q) >= 1:
main()
else:
clear()
exit()
However, we need the code for your clear
module to be able to do a full and complete review, so this review is only partial until such time you provide us with that code.
add a comment |Â
up vote
2
down vote
Disclaimer: You asked me to be harsh, so I'm not holding back as much. I tried to though...
Welcome to Code Review! Your python code has been put through my scrutiny and I have some concerns and suggestions for improvement. Any criticisms and scrutiny are to be taken at their face value unless stated otherwise, and may include extremely harsh criticisms. I tried to avoid being overly harsh, but there are cases where I have to be harsh because of the severity of the mistakes or issues.
RED ALERT - MISSING CODE FROM PROGRAM!
Unknown Module, Code Not Available: clear
Your question could be closed because it does not have the complete code made available to us for review!
You state you wrote your own code for clear
. Guess what, we need that code too! You don't give us the code, so your program does not function at all, in any way, shape, and form. Because of this, your post violates the rules about having complete code examples and complete working code. We must have your clear
library in order to properly review your code.
The missing code for clear
aside, this is the review I have written so far:
from clear import *
: BAD FORM!
Wildcard imports are bad form! PEP8, the Style Guide for Python, explicitly discourages using wildcard imports.
To quote PEP8:
Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
You are not taking a private internal interface and republishing it for public API, so that doesn't apply. Replace any functions you're using from clear.*
with clear.FUNCTION
instead. This is so we know what module the specific bit(s) work with.
Alternatively, you can import the specific function with:
from clear import clear
... which would let you do clear()
calls like you have in your code. I have gone with this for the code example at the end.
Bad form: declaring modules inside your main() function
This isn't C, C++, or Java. You don't need to declare your functions within main()
. In fact, unless you are working with class
es and defining functions for a class, you should not be declaring your functions within a class. Take your mean
, median
, and range_
functions and declare them individually outside the main
class. Your general code structure would then look like this:
def mean():
...
def median():
...
def range_():
...
def main():
...
This is completely acceptable and in fact the proper way to do these types of declarations.
Unused Function: end()
You create the function end
but don't use it. Either leave it out entirely because its code is already written into the code that executes after main
, or replace the code after the main()
call with end()
. However, I would suggest that you do the second of these, rather than call (end) just to re-call main()
later.
You should not call main() directly, but instead use if __name__ == "__main__":
heading to call the code specifically, and call main() from within that.
This way, we can make sure that if we directly execute your Python code things properly get set or executed in sequence. While Python typically calls main()
, a lot of Python scripts and programs aren't written like Java or the likes and don't declare a main()
function. Therefore, if we write up everything under an if __name__ == "__main__":
line, we get everything inside that executed whenever we directly execute the program in Python.
This is as simple as putting all of your code that happens outside your function declarations under an if
, i.e.:
if __name__ == "__main__":
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Note that I am not using your end()
function here, because it's not worth it since we're going to just be re-executing main
anyways.
Use escape characters instead of triple-apostrophe strings when working with New Lines
You have this type of print statement at least twice:
print('''
Great choice! Choose again or type stop the sequence.''')
Functionally, this works, but from a code readability perspective, it's ugly. Replace this with escape-charactered strings instead, like:
print("nGreat choice! Chose again or type stop the sequence.")
This reads better to those of us doing the reviews.
Use string formatting rather than appending strings to other strings
Here's an example of what I'm talking about. You do this in many different places in the code:
return 'Mean: ' + str(sum(list_one)/len(list_one))
This works, but... string appending is not the nicest thing in the world. The proper way to do this nowadays, because you'll undoubtedly in the future have longer strings with multiple things needing inserted into it instead of just one thing at the end, is to use a format string. This'd be such as this:
return 'Mean: '.format(sum(list_one) / len(list_one))
This also reads slightly nicer because string casting just takes up extra characters and space. Also you'll note that with this I added some spaces around that /
- this makes math more readable, actually, to those of us doing reviews.
Use one print line instead of multiple
print
, when combined with strings and line endings and format
capable strings can actually post many things at once!
So let's take my last suggestion and turn your print
calls for mean, median, and range into one statement:
print("nn".format(mean(), median(), range_()))
We get to save some typing here, too, as well.
Consider including #!
(shebang) syntax at the first line
This way, we can call your Python code directly in command lines such as the Linux shell with ./file.py
and execute the code that way (if execute bit is set). This is not a requirement, but it's nice to have so I don't have to type python3 ./filename.py
or such to run your script.
I apologize if I was overly harsh, but you said not to hold back, and I gave you a warning early on. I tried to be as non-harsh as I could.
With all my suggestions above, you get something like this:
#!/usr/bin/python3
#Mean, median, and range
from clear import clear
def mean():
return 'Mean: ' + str(sum(list_one) / len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: '.format(sum(list_one[length // 2 - 1:length // 2 + 1]) / 2)
else:
return 'Median: '.format(list_one[length // 2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print("nGreat choice! Choose again or type stop the sequence.")
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
print("nn".format(mean(), median(), range_()))
break
else:
print("nThat's not a number or stop! Try again brudda man.")
if __name__ == "__main__":
main()
while True:
q = input("nType anything and and press enter to repeat or press only 'Enter' to exit. ")
if len(q) >= 1:
main()
else:
clear()
exit()
However, we need the code for your clear
module to be able to do a full and complete review, so this review is only partial until such time you provide us with that code.
add a comment |Â
up vote
2
down vote
up vote
2
down vote
Disclaimer: You asked me to be harsh, so I'm not holding back as much. I tried to though...
Welcome to Code Review! Your python code has been put through my scrutiny and I have some concerns and suggestions for improvement. Any criticisms and scrutiny are to be taken at their face value unless stated otherwise, and may include extremely harsh criticisms. I tried to avoid being overly harsh, but there are cases where I have to be harsh because of the severity of the mistakes or issues.
RED ALERT - MISSING CODE FROM PROGRAM!
Unknown Module, Code Not Available: clear
Your question could be closed because it does not have the complete code made available to us for review!
You state you wrote your own code for clear
. Guess what, we need that code too! You don't give us the code, so your program does not function at all, in any way, shape, and form. Because of this, your post violates the rules about having complete code examples and complete working code. We must have your clear
library in order to properly review your code.
The missing code for clear
aside, this is the review I have written so far:
from clear import *
: BAD FORM!
Wildcard imports are bad form! PEP8, the Style Guide for Python, explicitly discourages using wildcard imports.
To quote PEP8:
Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
You are not taking a private internal interface and republishing it for public API, so that doesn't apply. Replace any functions you're using from clear.*
with clear.FUNCTION
instead. This is so we know what module the specific bit(s) work with.
Alternatively, you can import the specific function with:
from clear import clear
... which would let you do clear()
calls like you have in your code. I have gone with this for the code example at the end.
Bad form: declaring modules inside your main() function
This isn't C, C++, or Java. You don't need to declare your functions within main()
. In fact, unless you are working with class
es and defining functions for a class, you should not be declaring your functions within a class. Take your mean
, median
, and range_
functions and declare them individually outside the main
class. Your general code structure would then look like this:
def mean():
...
def median():
...
def range_():
...
def main():
...
This is completely acceptable and in fact the proper way to do these types of declarations.
Unused Function: end()
You create the function end
but don't use it. Either leave it out entirely because its code is already written into the code that executes after main
, or replace the code after the main()
call with end()
. However, I would suggest that you do the second of these, rather than call (end) just to re-call main()
later.
You should not call main() directly, but instead use if __name__ == "__main__":
heading to call the code specifically, and call main() from within that.
This way, we can make sure that if we directly execute your Python code things properly get set or executed in sequence. While Python typically calls main()
, a lot of Python scripts and programs aren't written like Java or the likes and don't declare a main()
function. Therefore, if we write up everything under an if __name__ == "__main__":
line, we get everything inside that executed whenever we directly execute the program in Python.
This is as simple as putting all of your code that happens outside your function declarations under an if
, i.e.:
if __name__ == "__main__":
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Note that I am not using your end()
function here, because it's not worth it since we're going to just be re-executing main
anyways.
Use escape characters instead of triple-apostrophe strings when working with New Lines
You have this type of print statement at least twice:
print('''
Great choice! Choose again or type stop the sequence.''')
Functionally, this works, but from a code readability perspective, it's ugly. Replace this with escape-charactered strings instead, like:
print("nGreat choice! Chose again or type stop the sequence.")
This reads better to those of us doing the reviews.
Use string formatting rather than appending strings to other strings
Here's an example of what I'm talking about. You do this in many different places in the code:
return 'Mean: ' + str(sum(list_one)/len(list_one))
This works, but... string appending is not the nicest thing in the world. The proper way to do this nowadays, because you'll undoubtedly in the future have longer strings with multiple things needing inserted into it instead of just one thing at the end, is to use a format string. This'd be such as this:
return 'Mean: '.format(sum(list_one) / len(list_one))
This also reads slightly nicer because string casting just takes up extra characters and space. Also you'll note that with this I added some spaces around that /
- this makes math more readable, actually, to those of us doing reviews.
Use one print line instead of multiple
print
, when combined with strings and line endings and format
capable strings can actually post many things at once!
So let's take my last suggestion and turn your print
calls for mean, median, and range into one statement:
print("nn".format(mean(), median(), range_()))
We get to save some typing here, too, as well.
Consider including #!
(shebang) syntax at the first line
This way, we can call your Python code directly in command lines such as the Linux shell with ./file.py
and execute the code that way (if execute bit is set). This is not a requirement, but it's nice to have so I don't have to type python3 ./filename.py
or such to run your script.
I apologize if I was overly harsh, but you said not to hold back, and I gave you a warning early on. I tried to be as non-harsh as I could.
With all my suggestions above, you get something like this:
#!/usr/bin/python3
#Mean, median, and range
from clear import clear
def mean():
return 'Mean: ' + str(sum(list_one) / len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: '.format(sum(list_one[length // 2 - 1:length // 2 + 1]) / 2)
else:
return 'Median: '.format(list_one[length // 2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print("nGreat choice! Choose again or type stop the sequence.")
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
print("nn".format(mean(), median(), range_()))
break
else:
print("nThat's not a number or stop! Try again brudda man.")
if __name__ == "__main__":
main()
while True:
q = input("nType anything and and press enter to repeat or press only 'Enter' to exit. ")
if len(q) >= 1:
main()
else:
clear()
exit()
However, we need the code for your clear
module to be able to do a full and complete review, so this review is only partial until such time you provide us with that code.
Disclaimer: You asked me to be harsh, so I'm not holding back as much. I tried to though...
Welcome to Code Review! Your python code has been put through my scrutiny and I have some concerns and suggestions for improvement. Any criticisms and scrutiny are to be taken at their face value unless stated otherwise, and may include extremely harsh criticisms. I tried to avoid being overly harsh, but there are cases where I have to be harsh because of the severity of the mistakes or issues.
RED ALERT - MISSING CODE FROM PROGRAM!
Unknown Module, Code Not Available: clear
Your question could be closed because it does not have the complete code made available to us for review!
You state you wrote your own code for clear
. Guess what, we need that code too! You don't give us the code, so your program does not function at all, in any way, shape, and form. Because of this, your post violates the rules about having complete code examples and complete working code. We must have your clear
library in order to properly review your code.
The missing code for clear
aside, this is the review I have written so far:
from clear import *
: BAD FORM!
Wildcard imports are bad form! PEP8, the Style Guide for Python, explicitly discourages using wildcard imports.
To quote PEP8:
Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
You are not taking a private internal interface and republishing it for public API, so that doesn't apply. Replace any functions you're using from clear.*
with clear.FUNCTION
instead. This is so we know what module the specific bit(s) work with.
Alternatively, you can import the specific function with:
from clear import clear
... which would let you do clear()
calls like you have in your code. I have gone with this for the code example at the end.
Bad form: declaring modules inside your main() function
This isn't C, C++, or Java. You don't need to declare your functions within main()
. In fact, unless you are working with class
es and defining functions for a class, you should not be declaring your functions within a class. Take your mean
, median
, and range_
functions and declare them individually outside the main
class. Your general code structure would then look like this:
def mean():
...
def median():
...
def range_():
...
def main():
...
This is completely acceptable and in fact the proper way to do these types of declarations.
Unused Function: end()
You create the function end
but don't use it. Either leave it out entirely because its code is already written into the code that executes after main
, or replace the code after the main()
call with end()
. However, I would suggest that you do the second of these, rather than call (end) just to re-call main()
later.
You should not call main() directly, but instead use if __name__ == "__main__":
heading to call the code specifically, and call main() from within that.
This way, we can make sure that if we directly execute your Python code things properly get set or executed in sequence. While Python typically calls main()
, a lot of Python scripts and programs aren't written like Java or the likes and don't declare a main()
function. Therefore, if we write up everything under an if __name__ == "__main__":
line, we get everything inside that executed whenever we directly execute the program in Python.
This is as simple as putting all of your code that happens outside your function declarations under an if
, i.e.:
if __name__ == "__main__":
main()
while True:
q = input('''
Type anything and and press enter to repeat or press only 'Enter' to exit. ''')
if len(q) >= 1:
main()
else:
clear()
exit()
Note that I am not using your end()
function here, because it's not worth it since we're going to just be re-executing main
anyways.
Use escape characters instead of triple-apostrophe strings when working with New Lines
You have this type of print statement at least twice:
print('''
Great choice! Choose again or type stop the sequence.''')
Functionally, this works, but from a code readability perspective, it's ugly. Replace this with escape-charactered strings instead, like:
print("nGreat choice! Chose again or type stop the sequence.")
This reads better to those of us doing the reviews.
Use string formatting rather than appending strings to other strings
Here's an example of what I'm talking about. You do this in many different places in the code:
return 'Mean: ' + str(sum(list_one)/len(list_one))
This works, but... string appending is not the nicest thing in the world. The proper way to do this nowadays, because you'll undoubtedly in the future have longer strings with multiple things needing inserted into it instead of just one thing at the end, is to use a format string. This'd be such as this:
return 'Mean: '.format(sum(list_one) / len(list_one))
This also reads slightly nicer because string casting just takes up extra characters and space. Also you'll note that with this I added some spaces around that /
- this makes math more readable, actually, to those of us doing reviews.
Use one print line instead of multiple
print
, when combined with strings and line endings and format
capable strings can actually post many things at once!
So let's take my last suggestion and turn your print
calls for mean, median, and range into one statement:
print("nn".format(mean(), median(), range_()))
We get to save some typing here, too, as well.
Consider including #!
(shebang) syntax at the first line
This way, we can call your Python code directly in command lines such as the Linux shell with ./file.py
and execute the code that way (if execute bit is set). This is not a requirement, but it's nice to have so I don't have to type python3 ./filename.py
or such to run your script.
I apologize if I was overly harsh, but you said not to hold back, and I gave you a warning early on. I tried to be as non-harsh as I could.
With all my suggestions above, you get something like this:
#!/usr/bin/python3
#Mean, median, and range
from clear import clear
def mean():
return 'Mean: ' + str(sum(list_one) / len(list_one))
def median():
length = len(list_one)
if length % 2 == 0:
return 'Median: '.format(sum(list_one[length // 2 - 1:length // 2 + 1]) / 2)
else:
return 'Median: '.format(list_one[length // 2])
def range_():
return 'Range: ' + str(list_one[-1] - list_one[0])
def main():
clear()
list_one =
while True:
q = input('Type a number or type stop at any time: ').lower()
if q.isnumeric():
list_one.append(int(q))
print("nGreat choice! Choose again or type stop the sequence.")
elif q == 'stop':
list_one.sort(key=int)
print('''
And the values are...''')
print("nn".format(mean(), median(), range_()))
break
else:
print("nThat's not a number or stop! Try again brudda man.")
if __name__ == "__main__":
main()
while True:
q = input("nType anything and and press enter to repeat or press only 'Enter' to exit. ")
if len(q) >= 1:
main()
else:
clear()
exit()
However, we need the code for your clear
module to be able to do a full and complete review, so this review is only partial until such time you provide us with that code.
edited 10 mins ago
answered 24 mins ago
Thomas Ward
1,643722
1,643722
add a comment |Â
add a comment |Â
up vote
1
down vote
On top of Thomas Ward answer, here is a short and importent comment:
More beautiful functions
Your functions are performing some mathematical computations and handling the formatting to show the result to the 2 users. These correspond to 2 concerns that could be separated.
Also, your functions rely on the list_one
global variable. It would be clearer to have this provided to the functions using an argument.
You'd have something like:
def mean(lst):
return sum(lst) / len(lst)
def range_(lst):
return lst[-1] - lst[0]
def median(lst):
length = len(lst)
mid = length // 2
if length % 2 == 0:
return sum(lst[mid-1:mid+1]) / 2
else:
return lst[mid]
...
print('Mean: ' + str(mean(list_one)))
print('Median: ' + str(median(list_one)))
print('Range: ' + str(range_(list_one)))
These are easier to understand and to reason about. There are also easier to test. This is an interesting exercise that you try to practice.
Nice catch, I did a fast review and caught the big problems rather than nitpicking in this case. +1'd!
â Thomas Ward
8 mins ago
add a comment |Â
up vote
1
down vote
On top of Thomas Ward answer, here is a short and importent comment:
More beautiful functions
Your functions are performing some mathematical computations and handling the formatting to show the result to the 2 users. These correspond to 2 concerns that could be separated.
Also, your functions rely on the list_one
global variable. It would be clearer to have this provided to the functions using an argument.
You'd have something like:
def mean(lst):
return sum(lst) / len(lst)
def range_(lst):
return lst[-1] - lst[0]
def median(lst):
length = len(lst)
mid = length // 2
if length % 2 == 0:
return sum(lst[mid-1:mid+1]) / 2
else:
return lst[mid]
...
print('Mean: ' + str(mean(list_one)))
print('Median: ' + str(median(list_one)))
print('Range: ' + str(range_(list_one)))
These are easier to understand and to reason about. There are also easier to test. This is an interesting exercise that you try to practice.
Nice catch, I did a fast review and caught the big problems rather than nitpicking in this case. +1'd!
â Thomas Ward
8 mins ago
add a comment |Â
up vote
1
down vote
up vote
1
down vote
On top of Thomas Ward answer, here is a short and importent comment:
More beautiful functions
Your functions are performing some mathematical computations and handling the formatting to show the result to the 2 users. These correspond to 2 concerns that could be separated.
Also, your functions rely on the list_one
global variable. It would be clearer to have this provided to the functions using an argument.
You'd have something like:
def mean(lst):
return sum(lst) / len(lst)
def range_(lst):
return lst[-1] - lst[0]
def median(lst):
length = len(lst)
mid = length // 2
if length % 2 == 0:
return sum(lst[mid-1:mid+1]) / 2
else:
return lst[mid]
...
print('Mean: ' + str(mean(list_one)))
print('Median: ' + str(median(list_one)))
print('Range: ' + str(range_(list_one)))
These are easier to understand and to reason about. There are also easier to test. This is an interesting exercise that you try to practice.
On top of Thomas Ward answer, here is a short and importent comment:
More beautiful functions
Your functions are performing some mathematical computations and handling the formatting to show the result to the 2 users. These correspond to 2 concerns that could be separated.
Also, your functions rely on the list_one
global variable. It would be clearer to have this provided to the functions using an argument.
You'd have something like:
def mean(lst):
return sum(lst) / len(lst)
def range_(lst):
return lst[-1] - lst[0]
def median(lst):
length = len(lst)
mid = length // 2
if length % 2 == 0:
return sum(lst[mid-1:mid+1]) / 2
else:
return lst[mid]
...
print('Mean: ' + str(mean(list_one)))
print('Median: ' + str(median(list_one)))
print('Range: ' + str(range_(list_one)))
These are easier to understand and to reason about. There are also easier to test. This is an interesting exercise that you try to practice.
answered 9 mins ago
Josay
24.2k13781
24.2k13781
Nice catch, I did a fast review and caught the big problems rather than nitpicking in this case. +1'd!
â Thomas Ward
8 mins ago
add a comment |Â
Nice catch, I did a fast review and caught the big problems rather than nitpicking in this case. +1'd!
â Thomas Ward
8 mins ago
Nice catch, I did a fast review and caught the big problems rather than nitpicking in this case. +1'd!
â Thomas Ward
8 mins ago
Nice catch, I did a fast review and caught the big problems rather than nitpicking in this case. +1'd!
â Thomas Ward
8 mins ago
add a comment |Â
Brandon is a new contributor. Be nice, and check out our Code of Conduct.
Brandon is a new contributor. Be nice, and check out our Code of Conduct.
Brandon is a new contributor. Be nice, and check out our Code of Conduct.
Brandon is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f205845%2fprogram-to-accept-numbers-then-calculate-the-mean-median-and-range%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
1
You need to include your external custom libraries if you have them. We need COMPLETE CODE including any additional code libraries you wrote, including
clear
.â Thomas Ward
28 mins ago