-1

Have an If-Statement but no 'else' after 'if'. Is the 'else' part necessary? i don't want to change the program (which is supposed to randomise 3 die 50 times and count how many matches there were) unless I need to. Mainly focused on 'else' after if statement

#Program 2#
#create a Yatzhee dice program#
import random

print("--------------------")
print("Yatzhee dice program")
print("--------------------")
print("")
print("Welcome to the Yatzhee Dice Program")
print("In this program the dice will get rolled 50 times and at the end we tell you how many matches you got.")
print("")
# before loop #

rolls = 50
total_matches = 0

# --- loop ---

for i in range(rolls): #randomise 50 times#
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)#chooses a number from 1 to 6#
    die3 = random.randint(1, 6)

    print(die1, "|", die2, "|", die3)

    if die1 == die2 == die3:#If all three are the same.#
        print("****MATCH*****")#If statement inside for-loop so it adds up how many matches there were#
        total_matches += 1 #increases no. of matches by 1 each time there is a match#

#after loop#

print("")
print("The total number of matches was:", total_matches)#tells user how many matches there were#
Harry
  • 21
  • 6
  • Does your code work? If so, evidently you do not need an else clause. If not, tell us what the problem is. – khelwood Jan 29 '22 at 19:04
  • My code works but i was just unsure whether I needed an ‘else’ after the if statement – Harry Jan 29 '22 at 19:06
  • 1
    No. Your code works without one, so clearly you do not need it. An else clause is completely optional. – khelwood Jan 29 '22 at 19:07
  • If it works, and you don't need to do anything for the case that the numbers are not equal, then I don't see any problem. – Amit Sides Jan 29 '22 at 19:08
  • Ok, thank you. It was just a question of wondering whether or not an ‘else’ was necessary – Harry Jan 29 '22 at 19:10

2 Answers2

1

Have an If-Statement but no 'else' after 'if'. Is the 'else' part necessary?

No, the else part is not necessary.

Amit Sides
  • 274
  • 2
  • 6
1

you can use only if 'N' times without using else statement, but it is good practice to use else and elif over if again and again. IF-else is used when we have 2 choice to do

if a==True:
   Do something1
else:
   Do something2 

Adding control flow link for better understanding.

https://docs.python.org/3/tutorial/controlflow.html

Vibhor Karnawat
  • 100
  • 1
  • 12