python define a variable in an if statement

ei1 picture ei1 · Jan 4, 2015 · Viewed 8.4k times · Source

I want to make a coin toss / dice roll in python but i cannot figure out how to define / change a variable inside an if statement.

import random
def roll(number):
    if(number==1):
        {print("Take a moment to think that through")}
    if(number==2):
        {b=random.randint(0,1)
        if(b=0):
            {ba=1}
        else:
            {bb=1}
        }

the part, {b=random.randint(0,1)} the = is highlighted red and marked as a syntax error. I also tried this:

import random
b=0
def roll(number):
    if(number==1):
        {print("Take a moment to think that through")}
    if(number==2):
        {b+=random.randint(0,1)
        if(b=0):
            {ba=1}
        else:
            {bb=1}
        }

that gives the same error, and the = is highlighted, not the +

and before you ask, the function roll(number) is called in the shell. the shell is my interface.

Answer

user4414248 picture user4414248 · Jan 4, 2015
import random
def roll(number):
    if number==1:
        print("Take a moment to think that through")
    if number==2:
        b=random.randint(0,1)
        if b==0:
            ba=1
        else:
            bb=1

Python doesn't use curly braces, you should write your codes like this.Also you have to return something in your function.This is how you can use your function/variables with another methods.

import random
def roll(number):
    if number==1:
        my_string="Take a moment to think that through"
        return my_string
    if number==2:
        b=random.randint(0,1)
        if b==0:
            ba=1
        else:
            bb=1
        return ba,bb

Something like this, I don't know your whole code so.