Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] Looping a Program
#1
(Oct-05-2018, 07:36 PM)perfringo Wrote:
One way of doing it:

while True:
    print("Enter the name and scores of your students.")
    name = input("Enter name: ")
    while True:
        try:
            score = int(input("Enter score: "))
            if score in range(6):
                break
            else: 
                print('Only numbers 0 to 5 are acceptable!')
        except ValueError:
            print('Only numbers 0 to 5 are acceptable!')

    for i, v in enumerate(['F', 'E', 'D', 'C', 'B', 'A']):
        if i == score:
            grade = v

    print(f'{name} got a {grade}')
    repeat = input('Would you like to continue? Y/N ').lower()
    if repeat == 'y':
        continue
    else:
        break
This code will repeat only when user enter either 'Y' or 'y'. All other entries will end the program

  • Your solution contains redundant loop and else's
  • else on line 9 is redundant
  • Lines 14-16 may be replaced by
    grade = ['F', 'E', 'D', 'C', 'B', 'A'][score]
  • Line 20-23 may be rewritten as
    if repeat != 'y':
        break
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#2
(Oct-05-2018, 09:26 PM)volcano63 Wrote: Your solution contains redundant loop and else's

I agree with you that there are redundant loop and else's.

However, we should always keep in mind:

"Programs should be written for people to read, and only incidentally for machines to execute." Abelson and Sussman "Structure and Interpretation of Computer Programs"

"Explicit is better than implicit."

I have found useful (and there are some literature supporting this as well) to write out redundant parts of conditional statements. It's for letting readers of code know that writer of code didn't forget them (therefore line 9 should have been else: pass). Reader doesn't have to check whether missing clause is not needed or it's a bug.

Sure, it makes code more 'bloated', but computer doesn't care and if it may help some human to faster comprehend what code does, why not.

I am no software developer, I use Python for achieving results in another field. Therefore my viewpoint and style is probably not acceptable in professional setting. It's disputable even in non-professional setting Shy
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
(Oct-06-2018, 05:12 AM)perfringo Wrote:
(Oct-05-2018, 09:26 PM)volcano63 Wrote: Your solution contains redundant loop and else's

I agree with you that there are redundant loop and else's.

However, we should always keep in mind:

"Programs should be written for people to read, and only incidentally for machines to execute." Abelson and Sussman "Structure and Interpretation of Computer Programs"

"Explicit is better than implicit."

I have found useful (and there are some literature supporting this as well) to write out redundant parts of conditional statements. It's for letting readers of code know that writer of code didn't forget them (therefore line 9 should have been else: pass). Reader doesn't have to check whether missing clause is not needed or it's a bug.

Sure, it makes code more 'bloated', but computer doesn't care and if it may help some human to faster comprehend what code does, why not.

I am no software developer, I use Python for achieving results in another field. Therefore my viewpoint and style is probably not acceptable in professional setting. It's disputable even in non-professional setting Shy

Well, pardon my French, but those are poor excuses for showing bad coding practices Naughty . If you cannot give a good example - better to avoid showing your code as one. (BTW, I remember seeing an excellent Python code produced by geneticists in one of previous incarnations of the forum).

Since you don't care to learn best practices, I hope my comments will be useful as a warning to those trying to learn who stumble upon your code.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#4
(Oct-06-2018, 08:31 AM)volcano63 Wrote: those are poor excuses for showing bad coding practices Since you don't care to learn best practices, I hope my comments will be useful as a warning to those trying to learn who stumble upon your code.

First, I would like to make clear what we are talking about.

I think that your solution going directly to the object is superior to looping through objects to find needed one. No dispute here.

You are right that there was unnecessary repetition of string. I agree with that.

You consider else clause redundant. I accept this opinion and no dispute here as well.

However, I disagree with "those are poor excuses for showing bad coding practices" regarding else clause.

Following are my explanations (not excuses)

1. Programs are written for humans to read. I am as instance of human class find it easier to read. I have met other instances of that class who share this viewpoint.

2. Explicit is better than implicit. There is no performance penalty for machine to have 'redundant' branch. Explicitly stating that flow will either break or continue can be considered better than doing it implicitly.

3. Programming is expressing ideas. "In reality, programming languages are how programmers express and communicate ideas — and the audience for those ideas is other programmers, not computers. The reason: the computer can take care of itself, but programmers are always working with other programmers, and poorly communicated ideas can cause expensive flops. In fact, ideas expressed in a programming language also often reach the end users of the program — people who will never read or even know about the program, but who nevertheless are affected by it." (Kings Day Speech by Guido van Rossum). I think that using 'redundant for computer' else clause in flow control helps me to communicate my idea better to other humans (but by all means, I am not a programmer)

4. As mentioned earlier, there are some literature which have something to say about else-clause in if statement:

Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code, First Edition by Zed Shaw, Exercise 36. Designing and Debugging (average rating 4.5 on safaribooksonline.com)

"Every if-statement must have an else. If this else should never run because it doesn’t make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors."

Code Complete by Steve McConnell, 2nd edition, chapter 15, Using Conditionals (average rating 4.7 on safaribooksonline.com)

"Consider the else clause. If you think you need a plain if statement, consider whether you don't actually need an if-then-else statement. A classic General Motors analysis found that 50 to 80 percent of if statements should have had an else clause (Elshoff 1976).

One option is to code the else clause—with a null statement if necessary—to show that the else case has been considered. Coding null elses just to show that that case has been considered might be overkill, but at the very least, take the else case into account. When you have an if test without an else, unless the reason is obvious, use comments to explain why the else clause isn't necessary"

(I do realise that what is obvious to one person may be not so obvious to another person)

It seems to me that there are circumstances and examples where using redundant-for-computer else clause can not be considered as bad coding practice.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
(Oct-07-2018, 09:00 AM)perfringo Wrote: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code, First Edition by Zed Shaw, Exercise 36. Designing and Debugging (average rating 4.5 on safaribooksonline.com)

"Every if-statement must have an else. If this else should never run because it doesn’t make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors."

Code Complete by Steve McConnell, 2nd edition, chapter 15, Using Conditionals (average rating 4.7 on safaribooksonline.com)

"Consider the else clause. If you think you need a plain if statement, consider whether you don't actually need an if-then-else statement. A classic General Motors analysis found that 50 to 80 percent of if statements should have had an else clause (Elshoff 1976).

One option is to code the else clause—with a null statement if necessary—to show that the else case has been considered. Coding null elses just to show that that case has been considered might be overkill, but at the very least, take the else case into account. When you have an if test without an else, unless the reason is obvious, use comments to explain why the else clause isn't necessary"

(I do realise that what is obvious to one person may be not so obvious to another person)

It seems to me that there are circumstances and examples where using redundant-for-computer else clause can not be considered as bad coding practice.

Never read any - but I have nearly 3 decades of programming experience and more than 6 years of Python experience, and I tell you that
Quote:Every if-statement must have an else
is pure undiluted bullshit.

I do not care much for 40+ years old
Quote:A classic General Motors analysis found that 50 to 80 percent of if statements should have had an else clause
either - 30% margin is so convincing.

Let me teach you a simple KISS imperative - Keep It Simple Stupid. Using a loop instead of indexing is extremely stupid - but not simple. I have no intention to continue this argument - but your arguments are pure demagoguery without any value.

I wish you would invest as much effort into learning proper Python as you invest in this argument. Intellectual laziness is not a commendable value. Hijacking threads for defending bad practices is not appreciated in programming community either,
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#6
Maybe it's still not clear what I am talking about (pardon my French). I said: "I have found useful (and there are some literature supporting this as well) to write out redundant parts of conditional statements".

So instead of of snippet suggested by you:

if repeat != 'y':
    break
I find useful to use this:

if repeat == 'y':
    continue
else:
    break
If you read my comments you should have noticed that I agreed with your other observations. It also can be verified that I only claimed: "It seems to me that there are circumstances and examples where using redundant-for-computer else clause can not be considered as bad coding practice." accompanied with my considerations and references to back it up.

Still, we haven't had any argument.

"poor excuses for showing bad coding practices", "you don't care to learn best practices", "Never read any", "I have nearly 3 decades of programming experience and more than 6 years of Python experience", "is pure undiluted bullshit.", "I do not care much for 40+ years old".

Where are the arguments?

You have an opinion but fall short of explaining why your judgement should be preferred. You fail to explain why is it the bad coding practice; what is the best practice and why.

One of the moderators of this site has very good quote from Albert Einstein as his signature: "If you can't explain it to a six year old, you don't understand it yourself.". As father of four I can't agree more (of course, one can have attitude that 'I dont care much for opinion of person 60+ years dead').

Just to put it another way: lot of things can go wrong if you follow blindly advice of some anonymous bloke/sheila off the internet.

I have a feeling that you are attacking the messanger, not the message ("Intellectual laziness is not a commendable value", "your arguments are pure demagoguery without any value", , "Hijacking threads for defending bad practices is not appreciated in programming community either").

I may be intellectually lazy (it should enable intellectually sharp person to show that I am wrong quite easily and without using words stupid and bullshit); I may use demagoguery (it should make proving me wrong very easy); I may defend bad habits (it should make it easy to demonstrate why my position is undefendable) and so what? Does it mean that because I am a stupid person with bad habits my opinion should disrespected without consideration? Am I not entitled to the explanation why I am wrong? I don't want to go any deeper into 'demagoguery' but you can ask yourself how do they call people who judge persons based what they are and not what they do.

Oh, and we shouldn't forget the gorilla in the room (Raymond Hettinger talk at PyCon 2015)

To sum it up: You pinpointed sloppiness in my code and showed ways to improve it. I appreciate that. However, I will not follow your (or somebody else's) advice or judgement blindly and without explanation. I don't buy this: 'it's bad because I say so and you are too stupid to understand it'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
Since I keep getting notifications about this thread, I feel inclined to comment. Neither of you are necessarily wrong; you have two different design philosophies. Between the two of you though, I find volcano's perspective more appealing (though delivered without tact).

Else clauses that don't provide instructions, such as "else: pass" are devoid of value. Imagine that someone provides the following bit of advice: "If it is raining, bring an umbrella." Do you need to also hear: "Otherwise, do whatever you'd like, the presence of an umbrella is not significant because it is not raining"? The condition for rain insinuates an exception to the rule that you do not need an umbrella. Essentially, if it is not raining, you can ignore the conditional altogether and move on.

Using the continue keyword at the end of a loop is also devoid of value. When working inside a loop, interpreter returns to the beginning of the loop once the body has been completed. Because the loop must be explicitly declared at its start, the inherent behaviors of it are arguably explicit as well (however, you could argue that those behaviors are an implicit rule of the language which is why "Explicit is better than implicit" is in the Zen of Python). Therefore, the following pattern has no usefulness:

while True:
    ...code...
    if True:
        continue
Conversely, the following pattern does have value because it alters the expected behavior of the code by terminating the loop:

while True:
    ...code...
    if True:
        break
The continue keyword only has value when it appears prior to the end of the loop body to skip the remainder of the body and start the next iteration. As a result, this conditional at the end of a loop

if repeat == 'y':
    continue
else:
    break
offers little to the code while saying too much. Because the instruction when the conditional is true is to continue the loop, I don't care about the conditional being true. Continuing the loop would have happened by default because of my explicitly declared loop. I only care about the instruction that contravenes the known behavior of the loop, which only happens when anything other than "y" has been inputted. As such, this version simplifies the conditional and tells me what I care to know without stating the obvious:

if repeat != 'y':
    break
Reply
#8
+1 to not requiring elses to ifs. I don't feel strongly enough about it to make you feel bad or call you names, but I do feel that I should throw in my intuition that it's unnecessary noise, and say that you will probably agree after a few months of Python. While I'm sympathetic to wanting code to be as legible for beginners as experienced folks, I feel like you learn to understand the code fairly fast and it's not worth bogging everyone down. Do with this intuition what you will.

I don't expect everyone to know about this, but Ed Shaw is not an authority on Python. His tutorial is popular and might not be entirely bad, but there are pretty serious criticisms of him that mean I would recommend learning Python from a shell before using his tutorial. Unfortunately I can't find it, but I know there was a good thread that went into detail. Anyone seeing this should feel free to link to it.

(Oct-08-2018, 02:38 PM)stullis Wrote: delivered without tact
+1. This is a learning forum, and I learned (here) this lesson at the cost (I'm sure) of a lot of people learning better.

Overall, I find the general practices for Python to be quite readable, and I believe they're good. To do any better I would suggest functional programming (which I don't find easy in Python), but I'm probably in the minority there :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Results of this program in an excel file eisamabodian 1 1,543 Feb-11-2022, 03:18 PM
Last Post: snippsat
  Need help looping this program JakobeTheKid 1 2,073 May-19-2019, 05:30 AM
Last Post: SheeppOSU
  Looping a Program DavidRobinsons 4 3,485 Oct-09-2018, 12:14 AM
Last Post: micseydel
  [split] Coin Flip Program Crackity 5 4,734 Sep-25-2017, 03:48 AM
Last Post: Crackity

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020