Search code examples
pythonshufflecard

My input handling looks for "S", but when I type "S" the script just terminates


I tried to make a UNO hand out system but it seems to not work: when I type “S”, it just terminates. (It’s not very finished yet)

Here is my code so far:

import random

n = 0
command = input("Rules[R], Start[S], End[E] or Quit[Q]")

if command.upper == "S":
  while n < 7:
    pick_type = random.randint[1, 9]
    pick_colour = random.randint[1, 5]
    if pick_type == 5 or 6 or 7:
      pick_colour = random.randint[1, 4]
      if pick_colour == 1:
        colour = "Blue"
      elif pick_colour == 2:
        colour = "Green"
      elif pick_colour == 3:
        colour = "Red"
      else:
        colour = "Yellow"
      print(colour)
    elif pick_type == 1 or 2 or 3 or 4:
      pick_number = random.randint[1, 10]
      number = str(pick_number)
      print(number)
    else:
      draw_condition = random.randint[1, 2]
      if draw_condition == 1:
        card_type = "Wild"
      else:
        card_type = "Wild Draw 4"
      print(card_type)
    n += 1

And the result I get is:

Rules[R], Start[S], End[E], Quit[Q]
S

Process terminated with exit code 0.

Solution

  • Here is a simplified version of your "pick" logic:

    from enum import Enum
    import random
    
    
    class PickType(Enum):
        COLOUR = 0
        NUMBER = 1
        DRAW = 2
    
    
    for pick in random.choices(list(PickType), weights=[3, 4, 2], k=7):
        print({
            PickType.COLOUR: random.choice(["Blue", "Green", "Red", "Yellow"]),
            PickType.NUMBER: random.randint(1, 10),
            PickType.DRAW: random.choice(["Wild", "Wild Draw 4"]),
        }[pick])
    

    Note the use of random.choice and random.choices to simplify the random selection. Rather than generating a random integer and then figuring out which string goes with which int, you can use choice to just pick a random string directly. The choices function allows you to weight the choices; in this case you wanted to have a 3:9 chance of a color, a 4:9 chance of a number, and a 2:9 chance of a draw, so we can just pass the weights [3, 4, 2] into choices to correspond to the three options (COLOUR, NUMBER, DRAW).

    Telling choices that we want 7 choices (k=7) also removes the need for the incrementing n counter -- we just ask for 7 "picks", and then loop over the resulting pick_type values. We then use a dict to translate each possible PickType to the resulting string, and print that string.