Validate dictionary membership with an if statement - python

I'm writing this code to verify that a user-provided value and key match what I have in my dict. When they match, the Welcome portion of the code will run, but if one of them is wrong then it will have to run the else statement.
name = input("Name: ")
code = input("Code: ")
users = {'rafiki':'12345', 'wanjiru':'12334', 'madalitso':'taxpos'}
if _______ in users: #at this point is where i need your support, yoverify both key and its value at once.
print ("Welcome back %s " % username)
else:
print ("Please check if your name or Code are correctly spelled")

In a single operation:
if users.get(name) == code:
Because dict.get return None for an unknown key instead of throwing a KeyError

Use this:
if name in users and users[name] == code:
print "Welcome back %s" % username

This should work:
if name in users and code == users[name]:

Related

How can I create an input that will loop and create a new list each time?

in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')

Error while getting input added into list

I am attempting to create a program that asks for the user to enter his/her name and records the input into a list (Was working towards dictionary but seems like I made a boo boo!) but it is returning with "TypeError: can only concatenate list (not "str") to list". The following is the code.Thanks in advance.
namedic = []
while True:
print ("Please, enter your name:")
name = input()
if len(name) > 3:
print ("Welcome")
else:
print ("Ew, your name have less than 4 letters! Gross! Try a new one")
continue
namedic = namedic + name
print ("Ah, your name have at least 4 words, good name.")
for name in namedic:
print (name)
Your erroring line is namedic = namedic + name. What you're trying to do is add a list (namedic) to a string (name). You should do namedic.append(name) instead.
The + operator isn't used to append elements to a list, as the error shows. You can use the append method for that:
namedic.append(name)
#your code should rather be like this;
namedic = []
while True:
print ("Please, enter your name:")
name = input()
if len(name) > 3:
print ("Welcome")
else:
print ("Ew, your name have less than 4 letters! Gross! Try a new one")
continue
namedic.append(name)
print ("Ah, your name have at least 4 words, good name.")
for name in namedic:
print (name)

Issues with my Python login script. Invalid syntax on try

I am having issues with the current program that I am trying to write. I don't understand why it keeps saying this or why.
Also can this code be extended to cover IP logging and making sure multiple users can be logged in on the same IP in theory?
Here is the code:
import hashlib
import time
#cPickle is faster then pickle but not available in all python releases
#thats why i used a try/accept there
try: import cPickle as cp
#load the database if it exist, if not it create one
try:
f =(r"C:\Users\Owner\Desktop\python\database.data")
data = cp.load(f)
except IOError:
data = {}
#A simple function made to make data dumping easy
def easyDump(data_):
f = file(r"C:\Users\Owner\Desktop\python\database.data", "w")
cp.dump(data_, f)
f.close()
#Get's the date (We'll use this as the custom salt)
def getData():
return str(time.strftime("%d-%m-%Y"))
#A function which accepts two parameters, password and date.
#The date is the custom salt. It returns the sha512 hash excetpyion
def salt(password, date):
salted = hasglib.sha512(password + str(data)).hexdigest()
retun str(salted)
menu = """"
1.Login
2.Register
3.Exit
"""
while True:
print menu
choice = int(raw_input("Your choice please: "))
if choice ==1:
username = raw_input("Enter your username please: ")
password = raw.input("Enter your authentication code please: ")
#if the username is found on the database
if data.has_key(username):
#date is equal to our secured stored data
date = date[username][1]
#check of the given password + date is equal to what is stored on the database
#password
if salt(password, date) == date[username][0]:
print"Welcome %s!" % username
else:
print "Incorrect password"
else:
print "user %s not found, please register!" % username
elif choice == 2:
username = raw_input("Please enter yout username: !")
password = raw_input("Please enter your password: !")
#if username exists in the system already then the name is taken
if data.has_key(username):
print "user %s already registered, please put in another % username
else:
#in order words data = {username: hash, date}
data[username] = [salt(password, getData()), get Data()]
easyDump(data)
print "user %s successfully registereed!" %username
elif choice == 3:
print "goodbye!"
break
else:
print "invaid input or commands"
This code:
try: import cPickle as cp
is not followed by an except ... hence the syntax error
Your code contains many indenting, syntax errors and spelling mistakes. The following fixes these to allow it to at least run:
import hashlib
import time
#cPickle is faster then pickle but not available in all Python releases
#That is why I used a try/accept there
try:
import cPickle as cp
except:
import pickle as cp
#load the database if it exist, if not it create one
try:
f = open(r"C:\Users\Owner\Desktop\python\database.data")
data = cp.load(f)
except IOError:
data = {}
#A simple function made to make data dumping easy
def easyDump(data_):
f = file(r"C:\Users\Owner\Desktop\python\database.data", "w")
cp.dump(data_, f)
f.close()
#Get's the date (We'll use this as the custom salt)
def getData():
return str(time.strftime("%d-%m-%Y"))
#A function which accepts two parameters, password and date.
#The date is the custom salt. It returns the sha512 hash exception
def salt(password, date):
salted = hasglib.sha512(password + str(data)).hexdigest()
return str(salted)
menu = """"
1.Login
2.Register
3.Exit
"""
while True:
print menu
choice = int(raw_input("Your choice please: "))
if choice == 1:
username = raw_input("Enter your username please: ")
password = raw.input("Enter your authentication code please: ")
#if the username is found on the database
if data.has_key(username):
#date is equal to our secured stored data
date = date[username][1]
#check of the given password + date is equal to what is stored on the database
#password
if salt(password, date) == date[username][0]:
print"Welcome %s!" % username
else:
print "Incorrect password"
else:
print "user %s not found, please register!" % username
elif choice == 2:
username = raw_input("Please enter yout username: !")
password = raw_input("Please enter your password: !")
#if username exists in the system already then the name is taken
if data.has_key(username):
print "user %s already registered, please put in another" % username
else:
#in order words data = {username: hash, date}
data[username] = [salt(password, getData()), getData()]
easyDump(data)
print "user %s successfully registered!" % username
elif choice == 3:
print "goodbye!"
break
else:
print "invalid input or commands"
Indenting in Python is very important, getting it wrong can completely change the meaning of the code.

Python - input control

I have problem with users input control in one function in Python 3.4.
def input_name (*args):
name_output = ""
name_input = input ("Give first name: ")
if name_input.isalpha() and name_input[0].isupper() == True:
name_output += name_input
return (name_output)
else:
print ("Wrong, do it again")
input_name ()
name = input_name()
print(name.lower())
I am trying to catch users wrong input - so the name must be alphabetical and first letter must be uppercase. In future code I will create users login name with lowercase letters, so I am trying to print users name with small leters for login name. And there is problem.
When I type name firs time well, it's ok
When I type first time name with 1 lowercase letter (name) and then I write it correctly (Name), it tells me Error, I don't understand why. Can you tell me, what is my mistake?
Thank you very much for showing the path.
Mirek
The error is caused by the last line. Since your input is wrong the first time, the function returns None, so name.lower() raises an exception. I wouldn't use recursion in this case.
def input_name():
while True:
name_input = input ("Give first name: ")
if name_input.isalpha() and name_input[0].isupper():
return name_input
else:
print ("Wrong, do it again")
name = input_name()
print(name.lower())
Hope it helps!

Having trouble parsing a txt file into a list full of zip codes in my zipcode lookup program

Hello everyone thanks for looking into my problem. What I am trying to do is write a "Structured" program in python that takes txt from a file and parses it into lists. Then after closing the file, I need to reference the user input (zipcode) in those lists and then print out the city and state according to the zipcode that they entered. My instructor is having us use structure by making several functions. I know there are probably lots of more efficient ways of doing this, but I must keep the structure thats in place.
EDIT
Here is my code(Current):
#-----------------------------------------------------------------------
# VARIABLE DEFINITIONS
eof = False
zipRecord = ""
zipFile = ""
zipCode = []
city = []
state = []
parsedList = []
#-----------------------------------------------------------------------
# CONSTANT DEFINITIONS
USERPROMPT = "\nEnter a zip code to find (Press Enter key alone to stop): "
#-----------------------------------------------------------------------
# FUNCTION DEFINITIONS
def startUp():
global zipFile
print "zipcode lookup program".upper()
zipFile = open("zipcodes.txt","r")
loadList()
def loadList():
while readRecord():
pass
processRecords()
def readRecord():
global eof, zipList, zipCode, city, state, parsedList
zipRecord = zipFile.readline()
if zipRecord == "":
eof = True
else:
parsedList = zipRecord.split(",")
zipCode.append(parsedList[0])
city.append(parsedList[1])
state.append(parsedList[2])
eof = False
return not eof
def processRecords():
userInput = raw_input(USERPROMPT)
if userInput:
print userInput
print zipCode
if userInput in zipCode:
index_ = zipcode.index(userInput)
print "The city is %s and the state is %s " % \
(city[index_], state[index_])
else:
print "\nThe zip code does not exist."
else:
print "Please enter a data"
def closeUp():
zipFile.close()
#-----------------------------------------------------------------------
# PROGRAM'S MAIN LOGIC
startUp()
closeUp()
raw_input("\nRun complete. Press the Enter key to exit.")
Here is a sample from the zipcode txt file:
00501,HOLTSVILLE,NY
I am definitely stuck at this point and would appreciate your help in this matter.
EDIT
Thanks for all the help everyone. I really do appreciate it. :)
why you fill the lists zipcode, city , state like that, i mean in each user entry we get the next line from the file
i think that you should do :
def loadList():
# Fill all the list first , make the readRecord() return eof (True or False).
while readRecord():
pass
# than process data (check for zip code) this will run it only one time
# but you can put it in a loop to repeat the action.
processRecords()
about your problem :
def processRecords():
userInput = raw_input(USERPROMPT)
# Check if a user has entered a text or not
if userInput:
# check the index from zipcode
if userInput in zipcode:
# the index of the zipcode in the zipcode list is the same
# to get related cities and states.
index_ = zipcode.index(userInput)
print "The city is %s and the state is %s " % \
(city[index_], state[index_])
else:
print "\nThe zip code does not exist."
else:
print "Please enter a data"
one of the beauties of Python is that it's interactive. if you take processRecords() out of loadList(), and then at the bottom of your program put:
if __name__ == '__main__':
processRecords()
Then, from the command prompt, type "python". You'll get the Python shell prompt, ">>>". There you type:
from zipcodes import * # this assumes your program is zipcodes.py
dir() # shows you what's defined
print zipCode # shows you what's in zipCode
that ought to help debugging.
Strings don't have an append method like lists do. What I think you're trying to do is append the strings zipCode, city, and state to parsedList. This is the code you'd use to do that:
parsedList.append(zipCode)
parsedList.append(city)
parsedList.append(state)
Or, even more compactly:
parsedList = [zipCode, city, state]
Let me know if you get another error message and I can offer more suggestions.

Categories