update and save data to a .txt file daily - python

I'm trying to create something similar to a journal of my daily fluid intake, food, exercise, etc. I have created a few menus do ask user for specific input that is pre-defined in the menus. From there I need to collect all the output print data and save to a file, the file will be updated daily (asking the user for the same pre-defined input.
Code is pretty long, but looks like this:
health = open('healthy.txt','a+')
date = input('Date: ')
#Loop Menu for Exercise info for that day.
loop=True
while (loop):
print ()
print ("----------------------------------")
print ("1 = Yoga")
print ("2 = Cardio")
print ("3 = Walk")
print ("4 = Dance")
print ("5 = Rest/None")
print ("D = Done")
print ("----------------------------------")
print ()
exer = input('Exercise: ')
if (exer =='1'):
print("Yoga")
elif (exer =='2'):
print("Cardio")
elif (exer =='3'):
print ("Walk")
elif (exer =='4'):
print ("Dance")
elif (exer == '5'):
print ("Rest/None")
elif (exer =='d' or exer =='D'):
loop=False
else:
print ("Invalid Option")
#End Exercise Menu
dur = input('Duration(in minutes): ')
#Loop menu for the Food Intake for particular date.
loop=True
while (loop):
print ()
print ("----------------------------------")
print ("1 = Protein")
print ("2 = Starch")
print ("3 = Fruit")
print ("4 = Vegetable")
print ("D = Done")
print ("----------------------------------")
print ()
food = input('Food: ')
if (food =='1'):
print("Protein")
elif (food =='2'):
print("Starch")
elif (food =='3'):
print ("Fruit")
elif (food =='4'):
print ("Vegetable")
elif (food =='d' or food =='D'):
loop=False
else:
print ("Invalid Option")
#End Food Menu
fluid = input('Fluid Intake Total: ')
#for line in health:
#Final print of info to be written to file
#not sure if I need the next four lines
food_true = False
food_total = 0
exer_true = False
exer_total = 0
for char in exer:
if (exer_true == "Yoga"):
print ("Yoga", end=" ")
if (exer_true == "Cardio"):
print ("Cardio", end=" ")
if (exer_true == "Walk"):
print ("Walk", end= " ")
if (exer_true == "Dance"):
print ("Dance",end=" ")
if (exer_true == "Rest/None"):
print ("Rest/None",end=" ")
else:
loop=False
while(loop):
if (food_true == "Protein"):
print ("Protein", end=" ")
if (food_true == "Starch"):
print ("Starch", end=" ")
if (food_true == "Fruit"):
print ("Fruit", end= " ")
if (food_true == "Vegetable"):
print ("Vegetable",end=" ")
else:
loop=False
print ("{:>10}".format("Date: "),date)
print ("{:>10}".format("Exercises: "),exer_total)
print ("{:>10}".format("Duration: "),dur)
print ("{:>10}".format("Foods: "),food_total)
print ("{:>10}".format("Fluids: "),fluid)
print("-"*60)
#Save/Write to file function will be here
#Save/Write to file function will be here
health.write(info)#word "info" is a place holder only for final code info
health.close()
I want to be able to print out the info only (this does not include saving the info to the file)for the following in a neat looking file(format doesn't really matter as long as it is neat): Date: output; Exercise: output(all if applicable) ;Duration:output ;Food:output(all four if applicable);Fluids: output
Each day I will run the program and update my daily info for all the above.
Then the file needs to have the info written and saved to the same file each day(cannot be a new file each day, hence the use of the the following at start of the code, this is a MUST):
health = open('healthy.txt','a+')

Related

why does it go to the else statement when it's a draw?

steen = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
papier = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
schaar = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
import random
list = [steen,papier,schaar]
user = input ("Wat kies je? schaar, steen of papier? ")
if user == 'steen':
print ('')
print ('Jij koos: ')
print (steen)
print ('')
elif user== 'schaar':
print ('')
print ('Jij koos: ')
print (schaar)
print ('')
elif user == 'papier':
print ('')
print ('Jij koos: ')
print (papier)
print ('')
else :
print ("verkeerde ingave")
print ('de computer koos:')
computer = random.choice(list)
print (computer)
***if user == computer:
print ('gelijk!!')***
if user == 'steen' and computer == schaar :
print ('Jij wint')
else :
if user == 'schaar' and computer == papier:
print ('Jij wint')
else:
if user == 'papier' and computer == steen:
print ('Jij wint')
else:
print ('jij verliest\n')
Do NOT use list as a variable name. If you keep the list of choices (which I'll call choices) as strings, it's easier to validate the user entry, and then using the position in that list it's easy to compare the user and computer choices.
Following the graphic setup, you could have:
choices = ('steen','papier','schaar')
graphix = ( steen, papier, schaar )
n_choices = len(choices)
user = input ("Wat kies je? schaar, steen of papier? ")
if user not in choices: # tests against all valid options
print ("verkeerde ingave ", choices)
else :
user_ix = choices.index(user) # use position
print ('')
print ('Jij koos: ')
print ( graphix[user_ix] )
print ('')
computer_ix = random.randrange(n_choices)
print ('de computer koos:')
print ( graphix[computer_ix] )
if user_ix == computer_ix:
print ('gelijk!!')
elif (user_ix + 1)%n_choices == computer_ix:
# modular arithmetic comparison for interest
## you lose to the next in (circular) list
print ('Jij verliest \n')
else:
print ('Jij wint \n')
This also improves input error handling, but further improvement is certainly desirable, for example to allow the user a few tries to make a valid entry.

Quiz Game . If not executing

The problem is that it does not execute the last part of code when the user gives as input "ok",any ideas?. I try also to make it def and call it but the same happened. I am stuck. BTW this if is supposed to give you the choice to choose a different category when you give like an input "ok" if endgame.lower()=="ok":. Thanks a lot for your time.
import requests
import json
import pprint
import random
import html
correctAnswers=0
wrongAnswers=0
input("this is a quiz game,do you want to play? Press enter to start or quit to stop ")
endgame=" "
x=True
url=0
while x==True:
i=1
categorys=["Geography","History","Sports","Animals"]
for category in categorys:
print(str(i) + "- " + category)
i+=1
choise=input("Choose a category: ")
urlChoise=choise
choise = category[int(choise) - 1]
if urlChoise=='1':
url="https://opentdb.com/api.php?amount=1&category=22"
elif urlChoise=='2':
url="https://opentdb.com/api.php?amount=1&category=23"
elif urlChoise=='3':
url="https://opentdb.com/api.php?amount=1&category=21&type=multiple"
elif urlChoise=='4':
url="https://opentdb.com/api.php?amount=1&category=27"
x = False
while (endgame.lower()!="quit"):
r= requests.get(url)
question=json.loads(r.text)
if (r.status_code!=200):
endgame=input("Sorry we run to a problem please try again or type quit ")
else:
data = json.loads(r.text)
print(html.unescape(question['results'][0]['question']))
print("---------------------------------")
answers = data['results'][0]['incorrect_answers']
correct_answer = data['results'][0]['correct_answer']
answers.append(correct_answer)
answer_number=1
random.shuffle(answers)
for answer in answers:
print(str(answer_number) + "- " + html.unescape(answer))
answer_number += 1
useranswer=input("give your answer only with numbers: ")
useranswer = answers[int(useranswer) - 1]
if (useranswer== correct_answer):
print("---------------------------------")
print("you are right")
print("---------------------------------")
correctAnswers+=1
print("Correct Answers: ", correctAnswers, "\n Wrong Answers: ", wrongAnswers)
endgame=input("if you want to continiu press enter else write quit if you want to change category write ok: ")
else:
print("---------------------------------")
wrongAnswers+=1
print("wrong answer the correct one is "+correct_answer)
print("---------------------------------")
print("Correct Answers: ",correctAnswers,"\n Wrong Answers: ",wrongAnswers)
endgame=input("if you want to continiou press enter else write quit if you want to change category write ok: ")
if endgame.lower()=="ok":
x==True
while x == True:
i = 1
categorys = ["Geography", "History", "Sports", "Animals"]
for category in categorys:
print(str(i) + "- " + category)
i += 1
choise = input("Choose a category: ")
urlChoise = choise
choise = category[int(choise) - 1]
if urlChoise == '1':
url = "https://opentdb.com/api.php?amount=1&category=22"
elif urlChoise == '2':
url = "https://opentdb.com/api.php?amount=1&category=23"
elif urlChoise == '3':
url = "https://opentdb.com/api.php?amount=1&category=21&type=multiple"
elif urlChoise == '4':
url = "https://opentdb.com/api.php?amount=1&category=27"
x = False```
the problem is with the
if endgame.lower()=="ok":
x==True
You do not set the x as True. You are asking the program whether the x is True. You have to change it into x = True

Can't assign to function call (python 3)

print ("** ** ***")
print ("** ** ***")
print ("********* ***")
print ("** ** ***")
print ("** ** ***")
Contacts = [0]
if Contacts == [0]:
print ("You have no friends!")
from time import sleep
Contact = input("Would you like to add a contact: Y or N?")
if Contact == "Y":
for c in range(0,1):
print (1 - c)
sleep(1)
Contact = input("Name:")
Contacts.append(Contact)
Contact1 = input ("age:")
Contacts.append(Contact1)
Contact2 = input ("Location:")
Contacts.append(Contact2)
Contact3 = input ("Phone Number:")
Contacts.append(Contact3)
Contactsn = open("Contactsn.txt", "w")
Contactsn.write(Contact)
Contactsn.write(Contact1)
Contactsn.write(Contact2)
Contactsn.write(Contact3)
print (Contact)
print (Contact1)
print (Contact2)
print (Contact3)
Contactsn.close()
Contact = input("Would you like to see your Contacts:Y or N?")
if Contact == "Y":
Contactsn()
else:
Contact = input("Would you like to see your Contacts:Y or N?")
if Contact == "Y":
Contactsn()
def Contactsn():
Contactsn() = open("Contactsn.txt", "r")
print (Contactsn.read())
quit
when I run this it says cant assign function, how can I fix this?
This block is the problem
def Contactsn():
Contactsn() = open("Contactsn.txt", "r")
print (Contactsn.read())
You are trying to assign the result of open to the result of calling your function contactsn()? Either the () is a typo, and you're about to shadow your function name with a variable with the same name, or you are trying some really odd recursive strangeness.

Making an RPG in Python

The code gets stuck within the yes_or_no function right after the user input. No error message, please help! As you can see all I am trying to do is effectuate a simple purchase, I haven't been able to test the buy_something function, and I'm aware that it may have issues.
#!/usr/bin/env python
import time
# Intro
print "Input Name:"
time.sleep(1)
name = raw_input()
print "Welcome to Tittyland brave %s'" %(name)
time.sleep(2)
print "You are given nothing but 500 gold to start you journey..."
time.sleep(2)
print "Good luck..."
time.sleep(3)
print "Shopkeeper: 'Eh there stranger! Looks like you'll need some gear before going into the wild! Check out my store!'"
time.sleep(4)
print ""
#Inventory and first shop
inventory = {
'pocket' : [],
'backpack' : [],
'gold' : 500,
}
shop = {
'dagger' : 50,
'leather armor' : 150,
'broadsword' : 200,
'health potion' : 75,
}
#Buying items
for key in shop:
print key
print "price: %s" % shop[key]
print ""
print "Shopkeeper: So, you interested in anything?"
answer1 = raw_input()
item = raw_input()
def buying_something(x):
for i in shop:
if shop[i] == x:
inventory[gold] -= shop[i]
inventory[backpack].append(shop[i])
def yes_or_no(x):
if x == 'yes':
print "Shopkeeper: 'Great! So what is your desire stranger"
buying_something(item)
else:
print "Shopkeeper: 'Another time then'"
yes_or_no(answer1)
I fixed both your functions. You had your raw_inputs at the wrong place:
def yes_or_no(purchase_q):
if purchase_q == "yes":
while True:
things = raw_input("Great. What is your hearts desire(type no more to exit shop): ")
if things != "no more":
buying_something(things)
else:
print "Good luck on your journey then"
break
def buying_something(item):
if item in shop.keys():
print "You have %s gold available" %(inventory.get('gold'))
print "Item Added {0}: ".format(item)
backpack_items = inventory.get('backpack')
backpack_items.append(item)
item_cost = shop.get(item)
print "Cost of Item is %s gold coins " %(item_cost)
inventory['gold'] = shop.get(item) - item_cost
What happens is that after this line:
print "Shopkeeper: So, you interested in anything?"
you wait for raw input with this answer1 = raw_input()
Then immediately after you type yes or no, you wait for input again item = raw_input()
Tt's not getting stuck or anything, it's just doing as it's told.
print "Shopkeeper: So, you interested in anything?"
answer1 = raw_input()
item = raw_input() // <-- This is in the wrong place
yes_or_no(answer1)
What you've written requires the user to type in the item they want after the yes or no answer, and regardless of a yes or no. I suggest you move the item = raw_input() into your yes_or_no function.
def yes_or_no(x):
if x == 'yes':
print "Shopkeeper: 'Great! So what is your desire stranger"
item = raw_input()
buying_something(item)
else:
print "Shopkeeper: 'Another time then'"

How to assign a Line Number from a text file to a variable?

I am trying to print the variable 'Number' But it come up with a error.
'TypeError: list indices must be integers, not tuple'
I dont understand? What is a tuple and how could i fix this problem?
How do i assign a line number in a text file to a variable?
def CheckDatabase():
print ("====Check Database===== \nA)Would you like to check details? \nB)Check if they are a member?")
TC = input(": ")
if TC == "A" or TC == "a":
NameDetail = input ("Please enter the name you would like to check the details of.\nThis will only work if they are a member\n: ")
with open('Name.txt') as ND:
for number, line in enumerate(ND, 1):
if (str(NameDetail)) in line:
Number = number, line in enumerate(ND, 1)
print ("\nName = ", NameDetail)
A = open("Address.txt", "r")
AData =[line.rstrip() for line in A.readlines()]
print ("Address = ",(AData[Number]))
HN = open("Home Number.txt", "r")
HNData =[line.rstrip() for line in HN.readlines()]
print ("Home Number = ",(HNData[Number]))
MN = open("Mobile Number.txt", "r")
MNData =[line.rstrip() for line in MN.readlines()]
print ("Mobile Number = ",(MNData[Number]))
EAS = open("Email Address.txt", "r")
EAData =[line.rstrip() for line in EAS.readlines()]
print ("Email Address = ",(EAData[Number]))
MDND = open("Email Address.txt", "r")
MDNData =[line.rstrip() for line in MDND.readlines()]
print ("Medical/Dietry Needs = ",(MDNData[Number]))
else:
print ("Person not found!")
EDIT:
import time
def AddToDatabase():
print ("\nYou are adding to the Database. \nA)Continue \nB)Go Back")
ATD = input(": ")
if ATD == "A" or ATD == "a":
Name = input("\nEnter Name of Member [First Name and Surname]: ")
with open("Name.txt", "a") as N:
N.write("\n{}".format(Name))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
print ("\nEnter Address of "+Name+" all on one line")
print ("In format [Include Commas]")
print ("\nRoad name with house number [e.g. 1 Morgan Way], Borough [e.g Harrow], City [e.g London], Postcode [e.g. HA5 2EF]")
Address = input("\n: ")
with open("Address.txt", "a") as A:
A.write("\n{}".format(Address))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Home_Number = input("\nEnter Home Number of "+Name+": ")
with open("Home Number.txt", "a") as HN:
HN.write("\n{}".format(Home_Number))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Mobile_Number = input ("\nEnter Mobile Number of "+Name+": ")
with open("Mobile Number.txt", "a") as MN:
MN.write("\n{}".format(Mobile_Number))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Email_Address = input ("\nEnter Email Address of "+Name+": ")
with open("Email Address.txt", "a") as EA:
EA.write("\n{}".format(Email_Address))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Dietry_Needs = input("\nEnter Medical/Dietry Needs of "+Name+": ")
with open("Medical Dietry Needs.txt", "a") as MDN:
MDN.write("\n{}".format(Dietry_Needs))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
print ("All information for "+Name+" has been added. Redirecting Back To Main...")
time.sleep(5)
Main()
elif ATD == "B" or ATD == "b":
Main()
def CheckDatabase():
print ("====Check Database===== \nA)Would you like to check details? \nB)Check if they are a member?")
TC = input(": ")
if TC == "A" or TC == "a":
NameDetail = input ("Please enter the name you would like to check the details of.\nThis will only work if they are a member\n: ")
with open('Name.txt') as ND:
for number, line in enumerate(ND, 1):
if (str(NameDetail)) in line:
Number, junk = number, line in enumerate(ND, 1)
print ("\nName = ", NameDetail)
A = open("Address.txt", "r")
AData =[line.rstrip() for line in A.readlines()]
print ("Address = ",(AData[number]))
HN = open("Home Number.txt", "r")
HNData =[line.rstrip() for line in HN.readlines()]
print ("Home Number = ",(HNData[Number]))
MN = open("Mobile Number.txt", "r")
MNData =[line.rstrip() for line in MN.readlines()]
print ("Mobile Number = ",(MNData[Number]))
EAS = open("Email Address.txt", "r")
EAData =[line.rstrip() for line in EAS.readlines()]
print ("Email Address = ",(EAData[Number]))
MDND = open("Email Address.txt", "r")
MDNData =[line.rstrip() for line in MDND.readlines()]
print ("Medical/Dietry Needs = ",(MDNData[Number]))
else:
print ("Person not found!")
elif TC == "B" or TC == "b":
NameChoice = input("Enter persons name: ")
with open('Name.txt') as NAME:
for number, line in enumerate(NAME, 1):
if (str(NameChoice)) in line:
print (NameChoice)
print ("is a member")
else:
print ("Not a member!")
def Main():
print ("\nSVA of UK Database")
while True:
print ("\nA)Check Database \nB)Add to Database \nC)Exit Program")
choice = input(": ")
if choice == "A" or choice == "a":
CheckDatabase()
elif choice == "B" or choice == "b":
AddToDatabase()
elif choice == "C" or choice == "c":
break
else:
print ("Invalid Input")
Main()
Main()
EDIT 2:
Name.txt :
Sagar Bharadia
Address.txt
8 John Road
Home Number.txt
02089563524
Mobile Number.txt
02045745854
Medical Dietry Needs.txt
None
EDIT 3:
SVA of UK Database
A)Check Database
B)Add to Database
C)Exit Program
: A
====Check Database=====
A)Would you like to check details?
B)Check if they are a member?
: A
Please enter the name you would like to check the details of.
This will only work if they are a member
: Sagar Bharadia
Name = Sagar Bharadia
1
Traceback (most recent call last):
File "H:\SVA UK PROGRAM\SVA of UK.py", line 126, in <module>
Main()
File "H:\SVA UK PROGRAM\SVA of UK.py", line 114, in Main
CheckDatabase()
File "H:\SVA UK PROGRAM\SVA of UK.py", line 74, in CheckDatabase
print ("Address = ",(AData[Number]))
IndexError: list index out of range
>>>
You define Number as a tuple when you do Number = number, line in enumerate(ND, 1). You already created number, line in enumerate(ND, 1) with your for loop anyway. Why not just use that? i.e. AData[number].
Just using an example, this is what essentially what you are setting Number to:
>>> for x, y in enumerate([1,2,3], 1):
print x, y in enumerate([1,2,3], 1)
1 False
2 False
3 False
It is a tuple containing the number from your for loop, and the value of line in enumerate(ND, 1) (a boolean expression, either it's in there or it's not).
You also have several other problems:
You start number at 1 instead of 0 by providing the 1 to enumerate. In python, list indices start at 0. So if the length of a list is 1 then sub-indexing at [1] is actually out of bounds. You should be doing enumerate(ND) instead to start at 0.
You need to .close() your files that you open(), or use with/as like you do with your first file.
You are opening Email Address.txt twice... did you mean to do that?
In this line:
Number = number, line in enumerate(ND, 1)
You are assigning two values to Number -- this produces a tuple.
You could do something like this:
Number, junk = number, line in enumerate(ND, 1)
This would result in Number being a single value, no longer a tuple.
Tuples are a kind of a "list". See doc on:
http://docs.python.org/release/1.5.1p1/tut/tuples.html
You are probably assigning 2 or more values for the var Number

Categories

Resources