Defining a variable within a function

Hiya guys is there a way to print a parameter within a function?

For example I am trying to print the bet parameter within the function below:

import random
money = 100
num = random.randint(1, 10)

#Write your game of chance functions here
def coin_flip(guess, bet):
  coin_flip = random.choice(['Heads', 'Tails']) #randomly generates heads or tails choice.
  
  if coin_flip == 'Heads':  
    return "Congratulations, you guessed correctly! You have won " + str(bet*2) +"!"

  else:
    return "Unfortunately you have lost " + str(bet/2) + " better luck next time"

#Call your game of chance functions here
print(coin_flip('Tails', 30))
money += bet
print("You now have £" + str(bet) + " in your account.")

I am trying to print it within this print command:

print("You now have £" + str(bet) + " in your account.")

However each time I try and do that this error message comes up:

Traceback (most recent call last):
File “script.py”, line 15, in
money += bet
NameError: name ‘bet’ is not defined

Any help would be greatly appreciated.

Since bet is not a variable, but rather a parameter, the Python error tells you that no variable declared as bet exists. This means that we cannot do money += bet or print bet.


Yes, we can print parameters inside a function. However, we cannot print them outside of the function since the scope of parameters is limited to the function they are defined in.


What is a way you could make the value of bet accessible both inside and outside of the function? Or, what is a way of manipulating and printing out the value of money so that it can use the parameter bet, which is accessible only inside the coin_flip function?

I there a way I could possibly make bet global? rather than local?

While you can’t make a parameter global, you could make bet a global variable. This way, you call coin_flip and pass in a variable rather than an integer for the bet parameter.

Example
greeting = "Hello!"

def displayMessage(message):
  print(message)

displayMessage(greeting) # prints Hello!

This allows you to continue using the value of bet while being able to access it from anywhere in your program.

More on scopes here.

1 Like

Bottom line, don’t think about manipulating globals. Think about what each function is supposed to return… The bet result. Build an outer shell that handles all the verbosity and keep the functions simple. Deal in global scope with whatever is global.

1 Like