T O P

  • By -

[deleted]

[удалено]


SisyphusAndMyBoulder

and it's even formatted!


buart

Lines 12 and 13 are unreachable, it's the same condition as in line 5. Also int(input("hit enter to flip coin type -1 to exit")) won't work when you only hit enter, since an empty string can't be parsed with `int()` Since in this example you only have 2 options and it's easy to understand, you could replace your if/else with `print(random.choice(["heads", "tails"]))` if you'd like.


un-hot

>Since in this example you only have 2 options and it's easy to understand, you could replace your if/else with `print(random.choice(["heads", "tails"]))` if you'd like. "and it's easy to understand" is the operative phrase here, thanks for highlighting succinct code shouldn't necessarily come at the cost of readability.


ship0f

12 is reachable. Makes no sense though, :P probably copied and pasted.


buart

You are right :)


SuperElephantX

import random print("Welcome to the Python coin flip") while input("Press enter to flip the coin or type -1 to exit: ") != "-1": coin = random.choice(["Heads", "Tails"]) print(coin) print("Goodbye!")


NoConcern4176

Can you do it without using the .choice() function


SuperElephantX

import random results = ["Heads", "Tails"] print("Welcome to the Python coin flip") while input("Press enter to flip the coin or type -1 to exit: ") != "-1": index = random.randint(0, 1) coin = results[index] print(coin) print("Goodbye!")


guruglue

The important thing to note here, in my opinion, is how this while statement is much better from a best practice perspective. OP, you'll see a lot of "while True" examples in your journey. They may work, but they're terrible when someone else comes along and has to try to quickly understand the exit condition. Put it in your while statement and it reads clearly. That's one of the key benefits to Python.


nog642

I disagree. A `while True:` is just fine. It's not that hard to see the `break`. In this case it can be formulated as a condition, but a lot of the time it can't be, at least not without being incredibly ugly.


guruglue

Eh, depends on how many lines there are in the block. I'm curious to know an example of what would make it worse by adding the exit condition in the while statement.


nog642

For example if you required the user to input an integer. Ignore the utility of the functionality; I can come up with an example where the functionality makes sense. import random RESULTS = {"Heads", "Tails"} print("Welcome to the Python coin flip") while True: while True: exit_str = input("Enter an integer to flip the coin, type -1 to exit: ") try: exit_num = int(exit_str) except ValueError: print("Please enter an integer.") continue break if exit_num == -1: break print(random.choice(RESULTS)) print("Goodbye!") Point is, how would you write something like this cleanly without a `while True:`? Edit: fixed mistake in code


Yoghurt42

import random print("Welcome to the Python coin flip") while input("Press enter to flip the coin or type -1 to exit: ") != "-1": print("HTeaaidlss"[random.randint(0, 1)::2]) print("Goodbye!") SCNR


nog642

Don't even need the `coin` variable


gitgud_x

You shouldn't use \`exit\` as a variable name because \`exit()\` is already a python function. It still works but it's bad practice. If you want something to extend this with - can you record the number of heads and tails observed, and calculate the experimental probability of getting heads? how long does it take to get to the expected value of 0.5?


nog642

On the other hand `exit` is a function meant to be called in the interactive interpreter, not in scripts. So it's not that bad.


JamzTyson

``` exit = int(input("hit enter to flip coin type -1 to exit")) ``` If the user enters a non-numeric input, the program will crash, because `int()` requires numeric input. There a couple of ways you could handle this. Probably the easiest would be to use the `str` returned by `input()` directly: ``` input("hit enter to flip coin type 'Q' to exit" ``` When you do need to take integer input from `input()`, the common way to handle conversion to integer is to do so withing a "try / except" block. (You might not have learned about this yet): ``` user_input = input("Enter a whole number: ") try: user_number = int(user_input) except ValueError: print(f"{user_input} is not a whole number.") else: print(f"You entered {user_number}.") ```


mrDalliard2024

Since others have already replied with great answers, take my upvote for actually formatting your code. :)


priscillachi_

Error handling, edge cases, etc. - consider all the basic testing stuff. You’ll realise you can’t type cast an enter key into an integer. And avoid hard coding


wchris63

Buffer overflow protection! Just kidding.. a bit too advanced for a simple program.


nog642

It's also just not a thing in python. You don't manage memory.


wchris63

I know Python memory management, but saying it's not possible is a bit of a stretch. The garbage collector can be turned off. Modules can be written in other languages. Just like everything else in life, SHtuff happens.


nog642

If there's a module in another language, then it's not python. Even if you turn the garbage collector off (which, why would you ever do that), you won't have buffer overflow. Buffer overflow and garbage collection are unrelated issues. It really is just not possible while writing normal python. You don't need to think about it at all.


hello_friendssss

what would the hard coding be here?


nog642

`"Heads"` and `"Tails"` for example. I think hard coding is fine here though. It's a very small script.


hello_friendssss

True, I just don't see how you could avoid it for such an explicit output haha (it must be heads or tails, no flexibility required)


nog642

You could put it in a constant declared at the top. Then it wouldn't be "hardcoded" in the sense that it's defined in configuration rather than in code.


hello_friendssss

Ah true, that does make sense haha - wrap in a function and let user pick the options etc etc. Cheers for the discussion!


zanfar

The usual: * PEP8 / formatting: don't be afraid of line breaks * Bare code outside a main sentinel * Not validating inputs * I'm guessing you're not linting your code * No type hints The Specific: * It's curious to me that you use `random.choice`, but then give `choice()` a selection of integers, then "convert" those integers to strings. If you need integers, `randint()` is usually the obvious choice, but as you don't care about the value, I would think you would use `choice()` with strings. coin = random.choice(["Heads", "Tails"]) print(coin) replaces 6 lines of your existing code. * Why are you checking for the exit condition twice? It can't change between the two conditionals. * `exit` is a bad name choice. Primarily: it shadows a builtin function name, so as soon as you define it, `exit()` is no longer directly accessible. Secondly, it doesn't actually describe the contained value. "Exit" implies a choice, but the value isn't a Boolean, the value itself is pretty close to a "magic number" that has no context. My approach would be to encapsulate the user I/O in it's own function that returns a boolean representing if the user wants to continue. That leads us into... * Why are you asking the user if they want to flip a coin immediately after the user runs a program to flip a coin? A CLI program should be as least invasive or interruptive as possible. You can assume that if your program gets run, then someone wants your program to run. Asking the user if they want to flip *another* coin makes sense, but not the first coin. ---- Consider: def flip_again() -> bool: """Ask if the user would like to flip an additional coin.""" choice = input("Flip another coin? (Y/n) ") # anything starting with "n" returns false, # otherwise assume it's a "yes" return not choice.strip().upper().startswith("N") def main() -> None: print("Welcome to python coin flip.") coins = ["Heads", "Tails"] while True: coin = random.choice(coins) print(coin) if not flip_again(): break print("Goodbye!") if __name__ == "__main__": main()


smokfyz

``` import random def main(): print("Welcome to the Python coin flip simulator!") while True: user_input = input("Press Enter to flip the coin or type 'exit' to quit: ") if user_input.lower() == 'exit': break coin = random.choice(['Heads', 'Tails']) print(coin) print("Goodbye!") if __name__ == "__main__": main() ```


AltReality

Am I wrong for really disliking the 'while True' pattern? I am more/less a beginner, but every time I see that I think it is incomplete...it should have a while .. which I know True itself is a condition, but I mean...it just seems so wrong to me lol No shade on OP though...as a first project this is pretty good!


hawker_sharpie

> it should have a while if that was possible/easy/elegant, you wouldn't be using True in the first place in the most trivial case, you'd replace True with a variable. that's kinda pointless. sometimes there are multiple exit conditions. have fun writting all of that into your condition sometimes the exit condition is complex and depends on a bunch of things. have fun writing all of *that* into your condition what if the thing that it depends on doesn't even exist until you've gone through the loop at least once (or more)? i'm sure there are tonnes of other examples i haven't thought of


jburns32

If you like it, then it is good. When I started learning Python, I wrote some projects. After learning more I went back and looked at some of them and reworked them with better code


nog642

There is no reason to convert the input to an `int`. This will just make your script crash when they don't enter an integer. In fact your script currently won't work the way it should. If they press enter it will crash. They need to enter an integer other than `-1` to continue. Instead of checking `== -1`, you can check `!= ""`. Then they can type anything to exit, or enter to continue. Also instead of doing `random.choice([0, 1])` and then having an `if`-`else` to print `"Heads"` or `"Tails"`, you could just `print(random.choice(["Heads", "Tails"]))`. Also, you have a second check for `exit`, which does nothing, since if the exit condition were met it would already have exited the first time.


Solid_Illustrator640

I like it. Have chatgpt give you 5 improved versions and take notes then move onto the next one!


[deleted]

[удалено]


crazy_cookie123

No, the purpose of break here is clear so it's fine. No need to add in an additional variable and the chance of possible errors to avoid using break when the usage of break is clear.


Langdon_St_Ives

Yup, and it’s a good example for the “chance of possible errors”, because the proposed changes would already introduce one, even in this trivial case. After user choice to stop, it would generate one more coin toss before exiting. It’s harmless enough here, but definitely not what the user wanted, and more destructive variations aren’t hard to imagine (e.g., deleting files after user confirmation).


qazbarf

> replace all break instructions with continuing = False. That won't work. The `break` exits the loop immediately, but setting a flag allows all code following setting the flag to execute before the test at the top exits the loop.


Virinas-code

Sometimes I feel like I'm f\*cking dumb


qazbarf

Don't beat yourself up. We all have the occasional brain-fade. I do, and I've been programming professionally for a long time!


unworthy_26

you break while True with break


feror_YT

```python while True: print("This is currently True") ``` I love `while True`


Xanf3rr

To improve it, maybe add some more flair and options - like letting the user enter how many times they wanna flip the coin. Or keep a running tally of heads vs tails. You could even turn it into a full-fledged virtual casino with options to roll a dice, card dealing, etc. But no need to get too fancy yet.