Calling specific objects within a list in python? - python

I've defined the following:
class SMSMessage(object):
def __init__(self, hasBeenRead, messageText, fromNumber):
self.hasBeenRead = hasBeenRead
self.messageText = messageText
self.fromNumber = fromNumber
hasBeenRead = "False"
fromNumber = "07189202003"
With the following functions:
def MarkAsRead(self):
if hasBeenRead == "False":
return hasBeenRead == "True"
def add_sms():
sms1 = (hasBeenRead, messageText, fromNumber)
return SMSStore.append(sms1)
def get_count():
return len(SMSStore)
def get_message(i):
for i in SMSStore:
return messageText
def get_unread_messages(i):
for i in SMSStore:
if hasBeenRead == "False":
return messageText
This is the Logic for the SMS simulation where a user is meant to send messages to a list (SMSStore[ ]) and then recall specific messages from the list:
userChoice = ""
while userChoice != "quit":
userChoice = raw_input("What would you like to do - read/send/quit?")
if userChoice == "read":
unreadChoice = raw_input("Would you like to retrieve all unread messages or one of your own choice? - all unread/custom ")
if unreadChoice == "custom":
messageNo = int(raw_input("Please enter which messsage number you want to read: "))
print get_message(messageNo)
print MarkAsRead(messageNo)
elif unreadChoice == "all unread":
print get_unread_messages(hasBeenRead)
else:
print "incorrect entry"
elif userChoice == "send":
messageText = raw_input('Please type in your message')
add_sms()
print SMSStore
My main issue is that I am able to send the (hasBeenRead, messageText, fromNumber) to SMSStore but when trying to read I can't seem to return the messagetext of the user selected messageNo. It always returns the messageText of the last item in the list. I'm still new to coding so any help would be greatly appreciated.
Thanks

I'm not sure what is the role of SMSStore, but this block of code looks suspicious to me:
def get_message(i):
for i in SMSStore:
return messageText
Why are you iterating the SMSStore but just to return messageText ? Would that be a missing Indent over there ?

Related

Can I add two VALUES to a dictionary from user input?

I keep getting an error when I run this functions. Everything goes through and then it shows this error. I have tried adding .items() to the end when I print the dictionary and still throws this error.
CLARIFICATION just realized. Not getting any type errors or anything. It prints fine but when doesn't add the second variable to the dictionary. Instead it prints this..
{'Frappe': ('small', function type_of_milk at 0x000002BE2BCD2F78>)}
def order():
ready_to_order = True
while ready_to_order != False:
ordering_q = input(
"""Do you know what you would like to order or do you need to see the menu?
[M]enu or [R]eady to order or [Q]uit: """)
if ordering_q.upper() == "Q":
sys.exit()
elif ordering_q.upper() == "M":
print(Menu())
elif ordering_q.upper() == "R":
ready_to_order = False
else:
print("Please enter valid letters only, try again.")
print(" ")
print(" ")
add_cart = True
while add_cart != False:
order1 = input("What would you like to order?")
if order1.upper() == "Done":
add_cart = False
elif order1 == 'a1':
print("Frappe added to cart")
global total_order
total_order += 3
drink_size()
type_of_milk()
order_dict['Frappe'] = (drink_sizes, type_of_milk)
add_cart = False
print(order_dict)
This line:
order_dict['Frappe'] = (drink_sizes, type_of_milk)
is adding the function type_of_milk to your dict, which is why you see function type_of_milk at 0x000002BE2BCD2F78> when you print the dict out. Maybe you meant to say type_of_milk()?

Calling a method from farther down the stack

Ok I have a code that's basically this....
def create():
#long list of print statements
m_commands()
def get_desc():
#print statement
m_commands()
def m_commands():
while close != True:
input = input(str(">>>"))
If inp == "close" or "quit":
close = True
If inp == "create":
create()
If inp == "describe":
get_desc()
m_commands()
I need to call m_commands() in create() and get_desc() to continue continuity. Is this possible. Sorry in advance, I don't know how to put code in a spoiler thingy. Thanks!
def create():
#long list of print statements
print("hello")
m_commands()
def get_desc():
#print statement
print("world")
m_commands()
def m_commands():
close=False
while close != True:
inp = input(str(">>>"))
if inp == "close" or "quit":
close = True
if inp == "create":
create()
if inp == "describe":
get_desc()
m_commands()
This is working for me though.

How to properly use __repr__ when two classes are involved

I am working on some Python code where I create a basic ATM. The issue I am having is I am not able to get the result that I want its printing "<'function Account.balance at 0x012CBC90>" Instead of the actual balance number. So far I have only tested using jsmith. Feel free to call out any other issues that may cause a problem later.
class Account:
def __init__(self,user,pin,balance):
self.user = user
self.pin = pin
self.balance = int(balance)
def get_user(self):
return self.user
def get_pin(self):
return self.pin
def balance(self):
return int(self.balance)
def setBalance(self,newBalance):
self.balance = newBalance
def __repr__(self):
return str(self.user) + " " + str(self.pin) + " " + str(self.balance)
class ATM:
def withdraw(self,Person,amount):
result = Person - amount
return result
def check(self,Person):
Person = Account.balance
return str(Person)
def transfer(self,id1,id2):
pass
def __str__(self):
return self
def main():
Chase = ATM()
Database = []
Teron_Russell = Account("trussell",1738,0)
Joe_Smith = Account("jsmith",1010,1350)
print(Teron_Russell)
Database.append(Teron_Russell)
Database.append(Joe_Smith)
print("Welcome to the ATM")
id = input("Please enter your user ID: ")
pin = input("Enter your pin: ")
chosen = ""
for i in Database:
print("Test1")
name = Account.get_user(i)
print(name)
checkPin = Account.get_pin(i)
print(checkPin)
if id == name and pin == checkPin:
chosen = i
choice = input("What would you like to do. (Type 'Check','Withdraw','Transfer': ")
if(choice == "Check" or "check"):
print(Chase.check(chosen))
# if(choice == "Withdraw" or "withdraw"):
# wAmount = eval(input("How much would you like to Withdraw: "))
# # Chase.withdraw(Account.balance,)
# elif(choice == "Check" or "check"):
# Chase.check()
# else:
# print("Invalid Choice!")
if __name__ == "__main__":
main()
You named a variable and a method the same name, so the interpreter is confused on which one to use. Change the name of either the method or variable balance and you won't have this problem. Additionally, this isn't java, and you shouldn't use classes for no reason. Since you aren't using any instance variables, it is pointless to have all of those methods inside that class.

Issue doing a basic option menu system - Aways getting the message "Option not available"

Im showing some text options associated to numbers and then I want to execute some functions based on number that user enter.
First user need to choose 1 or 2, when user choose 1 it is working fine.
But when user choose 2 then I ask user to select other option, and when user choose any number it is always showing option not available.
But I just want to show this message when user choose a number that isnt 3,4,5 or 7.
Do you see where the issue is and how to fix this logic?
def nav(number):
while True:
input = raw_input(number)
if input == "1":
upload()
return False
elif input == "2":
results = table.get()
# here I show the name of users from database
for r in results:
print r["name"]
print " 3 - Add user"
print " 4 - Edit user"
print " 5 - Remove user"
print " 7 - Exit"
nav("Select an option: ")
if input == "":
print "field is empty"
if input == "3":
addUser()
return False
if input == "4":
removeUser()
if input== "5":
editUser()
elif input== "7":
return False
else:
print "Option not available"
def main():
print " 1 - Users managment"
print " 2 - Upload Files"
print " 7 - Exit"
nav("Select an option: ")
main()
You should have two functions. One that asks you to choose an option and one that parses that choice. For instance:
def upload():
# does whatever upload does....
def user_mgmt():
def adduser():
"""Adds a new user"""
pass
def edituser():
"""Edits an existing user"""
pass
def deluser():
"""Deletes an existing user"""
pass
response_options = {'3': ('add user', adduser),
'4': ('edit user', edituser),
'5': ('remove user', deluser),
'7': ('exit', sys.exit)}
response_func = make_choice(response_options)
response_func()
def nav():
response_options = {'1': ('manage users', user_mgmt),
'2': ('upload', upload),
'7': ('exit', sys.exit)}
response_func = make_choice(response_options)
response_func()
def make_choice(optiontable):
for resp, msg_func in optiontable.items():
msg, _ = msg_func
print("{} - {}".format(resp, msg))
usr_resp = raw_input(">> ")
try:
result = optiontable[usr_resp][1]
except KeyError:
raise # let the caller handle it
return result
This is actually a pretty good use case for a collections.namedtuple
from collections import namedtuple
Choice = namedtuple("Choice", ['msg', 'callback'])
def nav():
response_options = {'1': Choice(msg="Add user", callback=adduser),
...}
result = make_choice(response_options)
if result is None:
# improper user input -- handle it
else:
result.callback()
def make_choice(optiontable):
for resp, choiceobj in optiontable.items():
print("{} - {}".format(resp, choiceobj.msg))
usr_resp = raw_input(">> ")
return optiontable.get(usr_resp, None)

Personal archive tool, looking for suggestions on improving the code

i've written a tool in python where you enter a title, content, then tags, and the entry is then saved in a pickle file. it was mainly designed for copy-paste functionality (you spot a piece of code you like on the net, copy it, and paste it into the program), not really for handwritten content, though it does that with no problem.
i mainly did it because i'm always scanning through my pdf files, books, or the net for some coding example of solution that i'd already seen before, and it just seemed logical to have something where you could just put the content in, give it a title and tags, and just look it up whenever you needed to.
i realize there are sites online that handle this ex. http://snippets.dzone.com, but i'm not always online when i code. i also admit that i didn't really look to see if anyone had written a desktop app, the project seemed like a fun thing to do so here i am.
it wasn't designed with millions of entries in mind, so i just use a pickle file to serialize the data instead of one of the database APIs. the query is also very basic, only title and tags and no ranking based on the query.
there is an issue that i can't figure out, when you are at the list of entries there's a try, except clause where it tries to catch a valid index (integer). if you enter an inavlid integer, it will ask you to enter a valid one, but it doesn't seem to be able to assign it to the variable. if you enter a valid integer straightaway, there are no problems and the entry will display.
anyway let me know what you guys think. this is coded for python3.
main file:
#!usr/bin/python
from archive_functions import Entry, choices, print_choice, entry_query
import os
def main():
choice = ''
while choice != "5":
os.system('clear')
print("Mo's Archive, please select an option")
print('====================')
print('1. Enter an entry')
print('2. Lookup an entry')
print('3. Display all entries')
print('4. Delete an entry')
print('5. Quit')
print('====================')
choice = input(':')
if choice == "1":
entry = Entry()
entry.get_data()
entry.save_data()
elif choice == "2":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "3":
queryset = 'all'
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
elif choice == "4":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
entry = result[choices(result)]
entry.del_data()
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "5":
break
else:
input('please enter a valid choice...')
main()
if __name__ == "__main__":
main()
archive_functions.py:
#!/bin/usr/python
import sys
import pickle
import os
import re
class Entry():
def get_data(self):
self.title = input('enter a title: ')
print('enter the code, press ctrl-d to end: ')
self.code = sys.stdin.readlines()
self.tags = input('enter tags: ')
def save_data(self):
with open('entry.pickle', 'ab') as f:
pickle.dump(self, f)
def del_data(self):
with open('entry.pickle', 'rb') as f:
data_list = []
while True:
try:
entry = pickle.load(f)
if self.title == entry.title:
continue
data_list.append(entry)
except:
break
with open('entry.pickle', 'wb') as f:
pass
with open('entry.pickle', 'ab') as f:
for data in data_list:
data.save_data()
def entry_query(file, queryset):
'''returns a list of objects matching the query'''
result = []
try:
with open(file, 'rb') as f:
entry = pickle.load(f)
os.system('clear')
if queryset == "all":
while True:
try:
result.append(entry)
entry = pickle.load(f)
except:
return result
break
while True:
try:
if re.search(queryset, entry.title) or re.search(queryset, entry.tags):
result.append(entry)
entry = pickle.load(f)
else:
entry = pickle.load(f)
except:
return result
break
except:
print('no entries in file, please enter an entry first')
pause = input('\nPress [Enter] to continue...')
def choices(list_result):
'''takes a list of objects and returns the index of the selected object'''
os.system('clear')
index = 0
for entry in list_result:
print('{}. {}'.format(index, entry.title))
index += 1
try:
choice = int(input('\nEnter choice: '))
return choice
except:
pause = input('\nplease enter a valid choice')
choices(list_result)
def print_choice(list_result, choice):
'''takes a list of objects and an index and displays the index of the list'''
os.system('clear')
print('===================')
print(list_result[choice].title)
print('===================')
for line in list_result[choice].code:
print(line, end="")
print('\n\n')
back_to_choices(list_result)
def back_to_choices(list_result):
print('1. Back to entry list')
print('2. Back to Main Menu')
choice = input(':')
if choice == "1":
print_choice(list_result, choices(list_result))
elif choice == "2":
pass
else:
print('\nplease enter a valid choice')
back_to_choices(list_result)
In the else, you call the main function again recursively. Instead, I'd do something like choice == "0", which will just cause the while loop to request another entry. This avoids a pointless recursion.

Categories