Home > Back-end >  Whitespace issues, Python dice roll simulator
Whitespace issues, Python dice roll simulator

Time:10-23

My output differs from what my professor wants, below is my code, my output, and the desired output. The white space between the number and the 's' and the ':' is the issue, it shouldn't be there. I've tried the leading whitespace strip function, the trailing one, the join function. I keep getting errors. Something simple that I can just add in is best. Please help!!!

    import random
roll_list = []  #empty list for appending rolls
num_rolls = 100 #number of times the program will run

def init_list(): #defines initial list for possible outcomes
    for x in range(0,13):
      roll_list.append(0)

def roll_dice(): #rolls the dice and sums the outcomes
    dice1 = random.randint(1,6)#random operator to make all rolls random 1-6
    dice2 = random.randint(1,6)
    roll = dice1   dice2 #sum of each roll 
    return roll  #keeps the program in this loop

def update_list(roll): #defines updated list of possible outcomes
    previousvalue = roll_list.pop(roll)
    roll_list.insert(roll,previousvalue   1)


def print_histogram(): #defines the for loop below, printing the desired outcome
  for numbers in range(2, 13):
    print((numbers), 's', ':', '*' * roll_list[numbers])

# main program
init_list() #executeds first def, list of values 2-12
for y in range(0,num_rolls): #excecutes second def, roll dice, 100 times
  update_list(roll_dice())#executes third def, updated list 100 values long

print_histogram() #excecutes fourth def, printing desired outcome

My output:

2 s : ****
3 s : ***
4 s : ************
5 s : ***********
6 s : ******************
7 s : ************
8 s : ************
9 s : **********
10 s : **********
11 s : ****
12 s : ****

Desired output:

2s: *****
3s: *********
4s: *******
5s: ****
6s: ************
7s: *****
8s: **********
9s: **
10s: ********
11s: ****
12s: *************

CodePudding user response:

By default, print puts a space between each argument supplied to it. You can override this by specifying the sep argument... but it's usually easier to provide one argument, which you can build as an f-string.

print(f'{numbers}s: {"*" * roll_list[numbers]}')

CodePudding user response:

Try

print("%ds:" % numbers, '*' * roll_list[numbers])

or

print(f"{numbers}s:", '*' * roll_list[numbers])

CodePudding user response:

There is some issue with the printing function. See this

def print_histogram(): #defines the for loop below, printing the desired outcome
  for numbers in range(2, 13):
    print(f'{numbers}s', ':', '*' * roll_list[numbers])

Almost identical, but i changed the first argument of print(), putting numbers inside a formatted string, where i have more control.

  • Related