Objective is to come out of 'final result while loop' (added as comment) once p1 or p2 wins. I have created a global flag which is initially False but once the winningfunc() returns result1 or result 2 equals to 3, flag is turned to True. I understand there might be verbose, but I am new to python or coding of any sort.   Trying to make a simple tic tac toe. Any help is appreciated :)  frame=[[" ","|"," ","|"," "],       ["-","-","-","-","-"],       [" ","|"," ","|"," "],       ["-","-","-","-","-"],       [" ","|"," ","|"," "]]  # Name assignment while True:     p1_name=input("Enter player 1 name: ")     p2_name=input("Enter player 2 name: ")      if p1_name.lower()==p2_name.lower():         print("Both names entered are same, please re-enter!")     else:         break # Notation assignment  while True:     p1_nt=input(f"{p1_name}, choose 'X' or 'O' to play with: ")     if p1_nt.lower()=="x":         p1_nt="X"         p2_nt="O"         print(f"{p1_name} will play with 'X' &amp; {p2_name} will play with 'O'")         break     elif p1_nt.lower()=="o":         p1_nt="O"         p2_nt="X"         print(f"{p1_name} will play with 'O' &amp; {p2_name} will play with 'X'")         break     else:         print("Entered notation is wrong, please re-enter!")  # dict  dc={"1":[4,0],"2":[4,2],"3":[4,4],"4":[2,0],"5":[2,2],"6":[2,4],"7":[0,0],"8":[0,2],"9":[0,4]}  # winning logic definition flag=False def winningfunc ():      def mf(v1,v2,v3):         result1=0         result2=0         for x in range(v1,v2,v3):             if frame[dc[str(x)][0]][dc[str(x)][1]]==p1_nt:                 result1+=1             elif frame[dc[str(x)][0]][dc[str(x)][1]]==p2_nt:                 result2+=1             else:                 pass         if result1==3:             flag=True             print(f"Congratulations, {p1_name} wins! ")                     elif result2==3:             flag=True             print(f"Congratulations, {p2_name} wins! ")                     else:             pass      mf(1,4,1) # for c4     mf(4,7,1) # for c2     mf(7,10,1) # for c0     mf(1,10,4) # for d1     mf(3,8,2) # for d2     mf(1,8,3) # for r0     mf(2,9,3) # for r2     mf(3,10,3) # for r3  # loop for payer input  while not flag: # for final result      while True: # for p1 data filling          s1=input(f"{p1_name} its your turn: ")         if 0&lt;=int(s1)&lt;=9 and frame[dc[str(s1)][0]][dc[str(s1)][1]]==" ":             if p1_nt=="X":                 frame[dc[str(s1)][0]][dc[str(s1)][1]]="X"             else:                 frame[dc[str(s1)][0]][dc[str(s1)][1]]="O"             break         else:             print(f"Wrong entry {p1_name}, try once again!")     x1=None             for x1 in range(len(frame)):         f1="".join(frame[x1])         print(f1)     # Result check for p1     winningfunc()           while True: # for p2 data filling          s2=input(f"{p2_name} its your turn: ")         if 0&lt;=int(s1)&lt;=9 and frame[dc[str(s2)][0]][dc[str(s2)][1]]==" ":             if p2_nt=="X":                 frame[dc[str(s2)][0]][dc[str(s2)][1]]="X"             else:                 frame[dc[str(s2)][0]][dc[str(s2)][1]]="O"             break         else:             print(f"Wrong entry {p2_name}, try once again!")      x2=None     for x2 in range(5):         f2="".join(frame[x2])         print(f2)     # Result check for p2         winningfunc()
4613
How can I create or use a global variable in a function?  If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
45840
How do I end a Tkinter program? Let's say I have this code:  from Tkinter import *  def quit():     # code to exit  root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop()   How should I define the quit function to exit my application?
55492
Title says it all.  Prove the statement is false with a counter-example:  For all sets S, T and V, V ∪ (S ∩ T) = (V ∪ S) ∩ T  Explain thoroughly if possible. I'm new to this
2897
Today, I was caught redhanded while attempting to code golf a password generator for Twitter.  import string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))   90 chars. Since that is a lot of spare space, I decided to raise the bar and make it executable too.  echo -e "#!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))"&gt;pg;chmod +x pg;./pg   139 chars. Nice, except obviously bash chokes on the exclamation point.  badp@delta:~$ echo -e "#!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))"&gt;pg;chmod +x pg;./pg bash: !/usr/bin/python\nimport: event not found   Pesky exclamation point. "Let's escape it," I thought! I do have one spare character after all.  echo -e "#\!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))"&gt;pg;chmod +x pg;./pg   Obviously...  badp@delta:~$ echo -e "#\!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))"&gt;pg;chmod +x pg;./pg ./pg: line 2: syntax error near unexpected token `(' ./pg: line 2: `import string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))' badp@delta:~$ cat pg #\!/usr/bin/python import string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))   Leaving my asinine code golfing aside -- I can't explain this.  With \!, the exclamation point was escaped, except it really wasn't, because the \! was left as-is for echo to pick up.  One solution could have been using \x21 instead, but I'm not convinced that's the proper way of escaping an exclamation point in a bash command.  tl;dr: How do you properly escape an exclamation point in a bash command?
78827
My brother recently started learning C++. He told me a problem he encountered while trying to validate input in a simple program. He had a text menu where the user entered an integer choice, if they entered an invalid choice, they would be asked to enter it again (do while loop). However, if the user entered a string instead of an int, the code would break. I read various questions on stackoverflow and told him to rewrite his code along the lines of:    #include&lt;iostream&gt; using namespace std;  int main() {     int a;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }     }while(true);     return 0; }   While this worked ok, I also tried a few other ideas: 1. Using a try catch block. It didn't work. I think this is because an exception is not raised due to bad input. 2. I tried if(! cin){//Do Something} which didn't work either. I haven't yet figured this one out. 3. Thirdly, I tried inputting a fixed length string and then parsing it. I would use atoi(). Is this standards compliant and portable? Should I write my own parsing function? 4. If write a class that uses cin, but dynamically does this kind of error detection, perhaps by determining the type of the input variable at runtime, would it have too much overhead? Is it even possible?  I would like to know what is the best way to do this kind of checking, what are the best practices?  I would like to add that while I am not new to writing C++ code, I am new to writing good standards compliant code. I am trying to unlearn bad practices and learn the right ones. I would be much obliged if answerers give a detailed explanation.  EDIT: I see that litb has answered one of my previous edits. I'll post that code here for reference.  #include&lt;iostream&gt; using namespace std;  int main() {     int a;     bool inputCompletionFlag = true;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }         else         {             inputCompletionFlag = false;         }     }while(!inputCompletionFlag);     return 0; }   This code fails on input like "1asdsdf". I didn't know how to fix it but litb has posted a great answer. :)
45967
I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards.  #include &lt;iostream&gt; #include &lt;vector&gt;  using namespace std;  int main() {     vector&lt;char&gt; deck;     char suit[] = {'h','d','c','s'};     char card[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'};     for (int j=0; j&lt;13; j++) {         for (int i=0; i&lt;4; i++) {             deck.push_back(card[j] suit[i]);         }            }      return 0; }   I know my problem begins with me trying to assign the value '10' to a char. Obviously I couldn't get this to compile but I'm sure when I try to assign the card values to the vector deck I'll also get an error since I used variable type 'char'. Knowing what kind of variable type to use seems to be killing me. Also, would 'deck.push_back(card[j] suit[i]);' be the correct code to combine the card and suit, or do you have to put something between card[j] and suit[i]? I'd appreciate it if any of you could lead me in the right direction. Also as a little side note, this is part of a homework assignment so please don't just give me entire blocks of code. Thanks for your help.
58428
In either case, one coin flip resulted in a head and the other resulted in a tail. Why is {H,T} a different outcome than {T,H}? Is this simply how we've defined an "outcome" in probability?   My main problem with {H,T} being a different outcome than {T,H} is that we apply binomial coefficients (i.e. we count subsets of sets) in some common probability problems. But if we take {H,T} and {T,H} to be different outcomes, then our "sets" are ordered, but sets are by definition unordered...   I feel as though the fact that I'm confused about something so basic means that I am missing something fundamental. Any help or insight whatsoever is greatly appreciated!
22738
You and I decide to play a game where we take turns flipping a coin. The first player to flip 10 heads in total wins the game. Naturally, there is an argument about who should go first.  Simulations of this game show that the player to flips first wins 6% more than the player who flips second (the first player wins approx 53% of the time).  I'm interested in modelling this analytically.  This isn't a binomial random variable, as there are no fixed number of trials (flip until someone gets 10 heads). How can I model this?  Is it the negative binomial distribution?    So as to be able to recreate my results, here is my python code:  import numpy as np from numba import jit   @jit def sim(N):      P1_wins = 0     P2_wins = 0      for i in range(N):          P1_heads = 0         P2_heads = 0         while True:              P1_heads += np.random.randint(0,2)              if P1_heads == 10:                 P1_wins+=1                 break              P2_heads+= np.random.randint(0,2)             if P2_heads==10:                 P2_wins+=1                 break     return P1_wins/N, P2_wins/N   a,b = sim(1000000)
12352
I just came onto a project with a pretty huge code base.   I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic.    if (!!variable &amp;&amp; (!!api.lookup("some-string"))) {        do_some_stuff();  }                                      I know these guys are intelligent programmers, it's obvious they aren't doing this by accident.   I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value.   Is this correct, or am I missing something?
60850
I often use this code pattern:  while(true) {      //do something      if(&lt;some condition&gt;) {         break;     }  }      Another programmer told me that this was bad practice and that I should replace it with the more standard:  while(!&lt;some condition&gt;) {      //do something  }      His reasoning was that you could "forget the break" too easily and have an endless loop. I told him that in the second example you could just as easily put in a condition which never returned true and so just as easily have an endless loop, so both are equally valid practices.  Further, I often prefer the former as it makes the code easier to read when you have multiple break points, i.e. multiple conditions which get out of the loop.  Can anyone enrichen this argument by adding evidence for one side or the other?
40162
Please demonstrate how the ternary operator works with a regular if/else block. Example:  Boolean isValueBig = value &gt; 100 ? true : false;     Exact Duplicate:
24489
#include &lt;stdio.h&gt; #include &lt;conio.h&gt; main() {     char ch,name[20];     int i=0;     clrscr();     printf("Enter a string:");     while((ch=getch())!='\n')     {         name[i]=ch;         i++;     }     name[i] = '\0';     printf("%s",name); }   When I give "abc" as input and if I press enter it's not working. Can anyone let me know why the condition ch=getch() != '\n' is not becoming false when I press enter? I have also observed that ch is taking \r instead of \n. Kindly let me know. Thanks
21860
I'm trying to debug a Python script by placing a print("foo=" + foo) statement in my code.  But where does the output appear?     It doesn't appear on the Python Console, and it doesn't appear on the area that appears when you drag the lower edge of the infobar downwards (what is the name for this area? My script errors show up in red here.)
12628
Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:  &gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2
53271
If I (as a user with vote-to-close privileges) click &quot;flag&quot; on a question, I see the ability to flag as &quot;does not belong here, or is a duplicate&quot;.  Is this a ? I'm quite sure I didn't used to be able to see that.   Anyway, if I use that (&quot;does not belong here, or is a duplicate&quot;) option and VtC the question, take a sip of my tea and continue about my daily business, upon submitting the &quot;flag&quot;, the counter for the &quot;flag&quot; button gets set, not the &quot;close&quot; button.   This would seem like a definite .
87827
I created a utility function to return the expected single item from an generator expression  print one(name for name in ('bob','fred') if name=='bob')   Is this a good way to go about it?  def one(g):     try:         val = g.next()         try:             g.next()         except StopIteration:             return val         else:             raise Exception('Too many values')     except StopIteration:         raise Exception('No values')
32772
In chapter 2, the section on bitwise operators (section 2.9), I'm having trouble understanding how one of the sample methods works.  Here's the method provided:  unsigned int getbits(unsigned int x, int p, int n) {     return (x &gt;&gt; (p + 1 - n)) &amp; ~(~0 &lt;&lt; n); }   The idea is that, for the given number x, it will return the n bits starting at position p, counting from the right (with the farthest right bit being position 0). Given the following main() method:  int main(void) {     int x = 0xF994, p = 4, n = 3;     int z = getbits(x, p, n);     printf("getbits(%u (%x), %d, %d) = %u (%X)\n", x, x, p, n, z, z);      return 0; }   The output is:     getbits(63892 (f994), 4, 3) = 5 (5)   I get portions of this, but am having trouble with the "big picture," mostly because of the bits (no pun intended) that I don't understand.  The part I'm specifically having issues with is the complements piece: ~(~0 &lt;&lt; n). I think I get the first part, dealing with x; it's this part (and then the mask) that I'm struggling with -- and how it all comes together to actually retrieve those bits. (Which I've verified it is doing, both with code and checking my results using calc.exe -- thank God it has a binary view!)  Any help?