Can't assign to function call (python 3) - python

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.

Related

python basic phonebook application with IO

I had a basic phone book application that adds, lookup, updates, and deletes a record and it works fine. I wanted to add functionality to it in which when I close and restart the program the previously added records are still there saved in a file. And when I want to add more records to the dictionary file it will also be appended to the file but I am running into 2 issues the first one is when I try to integrate my saved file with my dictionary I get error dictionary update sequence element #0 has length 1; 2 is required so I for some reason can't read the file to check if I have a record in the file with the same name for example. The second issue is when I Quit the program I added a save Record function which when run adds the newly added records onto the file to save it before it quits but when I print it, it only shows the first string printed the other is not shown I don't know what is causing this. Any help is appreciated thanks in advance.
#!/usr/bin/python3
import os.path
from os import path
phones = {}
if path.exists('phones.txt'):
with open("phones.txt") as f:
phones = dict(x.rstrip().split(None, 1) for x in f)
else:
phoneFile = open("phones.txt", "w")
print("File Created")
phoneFile.close()
with open("phones.txt") as f:
phones = dict(x.rstrip().split(None, 1) for x in f)
def menu():
print("1. Add a record")
print("2. Lookup a record")
print("3. Update a record")
print("4. Remove a record")
print("5. List all records")
print("6. Quit")
selection = input("Please make your selection from the options above: ")
if(selection == '1'):
addRecord()
menu()
elif(selection == '2'):
lookupRecord()
menu()
elif(selection == '3'):
updateRecord()
menu()
elif(selection == '4'):
removeRecord()
menu()
elif(selection == '5'):
listRecords()
menu()
elif(selection == '6'):
saveRecords()
print("Goodbye")
#exit(0)
else:
print("Sorry, invalid input, try again.")
menu()
def addRecord():
a = str(input("Person's name to add to record: "))
b = int(input("Number to add to record: "))
if a in phones:
print("Name already in records, Please choose another name")
else:
phones[a] = b
print(phones)
def lookupRecord():
a = str(input("Person's name to look: "))
if a in phones:
print(a + "'s number is " + str(phones.get(a)))
else:
print("Person not found")
def updateRecord():
a = str(input("Person's name to update: "))
if a in phones:
b = int(input("New phone number to update: "))
phones[a] = b
print(phones)
else:
print(a + " is not in your phone book")
def removeRecord():
a = str(input("Person's name to remove: "))
if a in phones:
del phones[a]
print(a + " removed from phone book")
else:
print("Name not found")
def listRecords():
for i in phones.items():
print(i)
def saveRecords():
for i in phones.items():
writePhoneFile = open("phones.txt", "w")
finalRecord = ':'.join('%s' %id for id in i)
writePhoneFile.write(finalRecord)
readPhoneFile = open("phones.txt", "r+")
print(readPhoneFile.read())
def main():
print("== Welcome to the Phonebook App ==")
menu()
if __name__ == "__main__":
main()
use below because phone number in integer :
phones = dict( (x.rstrip().split(':')[0] , int(x.rstrip().split(':')[1])) for x in f)
in addition, open the file outside for loop in saverecords:
writePhoneFile = open("phones.txt", "w")
for i in phones.items():
print(i)
finalRecord = ':'.join('%s' %id for id in i)+'\n'
writePhoneFile.write(finalRecord)
writePhoneFile.close()

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

Trying to make it where you can select books from a list and then gives an itemized receipt at the end using python

Using python I am trying to make it where the books in a text file display and the user can select a book and a quantity and do this in a loop. As they do this it is supposed to save it to a text file as a receipt and print it out when the user is done making their selections. This is what I've been able to accomplish so far.
cusName = input("What is your name?")
def main():
def menu():
print("Here is a list of items that we have:")
books_file= open("Books.txt","r")
lines = books_file.readlines()
aryBooks = []
for line in lines:
print(line)
bookChoice = input("Which book would you like?")
bookQty = input("You chose", bookChoice , "How many would you like?")
print ("Qty:", bookQty)
print ("Item:", bookChoice)
price = print ("Price:", book[2])
print ("SubTotal:", price * bookQty)
repeat = input("Would you like another item? Y or N")
receipt_file= open("receipt.txt","w")
lines = receipt_file.writelines()
for i in range(0,len(aryBooks)):
print(i + 1, aryBooks[i])
Try the code below:
def menu():
# Main loop for shopping
cart = {}
# Read books here
books = read_books()
while True:
# Loop until user does not want to shop any longer
print("Here is a list of items that we have:\n")
for book_num, (book_name, book_price) in books.items():
print(f'#{book_num}: {book_name} -- ${book_price}')
bookChoice = input("Which book would you like? (Please enter a number)\n")
# Make sure user enters the right number
try:
price = books[bookChoice][1]
except:
print('Sorry you chose the wrong number')
print()
continue
bookQty = int(input(f"You chose {books[bookChoice][0]}. How many would you like?\n"))
subtotal = price * bookQty
cart[books[bookChoice][0]] = (bookQty, subtotal)
print (f"Qty: {bookQty}")
print (f"Item: {books[bookChoice][0]}")
print (f"Price: {price}")
print (f"SubTotal: {subtotal}")
repeat = input("Would you like another item? Y or N\n")
# End loop if answer was No
if repeat.lower() == 'n' or repeat.lower == "no":
print(f'Your total was: {sum([y for x, y in cart.values()])}')
generate_receipt('receipt.txt', books, cart)
print('Have a good day!\n')
break
else:
print('Here is what you have thus far:')
for name, (qty, sub) in cart.items():
print(f'Name: {name} ; Qty: {qty} ; Subtotal: {sub}')
print()
def generate_receipt(path_to_receipt, books, cart):
# Generate receipt based on shopping cart
with open(path_to_receipt, 'a') as receipt_file:
for name, (qty, subtotal) in cart.items():
receipt_file.write(f'Qty: {qty} ; Item: {name}; Total: {sum([y for x, y in cart.values()])}; Subtotal: {subtotal}\n')
def main():
# Main loop that starts the shopping
cusName = input("What is your name?\n")
print(f'Hi {cusName}. Welcome to the bookstore!')
menu()
def read_books(path_to_books="Books.txt"):
# Read in the books from the file
with open(path_to_books, 'r') as f:
books = f.readlines()
books = [book.strip().split(',') for book in books]
books = {book_num: (book_name, int(book_price)) for book_num, book_name, book_price in books}
return books
if __name__ == '__main__':
main()
The output file might not be what you want but that can be fixed really easily.
My Books.txt is as follows:
15,Harry Potter,20
2,LOTR,25

I am trying to create an address book program that will append user input to its appropriate list

I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()

update and save data to a .txt file daily

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+')

Categories

Resources