python - Can't get simple if..elif test to work with testing for a number -
my assignment is:
you have been asked write program give name of shape depending on number of sides. user can enter numbers between 3 , 8, if enter other number program should tell them enter number between 3 , 8.
and here's python answer:
#sides , shapes sides = int(input("how many sides on shape there? ")) if sides ==3: print ("your shape triangle") if sides ==4: print ("your shape square") if sides ==5: print ("your shape pentagon") if sides ==6: print ("your shape hexagon") if sides ==7: print ("your shape heptagon") if sides ==8: print ("your shape octagon") elif sides != range(3,9): print ("you should enter number between 3 , 8") after elif statement somehow need loop if person inputs other 3-8 keep asking them enter number 3 8.
the elif statement not work reason , outputs answer in f5:
how many sides on shape there? 6 shape hexagon should enter number between 3 , 8
range() produces object of different type; integer != range() always going true.
either test if integer outside range < or <= , chaining:
elif not (3 <= sides < 9): print ("you should enter number between 3 , 8") or use not in see if number outside range:
elif sides not in range(3, 9): print ("you should enter number between 3 , 8") or use elif on all tests first, , else last branch; it'll picked if if..elif tests did not match:
if sides ==3: print ("your shape triangle") elif sides ==4: print ("your shape square") elif sides ==5: print ("your shape pentagon") elif sides ==6: print ("your shape hexagon") elif sides ==7: print ("your shape heptagon") elif sides ==8: print ("your shape octagon") else: print ("you should enter number between 3 , 8") note there one if now; logically, elif , else parts belong 1 if statement. other if forms separate, new set of choices, , sides != range(3, 9) expression true, meaning elif test true time if slides == 8 not true.
you can simplify code using dictionary. lets associate key value; make numbers keys, , can test if sides in dictionary, or return default value if not:
shape_msg = "your shape " result = { 3: shape_msg + "triangle", 4: shape_msg + "square", 5: shape_msg + "pentagon", 6: shape_msg + "hexagon", 7: shape_msg + "heptagon", 8: shape_msg + "octagon", } sides = int(input("how many sides on shape there? ")) result = results.get(sides, "you should enter number between 3 , 8") print(result) here, dict.get() method returns value given key, or default value if key not present.
if need continue loop, test presence of key , branch based on that:
while true: sides = int(input("how many sides on shape there? ")) if sides in result: print(sides[result]) break # done, exit loop print("you should enter number between 3 , 8") for further tips on how ask user input , handle wrong input, see asking user input until give valid response.
Comments
Post a Comment