-1

I am a complete newbie and was trying to make a number magic trick. I want the program to stop when the user types "No". Here is my code below!

 print("Hello and welcome to the number magic trick!!")
x = input("Yes or No")
if x == "Yes":
    print("Yay!!")
    print("Pick an integer number from 1 to 10 but don't tell me!")
    print("Multiply this number with 2")
    print("Multiply the new number by 5")
    print("Now, divide your current number with your original number")
    print("Subtract 7 from your current number")
    print("Is the answer 3 ?")
elif x == "No":
    print("Boo!!")
else:
    print("Invalid Input")

y = input ("Yes or No")
if y  == "Yes":
    print("Cool isn't it?")
elif y == "No":
    print("You can't do math!")
else:
    print("Invalid input")

3 Answers3

2

You don't have to raise an error, you could simply use the exit method instead:

if x.strip().lower() == "no":
  print("You said no!")
  exit(0)

You could even use the exit method from the sys module, like this:

import sys

if x.strip().lower() == "no":
  print("You said no!")
  sys.exit(0)

INFO: The 0 in the exit method's parenthesis means that "this program finished without any errors" but replacing the 0 with a 1 would mean that "something went wrong with the program" and it's exiting with an error.

Good luck.

Malekai
  • 4,765
  • 5
  • 25
  • 60
  • 1
    What's the difference between the two `exit()` methods? – Voldemort's Wrath Dec 06 '19 at 02:16
  • [`exit`](http://docs.python.org/library/constants.html#exit) is a helper for the interactive shell, [`sys.exit()`](http://docs.python.org/library/sys.html#sys.exit) is intended for use in programs. You can find out more about the differences from [this answer](https://stackoverflow.com/a/6501134/10415695). – Malekai Dec 07 '19 at 13:45
1

You could raise an exception. Also, it's good practice to put one-line if/else statements on the same line... For example,

print("Hello and welcome to the number magic trick!!")
x = input("Yes or No")
if x == "Yes":
    print("Yay!!")
    print("Pick an integer number from 1 to 10 but don't tell me!")
    print("Multiply this number with 2")
    print("Multiply the new number by 5")
    print("Now, divide your current number with your original number")
    print("Subtract 7 from your current number")
    print("Is the answer 3 ?")
elif x == "No":
    print("Boo!!")
    raise SystemExit()
else:
    print("Invalid Input")
    raise SystemExit()

y = input ("Yes or No")
if y  == "Yes":
    print("Cool isn't it?")
elif y == "No":
    print("You can't do math!")
    raise SystemExit()
else:
    print("Invalid input")
    raise SystemExit()

You're welcome to use this code...

1
if x == "No":
     quit()  

OR

from sys import exit 
if x == "No":
     exit()
Preetham
  • 577
  • 5
  • 13