-3

I have a use a try/except block to prompt the user for an input. My problem is that it always prints "Perfect" no matter what the number of number_disks. What is the problem with my code?

number_disks = -2

try:
      number_disks > 0 and number_disks <= 8
      print("Perfect")
except:
      print("the number of disks is between 1 and 8, try again!")
      number_disks = input(int("what is the number of disks?\n"))
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 5
    You forgot the `if` in your `if`. – timgeb Nov 01 '18 at 17:18
  • 1
    I'm also curious what exception you expect to be thrown. – timgeb Nov 01 '18 at 17:19
  • `try` `except` blocks are not for conditionals, they are for catching errors that might otherwise crash your program. You should use an `if` statement instead. – Aaron Nov 01 '18 at 17:19
  • 1
    The ordering of statements in your code is most peculiar! – NPE Nov 01 '18 at 17:19
  • See https://stackoverflow.com/q/44646304/2564301 for a number of fixes. – Jongware Nov 01 '18 at 17:20
  • I want to use try/expect to make sure that the user input in an integer – FreshmanUCSD Nov 01 '18 at 17:20
  • 2
    I think we can't help you much here in the comments. There's so much wrong with this code. Not knowing how `if`/`else` is used, not knowing how to properly catch exceptions, the weird ordering of statements... You need to work through a Python tutorial. – timgeb Nov 01 '18 at 17:22
  • @FreshmanUCSD You have *two* coding situations: (1) see that the input is an integer; (2) repeat until you get a valid input. Solve one at a time; each technique is covered quite well in on-line resources. – Prune Nov 01 '18 at 17:27
  • Also, note that you have *not* used a `try` to check for integer input: there is no `input` or `int` operation in your `try` clause. Back up to the tutorials or class materials ... solve one item at a time, *then* go to the next. It's called "incremental programming" -- and it's not just for beginners! – Prune Nov 01 '18 at 17:29
  • Thank you Prune and folks here for help! – FreshmanUCSD Nov 01 '18 at 17:34

1 Answers1

1

It should be :

if number_disks > 0 and number_disks <= 8
  print("Perfect")

If you want the print to occure given that conditional, and not always

If wanted to use an exception perhaps:

if number_disks > 0 and number_disks <= 8
   raise Exception();

Which then wouldn't do the print statement if the exception occured

lostbard
  • 5,065
  • 1
  • 15
  • 17