Я пишу программу на Python для калькулятора и пытаюсь реализовать систему истории. Однако, когда мне нужно получить доступ к истории, я использую символ для доступа к ней, но он продолжает сообщать мне, что она не распознана.
Я использовал ? символ, который я установил для доступа к истории, и я ожидал, что он примет его и выполнит задачу, для которой предназначен.
Однако он просто сказал мне, что символ не распознан. .
from random import choice
def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply (a,b):
return a*b
def divide(a,b):
try:
return a/b
except Exception as e:
print(e)
def power(a,b):
return a**b
def remainder(a,b):
return a%b
def select_op(choice):
if (choice == '#'):
return -1
elif (choice == '$'):
return 0
elif (choice in ('+','-','*','/','^','%')):
while (True):
num1s = str(input("Enter first number: "))
print(num1s)
if num1s.endswith('$'):
return 0
if num1s.endswith('#'):
return -1
try:
num1 = float(num1s)
break
except:
print("Not a valid number,please enter again")
continue
while (True):
num2s = str(input("Enter second number: "))
print(num2s)
if num2s.endswith('$'):
return 0
if num2s.endswith('#'):
return -1
try:
num2 = float(num2s)
break
except:
print("Not a valid number, please enter again")
continue
def history(num1s, choice, num2s, result):
his_file = open("calc_his.txt", "a")
his_file = his_file.write(str(num1) + " " + choice + " " + str(num2) + "=" + result + "\n")
if choice == '?':
his_file = open("calc_his.txt", "r")
print(his_file.read())
result = 0.0
last_calculation = ""
if choice == '+':
result = add(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '-':
result = subtract(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '*':
result = multiply(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '/':
result = divide(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '^':
result = power(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '%':
result = remainder(num1, num2)
history(num1, choice, num2, str(result))
else:
print("Something Went Wrong")
last_calculation = "{0} {1} {2} = {3}".format(num1, choice, num2, result)
print(last_calculation)
else:
print("Unrecognized operation")
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
print("8.History : ? ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
Подробнее здесь: https://stackoverflow.com/questions/793 ... to-use-the
Я продолжаю получать эту «нераспознанную операцию» всякий раз, когда мне нужно использовать «?» ⇐ Python
Программы на Python
1737011803
Anonymous
Я пишу программу на Python для калькулятора и пытаюсь реализовать систему истории. Однако, когда мне нужно получить доступ к истории, я использую символ для доступа к ней, но он продолжает сообщать мне, что она не распознана.
Я использовал ? символ, который я установил для доступа к истории, и я ожидал, что он примет его и выполнит задачу, для которой предназначен.
Однако он просто сказал мне, что символ не распознан. .
from random import choice
def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply (a,b):
return a*b
def divide(a,b):
try:
return a/b
except Exception as e:
print(e)
def power(a,b):
return a**b
def remainder(a,b):
return a%b
def select_op(choice):
if (choice == '#'):
return -1
elif (choice == '$'):
return 0
elif (choice in ('+','-','*','/','^','%')):
while (True):
num1s = str(input("Enter first number: "))
print(num1s)
if num1s.endswith('$'):
return 0
if num1s.endswith('#'):
return -1
try:
num1 = float(num1s)
break
except:
print("Not a valid number,please enter again")
continue
while (True):
num2s = str(input("Enter second number: "))
print(num2s)
if num2s.endswith('$'):
return 0
if num2s.endswith('#'):
return -1
try:
num2 = float(num2s)
break
except:
print("Not a valid number, please enter again")
continue
def history(num1s, choice, num2s, result):
his_file = open("calc_his.txt", "a")
his_file = his_file.write(str(num1) + " " + choice + " " + str(num2) + "=" + result + "\n")
if choice == '?':
his_file = open("calc_his.txt", "r")
print(his_file.read())
result = 0.0
last_calculation = ""
if choice == '+':
result = add(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '-':
result = subtract(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '*':
result = multiply(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '/':
result = divide(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '^':
result = power(num1, num2)
history(num1, choice, num2, str(result))
elif choice == '%':
result = remainder(num1, num2)
history(num1, choice, num2, str(result))
else:
print("Something Went Wrong")
last_calculation = "{0} {1} {2} = {3}".format(num1, choice, num2, result)
print(last_calculation)
else:
print("Unrecognized operation")
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
print("8.History : ? ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
Подробнее здесь: [url]https://stackoverflow.com/questions/79360645/i-keep-getting-this-unrecognized-operation-whenever-i-need-to-use-the[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия