Is it possible to make a program go back to its original state after it being run. For example I made a calculator script below. Is it possible to make it start over after outputting an answer instead of the user having to exit the script and run it again. Code:
class bcolors:
Red = '\033[91m'
Green = '\033[92m'
Blue = '\033[94m'
Cyan = '\033[96m'
White = '\033[97m'
Yellow = '\033[93m'
Magenta = '\033[95m'
Grey = '\033[90m'
Black = '\033[90m'
Default = '\033[99m'
#code for addition
def addition(x, y):
return x + y
#code for subtraction
def subtraction(x, y):
return x - y
#code for multiplication
def multiplication(x, y):
return x * y
#code for division
def division(x, y):
return x / y
print(bcolors.Blue + "Hey and welcome to my first python program")
print("This is a calculater I made in my spare time!")
print(bcolors.Magenta + "Simply type in your question here and you will get answer.")
print(bcolors.Red + "This program is made by and credited to Mohammad Al Nesef")
print(bcolors.Yellow + "1.addition")
print(bcolors.Yellow + "2.subtraction")
print(bcolors.Yellow + "3.multiplication")
print(bcolors.Yellow +"4.division")
choice = input(bcolors.Green + "Enter choice(1/2/3/4: ")
num1 = input(bcolors.Blue + "Enter first number: ")
num2 = (input(bcolors.Magenta + "Enter second number: "))
if choice == '1':
print(float(num1), "+", float(num2), "=", addition(num1,num2))
elif choice == "2":
print(float(num1), "-", float(num2), "=", subtraction(num1,num2))
elif choice == "3":
print(float(num1), "*", float(num2), "=", multiplication(num1,num2))
elif choice == "4":
print(float(num1), "/", float(num2), "=", division(num1,num2))
else:
print("Invalid Input")
You did not close the bracket in this line: num2 = (input("Enter second number: ")
Also pay attention to use the same indentation for your file. This means 4 spaces for PEP8 conformity.
Actually, you should not have given an extra bracket before the "input" in line 35
num2 =(input("Enter second number: ")
the actual code should be:
num2 =input("Enter second number: ")
If you are looking for hard restart of script itself without handling it gracefully via some more lines then call below function when you want to start over:
def restart_calc_script():
import sys
print("resetting the calculator.")
import os
os.execv(sys.executable, ['python'] + sys.argv)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.