Pregunta

I have been trying to create a program that will simulate a dice roll, with the option to choose between a 4, 6, or 12 sided die. At the moment the problem I am having is that the program skips the rolling entirely no matter what option I choose and immediately asks me if I want to roll again. Im using Portable Python 3.2.1.1 to create the code. This is what I have so far:

#!/usr/bin/env python


import random

def fourdie():
   min = 1
   max = 4
   print (random.randint(min, max));
   return;

def sixdie():
  min = 1
  max = 6
  print (random.randint(min, max));
  return;

def twelvedie():
  min = 1
  max = 12
  print (random.randint(min, max));
  return;


roll = "yes"
y = 1


while roll == "yes" or roll == "y":
  x = raw_input("What die do you want to roll? 4, 6 or 12?");
  if x == 4:
    print (fourdie());
  elif x == 6:
    print (sixdie());
  elif x == 12:
    print (twelvedie());
  else:
    print = "Sorry, I dont appear to have that dice type";

  roll = raw_input("Do you want to roll again?");

Any help would be appreciated. Thank you for your time!

¿Fue útil?

Solución

input function returns a string.

You can convert this string to int and then compare it to 4, 6, or 12:

x = int(input("What die do you want to roll? 4, 6 or 12?"))
if x == 4:
    // whatever
elif x == 6:
    // whatever

Or you can compare x directly to a string:

x = input("... whatever ...")
if x == "4":
    // whatever
elif x == "6":
    // whatever

And one other thing: there is no need to end lines with the semicolon in python. Makes Guido van Rossum happy.

Otros consejos

Your basic problem is typing, as solved by Nigel Tufnel

I just, because it strikes my fancy, thought I'd mention you could make your code far more generic:

while roll in ["yes", "y"]:
    x = int(raw_input("Number of sides on the die you want to roll?"))
    print random.randint(1,x)
    roll = raw_input("Do you want to roll again?")
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top