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

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()?

Related

My 'if' statement is not changing my 'while' loop to False

I am working through a course where this has come up a few times now, and I've not been able to get it right.
**Edit: I have solved this now. I used a while loop, "while bidding:", then within that while loop I was able to create an 'if' statement to impact the 'bidding' variable. A function was the wrong idea for this code. **
I am creating a variable that = True early on in the code, then while it is True, running a function. Within that function is an 'if' statement that should be changing the variable to False, stopping the function, but it doesn't. I think I must have the code in the wrong order or maybe the wrong indentation.
Here is the relevant code.
bidding = True
bidder = input("What is your name?: ")
bid_amount = int(input("What's your bid?: $"))
more_bidders = input("Are there any other bidders? Type 'yes' or 'no'. \n").lower
def add_to_dict(bidder_name, dollar_amount, anyone_else):
bidder_dict[bidder_name] = dollar_amount
if anyone_else == "no":
bidding = False
while bidding:
add_to_dict(bidder_name = bidder, dollar_amount = bid_amount, anyone_else = more_bidders)
I run the code fine, I type "no" when it asks if there's any more bidders, and it just pauses because it thinks "bidding" is still True. So my 'if' statement isn't doing what I need it to, but I don't know why.
Without changing your code much, you can use global:
def add_to_dict(bidder_name, dollar_amount, anyone_else):
global bidding
bidder_dict[bidder_name] = dollar_amount
if anyone_else == "no":
bidding = False
while bidding:
add_to_dict(bidder_name = bidder, dollar_amount = bid_amount, anyone_else = more_bidders)
A better solution would be to return bidding from add_to_dict():
def add_to_dict(bidder_name, dollar_amount, anyone_else):
bidder_dict[bidder_name] = dollar_amount
if anyone_else == "no":
return False
return True
while bidding:
bidding = add_to_dict(bidder_name = bidder, dollar_amount = bid_amount, anyone_else = more_bidders)
I believe the issue is coming from the comparison in the if statement. You are seeing if the string in anyone_else is equal to "no" but you have the variable more_bidders taking in the string "yes" or "no. So I recommend either change anyone_else to more_bidders or initialize anyone_else with more_bidders before the if statement.
you can try in this way:
bidding = True
bidder_dict = {}
bidder = ""
bid_amount = 0
more_bidders = "yes"
def add_to_dict():
bidder = input("What is your name?: ")
bid_amount = int(input("What's your bid?: $"))
more_bidders = str(input("Are there any other bidders? Type 'yes' or 'no'. \n"))
bidder_dict[bidder] = bid_amount
print(more_bidders)
if more_bidders == "no":
return False
else:
return True
while bidding:
if add_to_dict():
print("OK")
else:
print("Terminou")
break
print(bidder_dict)

how to make a login by using the Pin

status_login = False
use_atm = "y"
data =[{"norek":932012042,
"pin":123,
"name":"grizly",
"bank":"BCA",
"balance":5000000},
{"norek":932012052,
"pin":1234,
"name":"Basuki Pepeh",
"bank":"BRI",
"balance":4000000},
{"norek":932012099,
"pin":1235,
"name":"Bambang Gentolet",
"bank":"Mandiri",
"balance":3500000}]
def cek_login(p):
for login in data:
if login['pin'] == p:
return login
return False
while use_atm == "y":
while status_login == False:
print("Welcome to ATM")
print("insert your pin")
pin = input("PIN : ")
if cek_login(pin) != False:
print("welcome "+cek_login(pin)['name'])
status_login = True
else:
print("")
print("Ops Your PIN is wrong")
print("")
print("")
I want to make a login using a pin but why the result is always wrong, what is wrong with the code above
Welcome to ATM
insert your pin
PIN : 123
Ops Your PIN is wrong
The pin in your data is int.
input is str.
str is not equal to int.
pin = int(input("PIN : "))
Your comparison is failing in cek_login, so print the values using repr() and see why they don't compare. Note that repr() gives a debugging representation of the data so it is easier to spot differences:
def cek_login(p):
for login in data:
print(repr(long['pin']),repr(p)) # see why they don't compare
if login['pin'] == p:
return login
return False
You will see:
Welcome to ATM
insert your pin 123
123 '123' # note integer versus string (quoted).
1234 '123'
1235 '123'
Convert the input to an integer to fix the problem.
pin = int(input("PIN : "))
You'll also find that you will enter an infinite loop after getting the pin correct, because use_atm never changes.
Learn to use a source debugger so you don't have to litter your code with print statements.
There were a couple bugs here, and some other people already pointed them out:
cek_login(p) uses data, which is a list of dictionaries, so you need to first access the dictionary in the list by index ([0], [1], ...), and THEN access the dictionary element with bracket notation like ['pin']
data[0]['pin'] is an int, whereas the result of input() is a str, so you need to CONVERT the str to an int with int(my_str_input)
Similar to point 1, the print statement under the while loop which prints the user's name needs to first access the index in the list (data) before accessing the dictionary value ([name])
Try this:
status_login = False
use_atm = "y"
data =[{"norek":932012042,
"pin":123,
"name":"grizly",
"bank":"BCA",
"balance":5000000},
{"norek":932012052,
"pin":1234,
"name":"Basuki Pepeh",
"bank":"BRI",
"balance":4000000},
{"norek":932012099,
"pin":1235,
"name":"Bambang Gentolet",
"bank":"Mandiri",
"balance":3500000}]
def cek_login(p):
print(int(p))
print(data[0]['pin'])
if data[0]['pin'] == int(p):
return True
return False
while use_atm == "y":
while status_login == False:
print("Welcome to ATM")
print("insert your pin")
pin = input("PIN : ")
if cek_login(pin) != False:
print("welcome "+ data[0]['name'])
status_login = True
use_atm = "n"
else:
print("")
print("Ops Your PIN is wrong")
print("")
print("")

Score function for a flashcard game in python

I am trying to add a very simple score function to an also very simple flashcard game and I can't make the game remember the value of the variable containing the score (it always resets it 0). The score is obviously relying on the honesty of the user (and that's fine) that has to press "Y" when guessing the word.
from random import *
def add_score():
pos_score = 0
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
pos_score += 1
print(pos_score)
def show_flashcard():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
def add_flashcard():
""" This function allows the user to add a new
word and related value to the glossary. It will
be activated when pressing the "a" button.
"""
key = input("Enter the new word: ")
value = input("Enter the definition: ")
glossary[key] = value
print("New entry added to glossary.")
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
add_score()
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')
Some notes:
I am aware that right now only the positive score is implemented in the code, but I figured it would be better to proceed step by step and have that working first.
Problem
In your def add_score(), you initialise the variable to 0 every time. Also, it is a local variable, which means you can only reference it from within your function add_score(). This means that every time you exit that function, that variable is completely deleted.
Solution
You need to make that a global variable, that is, initialise it to 0 at the start of the game, and outside your function. Then inside your add_score you simply reference to the global variable and increase it without initialising it every time:
from random import *
def add_score():
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
global pos_score
pos_score += 1
print(pos_score)
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
pos_score = 0 #NOTE you initialise it here as a global variable
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
add_score()
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')
Note I skipped the irrelevant functions. However, usually changing the scope of variables like this is considered bad practice. What you should do is either have a class -- a bit overly complicated for this example -- or return a value to add from your add_score and add that value in the main loop. This would be the code:
from random import *
def add_score():
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
#global pos_score
#pos_score += 1
#print(pos_score)
return 1
return 0
def show_flashcard():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
def add_flashcard():
""" This function allows the user to add a new
word and related value to the glossary. It will
be activated when pressing the "a" button.
"""
key = input("Enter the new word: ")
value = input("Enter the definition: ")
glossary[key] = value
print("New entry added to glossary.")
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
pos_score = 0 #NOTE you initialise it here as a global variable
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
pos_score += add_score()
print(pos_score)
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')

Adding items to shopping List Python

I'm learning Python and I'm trying to make shopping List
where you can add items
first it will ask you to add the items if the shopping list is empty
it will be added automatically if not it will ask you where you would like
to put the item (index)
but also I'm trying to make the program exit in certain condition like DONE
or HELP or SHOW but even that i put a condition for that but it's not working can anyone help me with this
hope I explained enough
import os
shopping_list =[]
# Function for clearing the screen
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def show_help():
print("Enter 'Done' if you finish adding item \n Enter 'Show' to show your items \n Enter 'Help' toshow this help ")
# Function to show the items that you've entered to the list
def show_item():
clear_screen()
index = 1
for item in shopping_list:
print("{} {}.".format(index,item))
index += 1
# Function to add items to the list
def add_to_list():
while True:
new_item = input("Please enter the item that you would like to add to your shopping list ")
if shopping_list and ((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW")):
position = input("Where you would like to add {} to the list \n press 'Enter' if you want to add to the end of the list".format(new_item))
position = abs(int(position))
shopping_list.insert(position - 1 , new_item)
show_item()
else:
if new_item.upper() == "DONE":
break
elif new_item.upper() == "SHOW":
show_item()
continue
elif new_item.upper() == "HELP":
show_help()
continue
else:
shopping_list.append(new_item)
show_item()
show_help()
add_to_list()
Welcome to stackoverflow. I think your logic statement is wrong, you need and instead of or. Right now all you need for the statement in the parentheses to be true, is that new_item.upper() is at least not one of those three words. It actually can't equate to False since two of the three are always true.
((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
If you have for example done the first statement is False ,but the other two are True, adding up to True in or-Statements.
>>> new_item = 'done'
>>> print((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
True

Calling specific objects within a list in 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 ?

Categories