Variables not recorded in the while loop - python

my problem lies within the lines of #. I don't understand why the invalidDish is always True even after it is set to False in one of the if statement.
class dishes:
def __init__(self, serial_no, dish_name, price):
self.serial_no = serial_no
self.dish_name = dish_name
self.price = price
def show_menu(self):
print(str(self.serial_no) + '. ' + self.dish_name + '\t$' + self.price)
def errorMessage(code, range):
if code == 'outOfRange':
print('***Please enter number 1 - {} only***\n'.format(str(range)))
machineRunning()
plain_prata = dishes(1, 'Plain prata', '0.50')
egg_prata = dishes(2, 'Egg prata', '1.00')
cheese_prata = dishes(3, 'Cheese prata', '2.50')
garlic_prata = dishes(4, 'Garlic prata', '1.50')
ham_prata = dishes(5, 'Ham prata', '2.50')
menu = [plain_prata, egg_prata, cheese_prata, garlic_prata, ham_prata]
current_order = []
def machineRunning():
while True:
print('1. Menu')
print('2. Add order')
print('3. Checkout')
value = input('Please input:')
try:
value = int(value)
if value < 1 or value > 3:
errorMessage('outOfRange', 3)
except ValueError:
print('***Please enter number 1 - 3 only***\n')
continue
if value == 1:
print()
for x in range(len(menu)):
menu[x].show_menu()
elif value == 2:
dish = input('Dish name/number:')
try:
dish = int(dish) - 1
if dish < 0 or dish >= len(menu):
errorMessage('outOfRange', len(menu))
except ValueError:
loop = True
while(loop):
for x in range(len(menu)):
dish = dish.capitalize()
split_dish = dish.split()
if dish == menu[x].dish_name:
dish = int(x)
loop = False
break
else:
invalidDish = True
x = 0
############################################
while invalidDish and x < len(menu):
print (invalidDish)
print (x)
if split_dish[0] in menu[x].dish_name:
isDish = input('Are you ordering ' + menu[x].dish_name + '?')
print('isDish',isDish.lower())
if 'y' in isDish.lower(): #TurningPoint
print('Entered here')
invalidDish = False
print(invalidDish)
break
else: x += 1
else: x += 1
##########################################
if invalidDish:
print('***Invalid dish name***\n')
dish = input('Dish name/number:')
amount = input('Amount:')
current_order.append([menu[dish].dish_name, menu[dish].price, amount])
else:
print('***Please enter number 1 - 3 only***\n')
for x in current_order:
print (x)
machineRunning()
I tried to follow the code in terminal and still can't figure out the problem. This is the result from the terminal.
1. Menu
2. Add order
3. Checkout
Please input:2
Dish name/number:c
True
0
True
1
True
2
Are you ordering Cheese prata?y
isDish y
Entered here
False #It is set to False at this point
True #Why it becomes True again at the beginning of the loop?
0
True
1
PS. Am learning python by trying to make a cash register for a restaurant, with generating weekly, monthly summary, calculating profit etc. Any suggestion on what I can do next to make this more user-friendly? Like python talks to other software or code making the interface for easy to use?

You are breaking out of the while loop, then looping again using the outer for loop, which then sets invalidDish to True.

Related

Return multiple values in a function

I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]

How to better implement a history of user action?

I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()

Python input statement

I have created a battleship like game, and have it all completed except for one detail.
I have the following input statement:
x, y = input("Enter two numbers here: ").split()
with the 2 numbers being entered corresponding to the players chosen coordinates. I also need to be able to handle the entry of 'q' or 'h' for the quit or help options. However, since i am taking two variables from this statement when only a q or h is entered i get the error that the statement needs 2 elements to unpack, which makes sense. Any pointers on how to get around this?
import random, math
class oceanTreasure:
def __init__(self):
self.board = self.board()
self.found = 0
self.left = 3
self.sonarsLeft = 20
self.chests= []
self.chest()
def board(self):
board = []
for x in range(16): # the main list is a list of 60 lists
board.append([])
for y in range(61): # each list in the main list has 15 single-character strings.
board[x].append('~')
return board
def chest(self):
chest1 = [random.randint(0,60), random.randint(0,15)]
chest2 = [random.randint(0,60), random.randint(0,15)]
chest3 = [random.randint(0,60), random.randint(0,15)]
self.chests = [chest1, chest2, chest3]
def getChestsLeft(self):
return self.found
def getChests(self):
return self.chests
def getTreasuresLeft(self):
return self.left
def getSonarsLeft(self):
return self.sonarsLeft
def dropSonar(self,x,y):
ySonar = ['a','b','c','d','e','f','g']
whichAxis, axis = self.checkDistance(x,y)
if whichAxis == True:
sonar = axis
if whichAxis == 'xaxis':
sonar = axis
elif whichAxis == 'yaxis':
sonar = ySonar[axis-1]
elif whichAxis == None:
sonar = axis
self.board[int(y)][int(x)] = sonar
self.sonarsLeft -=1
return axis
def checkDistance(self,x,y):
closest = self.chests[0]
distance = 100
for chest in self.chests:
temp = math.sqrt(math.pow((chest[0]-int(x)),2) + math.pow((chest[1]-int(y)),2))
if temp < distance:
closest = chest
distance = temp
xaxis =math.fabs((closest[0] - int(x)))
yaxis = math.fabs((closest[1]-int(y)))
if yaxis == 0 and xaxis == 0:
self.chests.remove(closest)
self.found +=1
self.left -=1
return True, 'X'
elif xaxis <= 9 and yaxis <=5 :
if yaxis == 0 :
return 'xaxis',int(math.fabs(xaxis))
if xaxis == 0 :
return 'yaxis',int(math.fabs(yaxis))
if min(xaxis//2,yaxis) ==(xaxis//2) :
return 'xaxis', int(math.fabs(xaxis))
elif min(xaxis//2,yaxis) == (yaxis) or xaxis == 0 :
return 'yaxis', int(math.fabs(yaxis))
else: return None,0
def drawBoard(self):
firstLine = ' '
for i in range(1,7):
firstLine += (' '*9) + str(i)
print(firstLine)
secondLine = ' '
secondLine += ('0123456789' *6)
print(secondLine)
print()
i = 0
for i in range(0,16):
boardRow = ''
for x in range(0,61):
boardRow += str(self.board[i][x])
if i < 10:
print(str(i) +' ' + str(boardRow) + str(i))
if i >= 10:
print(str(i) +' ' + str(boardRow) + str(i))
print()
print(secondLine)
print(firstLine)
device = 'devices'
if self.sonarsLeft ==1:
device = 'device'
print('You have %s sonar %s availabe. You have found %s treasures and have %s left' %(self.sonarsLeft, device, self.found, self.left))
ocean = oceanTreasure()
ocean.drawBoard()
gameOver = False
instructionsList = ['This is a treasure hunting game.' , 'You begin the game with 20 sonar devices available (each device has a range of 9 units in the x axis and 5 in the y axis).','When you place a device, if an "O" is displayed that means there are no chests in range.', 'If a number from 1-9 is displayed, the closest chest is within n units away on the X axis.', 'If a letter from a-e is displayed, the closest chest is n units away on the Y axis (a =1, b =2 and so on...).', 'The game ends when you run out of sonar devices, all the treasure is found or you enter "q" to quit.', 'Thanks for playing and happy hunting!']
while ocean.getTreasuresLeft() != 0 and ocean.getSonarsLeft() >0 and gameOver == False:
response = False
coordinate = False
while response == False:
inputString = input("Enter two numbers seperated by a space (X Y): ")
if inputString == 'q':
gameOver = True
response = True
elif inputString == 'h':
for instruction in instructionsList:
print(instruction)
response = True
else:
try:
x,y = inputString.split()
assert int(x) <=60 and int(y) <=15
response = True
coordinate = True
except AssertionError:
print('Please enter a valid move')
if gameOver == True:
break
#whichAxis, axis =ocean.checkDistance(x,y)
#print(axis)
if coordinate == True:
axis = ocean.dropSonar(x,y)
ocean.drawBoard()
if axis == 'X':
print('Congratulations, you have found a treasure!')
if ocean.getTreasuresLeft() == 0:
print('Congratulations, you found all the treasure')
elif ocean.getSonarsLeft() == 0:
print('Sorry, you ran out of sonar devices, the remaining chests were: %s ' % str(ocean.getChests()))
How about separating the tests to be a little clearer:
input_string = input("Enter two numbers here: ")
if input_string == 'q':
do_quit()
elif input_string == 'h':
do_help()
else:
x,y = input_string.split()
That way you can test for your special cases, and process the x and y if they are not found.
may be this, for example:
a = input("text")
b = a.split()
if len(b) == 1:
if b[0] == 'q':
return
elif b[0] == 'h':
print 'it is help ... '
elif len(b) == 2:
# process for two inputted numbers
You can just separate the input:
# get the input
ipt = input("Enter two numbers here: ")
# check if your option is entered
if ipt == 'q' or ipt == 'h':
# do something
else:
x,y = ipt.split()

Issue with Python Slot Machine

import random
balance = 50
def generator():
slot = 0
count = 0
gen = random.random()
while count < 3:
count = count + 1
if gen <= 0.01:
slot = 'Cherry'
elif gen <= 0.06:
slot = 'Diamond'
elif gen <= 0.16:
slot = 'Heart'
elif gen <= 0.36:
slot = 'Spade'
elif gen <= 0.66:
slot = 'Club'
elif gen <= 1:
slot = 'Monkey'
else:
break
return slot
def win(generator):
if generator() == 'Monkey' and generator() == 'Monkey' and generator() == 'Monkey':
balance = balance + 2122
print "Welcome to the International Slot Machine"
print ""
print "Balance: $",balance
print ''
spinyn = (raw_input("Would you like to spin? $5 per spin. Enter y or n:\n"))
while True:
if spinyn == "y":
break
elif spinyn == "n":
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spinyn = raw_input('\033[31mPlease enter only y or n.\033[0m\n')
spin = (raw_input("Press enter to spin for $5:\n"))
while True:
if spin == '':
balance = balance - 5
if balance <= 0:
print ""
print "Final Balance: $",balance
print "You have run out of money, the game has now ended."
raise SystemExit
print ""
print "\033[34mResult:\033[0m"
print "\033[34m-------\033[0m"
print generator()
print generator()
print generator()
print ""
print "New balance:$",balance
print ""
spinagain = (raw_input("Would you like to spin again? Press enter to spin again, type anything to exit.\n"))
while True:
if spinagain == "":
break
else:
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spin = (raw_input("Please press enter to spin.\n"))
I'm trying to make a very basic slot machine.
My question is: How do I make the generator function repeat 3 times and return 3 outputs, and then how do I make it recognise certain combinations?
Is this possible at all, keeping with my current format?
Also, how could I incorporate arrays into my code?
Thanks
Make the generator return a list or tuple of three values after generating three values, also it would be easier to use random.choice() rather than random.random() . random.choice() randomly selects a element for a list of values/iterable with equal probability for all elements. Example -
def generator():
ret = []
for _ in range(3):
ret.append(random.choice(['Cherry','Diamond','Heart','Spade','Club','Monkey']))
return tuple(ret)
If you want to have different probabilities for different elements, you can keep the current method, just loop over that three times and append to ret like done above and return ret from it.
Then in your win function, keep a dictionary such that the key is the tuple of combination and the value is the amount the user wins, then you can simply use .get() with a default value of 0 , to get how much the user won. Do not pass in generator as an argument. Example -
def win():
roll = generator()
d = {('Monkey','Monkey','Monkey'):21222,...}
return d.get(roll,0)
Then in your main loop, call this win() function to roll and see how much the user won.
Use the range function to choose 3 times and store it in a list.
import random
choices_list=[]
for ctr in range(3):
gen = random.choice(['Cherry', 'Diamond', 'Heart',
'Spade', 'Club', 'Monkey'])
choices_list.append(gen)
print choices_list

How to return the nth value of a Dict?

I have this dict for example and i wish to return the nth value of it
d = {'Hello':4, 'World':17, 'Hi':2, 'Again':46}
Note: I know that dicts are unordered, and i don't care i just want to return all the keys one after the other.
In my program I just want to make calculations with the values, and the keys will be a user input so we don't know the keys.
How can i return the nth value in this dict like this?
Hereis the full code of y progam, error is located in 2nd def function, on line 23
#Subroutines
def dumptodaydate():
import pickle
with open('LastOpenDate.txt', 'wb') as DOT:
import time
ODate = time.strftime('%d')
OMonth = time.strftime('%m')
OYear = time.strftime('%Y')
List = {'Day':ODay, 'Month':OMonth, 'Year':OYear}
pickle.dump(List, DOT)
def caltimelefttask():
import pickle
with open('LastOpenDate.txt', 'rb') as LOD:
List = pickle.load(LOD)
from datetime import date
Today = date.today()
ODay = List['Day']
OMonth = List['Month']
OYear = List['Year']
DifDay = (Today(eval(OYear),eval(OMonth), eval(ODay)).days
for key in Lesson:
OTimetask = Lesson[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Lesson[key]['Rating'] = Rating
for key in Exercises.keys():
OTimetask = Exercises[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Exercises[key]['Rating'] = Rating
for key in Assignment.keys():
OTimetask = Assignment[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Assignment[key]['Rating'] = Rating
def loadtxt():
import pickle
with open('LessonOut.txt', 'rb') as Li:
Lesson = pickle.load(Li)
with open('ExercisesOut.txt', 'rb') as Ei:
Exercises = pickle.load(Ei)
with open('AssignmentOut.txt', 'rb') as Ai:
Assignment = pickle.load(Ai)
def ADD():
print('Name of task? (Keep it short for convenience Example: Math1)\n(Must be diferent from any other non deleted tasks)')
Name = input('>>>')
print('Description of task? (this can be as long as you want)')
Desc = input('>>>')
print('Rate the time it takes you to do the task on a scale from 1 to 20')
Time = input('>>>')
print('Rate the importance of the task on a scale from 1 to 20')
Imp = input('>>>')
print('Rate how much you want to do it on a scale from 1 to 5 \n(1= want to do it, 5= don\'t want to')
Want = input('>>>')
print('enter deadline (day)')
TimeDay = input('>>>')
print('enter deadline (month)')
TimeMonth = input('>>>')
print('enter deadline(year)')
TimeYear = input('>>>')
print('what type of homework is it? (Lesson/Exercises/Assignment)')
TaskType = input('>>>')
from datetime import date
Today = date.today()
TaskForDate = date(eval(TimeYear), eval(TimeMonth), eval(TimeDay))
TimeLeftTemp = abs((TaskForDate - Today).days)
print ('You have', TimeLeftTemp, 'days to finish this task.')
Rating = eval(Time) + eval(Imp) + eval(Want) - (TimeLeftTemp * 2)
if TimeLeftTemp < 4:
Rating = Rating + 50
if TimeLeftTemp <= 0:
Rating = Rating + 50
if TaskType == 'Lesson':
Lesson[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Exercises':
Exercises[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Assignment':
Assignment[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
def DEL():
print ('What type of task is it? \nLesson, Exercises or Assignment)')
WhatDict = input('>>>')
if WhatDict == Lesson:
print(Lesson.keys())
if WhatDict == Exercises:
print(Exercises.keys())
if WhatDict == Assignment:
print(Assignment.keys())
print ('What task do you want do delete?')
WhatDel = input('>>>')
if WhatDict == 'Lesson':
try:
del Lesson[WhatDel]
except:
pass
elif WhatDict == 'Exercises':
try:
del Exercises[WhatDel]
except:
pass
elif WhatDict == 'Assignment':
try:
del Assignment[WhatDel]
except:
pass
pass
else:
print('Sorry, the type of task is not recognised, please try again.')
def sort_by_subdict(dictionary, subdict_key):
return sorted(dictionary.items(), key=lambda k_v: k_v[1][subdict_key])
def SHOW():
ShowWhat = input('What type of task do you want to do?\nLesson/Exercises/Assignment)\n>>>')
if ShowWhat == 'Lesson' or 'lesson':
print (sort_by_subdict(Lesson, 'Rating'))
elif ShowWhat == 'Exercises' or 'exercises':
print (sort_by_subdict(Exercises, 'Rating'))
elif ShowWhat == 'Assignment' or 'assignment':
print (sort_by_subdict(Assignment, 'Rating'))
else:
print('Type of task not recognosed, please try again')
def dumptxt():
import pickle
with open('LessonOut.txt', 'wb') as Lo:
pickle.dump(Lesson, Lo)
with open('ExercisesOut.txt', 'wb') as Eo:
pickle.dump(Exercises, Eo)
with open('AssignmentOut.txt', 'wb') as Ao:
pickle.dump(Assignment, Ao)
loadtxt()
while True:
print ('WARNING NEVER EXIT PROGRAM WITHOUT USING THE quit COMMAND,\nOR ALL ACTIONS DONE WILL BE LOST')
print ('Commands:')
print ('add (to add a task)')
print ('del (to delete a task)')
print ('quit (to exit program)')
print ('show (to see your tasks)')
Input = input('>>>')
if Input == 'add':
ADD()
elif Input == 'del':
DEL()
elif Input == 'show':
SHOW()
elif Input == 'quit':
print ('are you sure you want to quit? y/n')
Input = input('>>>')
if Input == 'y':
dumptxt()
quit()
elif Input == 'n':
print ('Not exiting')
else:
print ('Error, command not recognised')
This gives me a syntax error:
for key in Lesson:
#syntax error ^
# here
You can just enumerate over all the keys in the dict directly by using for key in d:
for key in d:
if d[key] < 20:
d[key] -= 4
else:
d[key] += 4

Categories