[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

Python assistance

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 17
Thread images: 2

Good evening. I would like some comments on my python code if any of you have time.

I am supposed to perform these tasks:
(1) Prompt the user for a string that contains two strings separated by a comma.
(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
(3) Using string splitting, extract the two words from the input string and then remove any spaces. Output the two words.
(4) Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.

Attached is my current code, but it does not pass all checks by the software. Please, let me know what you would do differently or what I have misunderstood and done incorrectly.
>>
>>352514
1) you don't pay by the letter. Use meaningful variable names.
2) (fw,sw)=l.split(......)
3) while:
____s=input.....
____if (s=="q"): exit
____if (',' in s): break

Pretty sure strip() only removes whitespace from the ends. You need to remove it from everywhere.
>>
Okay I cleaned up a little..

user_in = ''
while user_in != 'q':
user_in = input('Enter input string:')
if user_in == 'q': break
while not(',' in user_in) and user_in!='q':
print('Error: No comma in string.')
usr_in = input('Enter input string:')
new_text = user_in.replace(' ','')
user_text = new_text.split(",")
print('First word:', user_text[0])
print('Second word:', user_text[1])
>>
>>352529
Use pastebin you baka
>>
>>352514
Here's how I would have done it.
https://pastebin.com/S2p2K9n7
>>
>>352514
>>352529
Your second while inside your first while is fucking up your logic. Try inputting 'a' and then 'q'. The program will enter the inner while block and not test again for 'q', which it will then split into ['q'] and try to access user_text[1] which throws an IndexError because the list has a single element.

This should make it obvious to you why you shouldn't have an inner while reading input again. Test for the comma and 'q' separately, using break and continue to exit or restart the loop and read input again, like >>352540 is doing.

If you can't use continue because you haven't learned it yet, wrap everything in an if-then-else, so the while will naturally loop without doing anything else when you get a bad string. For example:

while user_in != 'q':
__user_in = input()
__if user_in != 'q':
____if ',' in user_in: parse_str_and_print()
____else: print_error()

This way if you get a 'q', you'll do nothing and the while will exit. If you get a bad string, you'll only print the error and continue. And if you get a good string, you'll parse it and print the output.

One more thing, since you said this is being tested by software: when the instructions tell you to output the two words, I'd recommend only printing the words themselves, without putting 'First/Second word:' before them.
>>
>>352604
>>352540

Third party here: I would be careful about using break and continue. When I was in school, we would get docked points/fail assignments if we got caught using them. Reason being that having multiple exit statements from a loop/method could cause trouble.

I would probably do something like:

While user input != 'q'
..Get user input
..if user input doesn't contain , then
....error message
..else
....print string 1 and string 2 (split by comma)
//End

You remove the early exits and get everything working as intended, I believe.
>>
>>353051
When I was in school, this was considered fine and no one cared. If your early break/continue causes a problem, that's on you. I'd understand if you were talking about gotos but break/continue is very common and useful.
>>
>>353051
The problem with that kind of an implementation is that it doesn't quit out when the user enters q. The conditional attached to the loop is only checked at the end of the loop so you shoot out the error before exiting (this would definitely dock you points). You pretty much have to use break/continue, especially if you want to write easily readable code (and if you don't, you shouldn't be using python in the first place).
>>
>>353056
My schooling was rather strict about that. Gotos were an insta-fail. We weren't even taught about it until assembly.

>>353057
Ah, you're right. But I disagree about needing the break/continue portion.

bool gate = false

While !gate
..Get user input
..if user input = 'q'
....gate = true
..else if user input doesn't contain , then
....error message
..else
....print string 1 and string 2 (split by comma)
//End

There. It uses 1 bit more, and will skip the error message.
>>
>>353062
Is it really worth avoiding using break when all you're doing is adding a fake conditional to replace it? It literally does the same thing but with less lines and more readability, plus it's the only exit condition, the loop is infinite until broken. Continue I can understand replacing with an if statement but I argue it's all about readability if you're using python.
The reason why you were probably taught the way you were was because the prof didn't want to see shit code that's a fucking mess to read. Goto statements are okay to use when needed and they should have told you that.
>>
>>353065
>Is it really worth avoiding using break when all you're doing is adding a fake conditional to replace it?
Honestly, yes. The official explanation (again) for being taught this way is that some larger end programs will have problems when the programmer tries to be fancy and break a statement early, and then the program runs into a problem when it runs into his break statement and returns early. It's easier to troubleshoot if you funnel the entire method down into one exit point instead of littering breaks in statements, especially if you're a beginner. I'd sacrifice "some" readability (and I can easily rename that temp boolean I made into something like "continueLoop = true" for the sake of having an easier to troubleshoot method and program.

Same thing with GoTo statements. GoTo statements are faster, but easy to fuck up, especially if you add code (by line number) or decide to change a label for readability. You should only use them if you HAVE to, and you can probably avoid it altogether with a method.
>>
>>353062
I went to [spoiler]MIT[/spoiler] and I can't think of any class where they said "you absolutely cannot do (thing) or you fail". That's a very simple-minded way to teach programming. If you explain why a certain thing is discouraged, then trust the programmer to do what's right, then you're fine. I guess it also helps(?) that most classes were not "(x) programming language", but "(subject matter), and we'll be using (x) so figure out how it works". Of course there's a primer for every language, but we'd never have a test specifically on that, because it's ancillary to the core subject material.
>>
File: gotofail[1].png (35KB, 660x300px) Image search: [Google]
gotofail[1].png
35KB, 660x300px
>>353069
There's nothing fancy about a break statement. And comparing it to goto is just silly.

I'm not saying that you weren't taught this way. I'm just saying, I think a lot of folks would disagree.
>>
>>353051
>>353102
Not only disagree, I'd say they'd go so far as to tell you you're wrong, and that you should stop contaminating young minds with your wrongness, and stop backing your wrongness up with appeals to authority like "I learned this in school".

You can see from the code in this thread that reimplementing break or return by hoisting conditions to the start of the loop or making "don't-loop-next-time" flag variables, or enclosing huge chunks of the loop in a condition to avoid using continue leads to uglier, more confusing code, and in effect you're still just using break/return/continue anyway, just you've written your own version that can't work without modifying loads of unrelated code.
>>
>>353102
A decent IDE or automatic formatter would have caught goto fail, because the second one would have the same indentation as the if statements.

I'm kind of surprised GCC didn't give a dead code warning for the stuff after the unconditional jump: JavaC does. Granted Java is easier for the compiler to analyse, but code after an unconditional goto and before any other label is always dead, and dead code is always a warning.
>>
>>353069
>some larger end programs will have problems when the programmer tries to be fancy and break a statement early, and then the program runs into a problem when it runs into his break statement and returns early. It's easier to troubleshoot if you funnel the entire method down into one exit point instead of littering breaks in statements, especially if you're a beginner.
That's a stupid reason, because all you do is go back one step in the debugger, and it'll show you the exact break statement it came from. If your debugger doesn't support reverse execution you can still put breakpoints on every break statement, and that'll achieve the same thing: tell you the point when your code changed from "work this thing out" to "give the result to the thing that asked for it".

Code written to have a single exit point still has a load of these transition points (they're intrinsic to the algorithm not the implementation), just you've hidden them in a bunch of flags and conditionals instead clearly marking them with a "break" or "return".
Thread posts: 17
Thread images: 2


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.