Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Coin Flip Program
#1
Not sure where I went wrong. I was trying to learn functions. By making a simple coin flip program and ran into a snag. Deleted my 50 extra imports :)

#! /usr/bin/python

# IMPORTS
import random

# Globals
CoinSideNames = ""

# FUNCTIONS
def CoinFlip():
    CoinSide = random.randint(-1,1)
    
    while CoinSide == 0 :
       CoinSide = random.randint(-1,1)
       print ("Inside Function CoinSide ", CoinSide)

    CoinSideName(CoinSide)
    

def CoinSideName(CoinSide):
    print ("Inside Function CoinSideName ******")
    if CoinSide == -1 :
        CoinSideNames ="Tails"
        print ("Inside Function CoinSideName ", CoinSideNames)
    elif CoinSide == 1 :
        CoinSideNames ="Heads"
        print ("Inside Function CoinSideName ", CoinSideNames)
        
    return CoinSideNames
    
    


# START
print("Welcome to my Coin flip game")

command=""


while command != "Exit" or command != "e" or command != "E" :

    command = input("Choose Heads, Tails,Start or Exit.")
    
    if command =="Exit" or command =="exit" or command =="E" or command =="e"  :
        break
       
    CoinFlip()
    
    
    print("The Coin Landed Showing " + CoinSideNames)

    
    
My output is this.

Welcome to my Coin flip game
Choose Heads, Tails,Start or Exit.s
Inside Function CoinSideName ******
Inside Function CoinSideName  Heads
The Coin Landed Showing
Choose Heads, Tails,Start or Exit.

I was wondering why

    print("The Coin Landed Showing " + CoinSideNames)

Doesn't Show me The CoinSideNames
Reply
#2
use:
   print("The Coin Landed Showing {}".format(CoinSideNames))
Reply
#3
You've got two CoinSideNames variable. One is in the global scope and is set to "" (an empty string). The other is local to your CoinSideName function. Variables created in a function only live in that function, and don't interfere with variables elsewhere. This is useful when you are writing a lot of functions, so you don't have to worry so much what variable names you use.

To get the variable from the CoinSideName function outside of the function, you would use return CoinSideNames. Then outside the function, you would catch the returned value with an assignment statement:
CoinSideNames = CoinSideName()
Your coin flip function is kind of odd. If you want the possible results to be either -1 or 1, use random.choice() instead:
CoinSide = random.choice([-1, 1])
Your while loop is also odd. You have the condition twice, once on the while loop and once on the if statement for the break. You can also simplify the condition with the lower method and the in operator:
while True:
    command = input("Choose Heads, Tails,Start or Exit.")
    if command.lower() in ('exit', 'e'):
        break
    # do the coin flip
Using the lower method to convert things to lower case is the standard Python way to do case insensitive comparisons. The in operator allows you to test is the left hand value is one of the right hand values.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
I appreciate the help but I seem not to be understand the correction you wanted me to make.

It appears my function calls the CoinSideNames Function Correctly

And CoinSideName Function

has return CoinSideNames

Now how do I transfer the value
back to the program

to make
print("The Coin Landed Showing " + CoinSideNames)
 
CoinSideNames have the value Heads or Tails

Here is my re-edit code
#! /usr/bin/python

# IMPORTS
import random

# Globals

global CoinSideNames

CoinSideNames =""
 
# FUNCTIONS
def CoinFlip():
    CoinSide = random.randint(-1,1)
     
    while CoinSide == 0 :
       CoinSide = random.randint(-1,1)
       print ("Inside Function CoinFlip ", CoinSide)
 
    CoinSideNames = CoinSideName(CoinSide)
    
    print ("Inside Function CoinFlip after CoinSideName call ", CoinSideNames)
    return CoinSideNames

 
def CoinSideName(CoinSide):
    print ("Inside Function CoinSideName ******")
    if CoinSide == -1 :
        CoinSideNames ="Tails"
        print ("Inside Function CoinSideName ", CoinSideNames)
    elif CoinSide == 1 :
        CoinSideNames ="Heads"
        print ("Inside Function CoinSideName ", CoinSideNames)
         
    return CoinSideNames
     
     
 
 
# START
print("Welcome to my Coin flip game")
 
command=""
 
 
while command != "Exit" or command != "e" or command != "E" :
 
    command = input("Choose Heads, Tails,Start or Exit.")
     
    if command =="Exit" or command =="exit" or command =="E" or command =="e"  :
        break
        
    CoinFlip()
    CoinSideNames = CoinSideName(CoinSide) 
     
    print("The Coin Landed Showing " + CoinSideNames)
 
I thank you both for taking the time to help me and I haven't ignored the other improvements you offer to my code. I want to crack this one problem first

Output:
Welcome to my Coin flip game Choose Heads, Tails,Start or Exit.q Inside Function CoinSideName ****** Inside Function CoinSideName  Tails Inside Function CoinFlip after CoinSideName call  Tails Traceback (most recent call last):   File "C:/Users/Slim 960/Desktop/Python/Python Projects/Coin Flipper/CoinFlipGame.py", line 101, in <module>     CoinSideNames = CoinSideName(CoinSide) NameError: name 'CoinSide' is not defined
Reply
#5
You're right, I had the structure of your program wrong. You call CoinSideName from CoinFlip. So you need to capture that value with an assignment in CoinFlip, and then return that value from CoinFlip. I see that you have already done that in your revised code. And you tried to do the same thing in the while loop, to get the value out of CoinFlip and into the while loop. The correct way to do that is:
CoinSideNames = CoinFlip()
And then you can remove line 54, which is giving you the error. Although in your error code it's referencing line 101. To be clear, you want to remove this line:
CoinSideNames = CoinSideName(CoinSide)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
Camelcase names is a little annoying Undecided
So to rewrite the task to show what i mean,and also so the game make sense.
Take a look at PEP-8
import random

def coin_flip():
    return random.choice(('Head', 'Tail'))

def user_choice():
    command = input("Choose Head or Tail: ")
    return command

def coin_result(coin_flip, user_choice):
    ''' Doc string explain what function do'''
    coin_f = coin_flip()
    user_c = user_choice()
    if coin_f == user_c:
        print(f'\nComputer <{coin_f}> You gussed <{user_c}> which is correct\n')
    else:
        print(f'\nComputer <{coin_f}> You gussed <{user_c}> which is wrong\n')

def menu():
    while True:
        print('(1) Coin flip game')
        print('(Q) Quit\n')
        choice = input('Enter your choice: ').lower()
        if choice == '1':
            coin_result(coin_flip, user_choice)
        elif choice == 'q':
            return False
        else:
            print(f'Not a correct choice: {choice}')

if __name__ == '__main__':
    menu()
A run:
Output:
λ python coin_flip_36.py (1) Coin flip game (Q) Quit Enter your choice: 1 Choose Head or Tail: Head Computer <Tail> You gussed <Head> which is wrong (1) Coin flip game (Q) Quit Enter your choice: 1 Choose Head or Tail: Tail Computer <Tail> You gussed <Tail> which is correct (1) Coin flip game (Q) Quit Enter your choice: Q
Reply
#7
Thank you both for the amount of effort you have put in helping me solve my problem, been working a lot. Am reading and trying the fixes and plan on reading the information you provided.

I just didn't want too much time to pass between the help you are providing and me thanking you all for it.

I will update as soon as I catch up to the help provided.

Thanks again,
Snippsat, Ichabod801, and Larz61+
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Are there errors in the code for my coin toss systems? Matlibplot is too perfect . Coolkat 0 376 Nov-13-2023, 11:54 AM
Last Post: Coolkat
  Coin Toss - Distribution lasek723 6 3,121 Oct-04-2020, 01:36 PM
Last Post: deanhystad
  effective means to flip boolean values? Exsul 3 4,367 Aug-25-2019, 03:58 PM
Last Post: Exsul
  [split] Coin Flip Program Crackity 5 4,833 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