how to use input() and match the elements with a database - python-3.x

database = {'User Name':['John frecks','Nadal alpha','Rick Ziani'],
'Code':['9264','8345','2675']}
for i in database:
name = input('Enter your name: ')
if name in database['User Name']:
print('Welcome', name,'Enter your code')
else:
print('You are not a client! Enter your name again!')
name = input('Enter your name: ')
break
code = input('Enter your code: ')
if code in database['Code']:
print('you are welcome')
break
else:
print('your code is wrong!')
break
The result I want,if all is right :
Enter your name: Nadal alpha
Enter your code: 8345
Your are welcome
The problem in my program is that whatever the code or the name are, I still get the same result.
For instance:
Enter your name: Nadal alpha
Enter your code: 2675 #this is Rick Ziani's code
You are welcome
Maybe, I didn't make the program the right way, if there is a way to optimize it, please tell me.
Thanks

The problem you have is that your database isn't mapping between things in a useful way. Your keys are just constant strings, and the values are lists. Maybe you could use indexing into the lists to find out which code corresponds to which name, but there is a much better way.
Make your database dictionary map from name to code directly, with no lists:
database = {'John frecks': '9264', 'Nadal alpha': '8345', 'Rick Ziani': '2675'}
Now you can check if a name is know with if name in database. And you can lookup the corresponding code with database[name].

the way that you have designed your dictionary is not the best practice to create a dictionary. but for the sake of the question, lets take things as they are.
The problem is that you haven't made any relationships between codes and usernames except for their orders which means nothing to python in itself
here is how to fix it in your code, i'll include comments for convenience:
for i in database:
user_index = 0 # you have to start a variable to be used in inner scopes
name = input('Enter your name: ')
if name in database['User Name']:
user_index = database['User Name'].index(name) # get the index of the entered name
print('Welcome', name,'Enter your code')
print(database['Code'][user_index])
else:
print('You are not a client! Enter your name again!')
name = input('Enter your name: ')
break
code = input('Enter your code: ')
if code in database['Code'] and code == database['Code'][user_index]:
# in the second part of the line above, you make sure that code and name have the same index
print('you are welcome')
break
else:
print('your code is wrong!')
break

Related

passing one function to another inside a for loop

New to programming. I wrote a program that Asks the user to enter the name, age and shoe size for four people and adds it to a dictionary. In fact, it works even when I don't use one function as an argument for another function. However, when i try to pass get_user_info() to store_user_info it doesnt work. I also tried to pass get_user_info to three separate variables and then passed these variables to store_user_info and it still didn't work. I am probably making a dumb error. Sorry its kind of a basic type of query but I just started learning programming. Any guidance is appreciated.
FOLLOWING CODE DOESN'T WORK: IT RUNS THE FOR LOOP BUT NEVER PROMPTS FOR THE INPUT FOR MORE THAN ONCE
#get user info
def get_user_info():
while True:
try:
user_input_name = (input("What is your name "))
user_input_age = int(input("How old are you "))
user_input_shoesize = float(input("What is your show size "))
break
except (ValueError,IndexError):
print('wrong selection or input')
return user_input_name,user_input_age,user_input_shoesize
#Store user info
def store_user_info(user_info):
user_information = {}
for i in range(3):
name, age, shoesize = user_info
user_information[name] = {"age" : age,"shoesize": shoesize}
print(user_information)
return user_information
=
store_user_info(get_user_info())
YET THE FOLLOWING WORKS and the loop works 3 times as expected:
#get user info
def get_user_info():
while True:
try:
user_input_name = (input("What is your name "))
user_input_age = int(input("How old are you "))
user_input_shoesize = float(input("What is your show size "))
break
except (ValueError,IndexError):
print('wrong selection or input')
return user_input_name,user_input_age,user_input_shoesize
#Store user info
def store_user_info():
user_information = {}
for i in range(3):
name, age, shoesize = get_user_info()
user_information[name] = {"age" : age,"shoesize": shoesize}
print(user_information)
return user_information
store_user_info()

My code isn't running after I break a while loop even though there is code after it

I tried making a rock-paper-scissors game, and to make sure that the user entered a number, I made a while loop. But after the user entered a number, the loop breaks but it won't keep running the game itself after it. How do I fix this?
main_choice = input('Please enter the number that matches your choice:\n')
#Make sure that user enters a number
while True:
try:
int(main_choice)
break
except:
main_choice = input('Please enter a NUMBER:\n')
continue
#Play
if main_choice == 1:
play_game()
I see others have placed the answer in the comments... but I'll place the full example in here. You need to convert your input into an integer to be able to compare it (or the 1 into a str).
The line that needs to change:
if main_choice == 1:
Change to:
if int(main_choice) == 1:
main_choice = input('Please enter the number that matches your choice:\n')
#Make sure that user enters a number
while True:
try:
int(main_choice)
break
except:
main_choice = input('Please enter a NUMBER:\n')
continue
#Play
if int(main_choice) == 1:
print("Game is now being played")
Gives the output:
Please enter the number that matches your choice:
1
Game is now being played

How to have a function return a variable that can be used in the rest of the program? Python 3

I'm trying to make a name generator function which will then return the parts of the name for use in the rest of my program. I put this inside of a function so that I could give the user the option to regenerate the name, instead of being stuck with the first one.
Putting the lists inside the function, and then being able to call the function again causes the random numbers to recalculate, so a new name is generated, but when I try to use "return" to move the variables outside of the function, I get an error.
There's probably a better way to do this, but I'm drawing a blank.
Here's what I have:
def naming():
titles = ["Sir", "Dr.", "Reverend", "Madam", "Master", 'Miss', 'Mrs.']
descriptors = ['sane', 'feelbe', 'cross-eyed', 'bow-legged', 'mad man', 'strange', 'frail', 'old', 'insane', 'cruel', 'bonkers', 'big-headed', 'knock-kneed', 'esquire', 'the huge']
name = input("What is your name?\n> ")
title = titles[random.randrange(0, 6)]
descriptor = descriptors[random.randrange(0,14)]
print(f"You shall be called {title} {name} the {descriptor}")
print("Does that work for you?")
choice = input("> ")
if choice == "yes":
return title, name, descriptor
if choice == "no":
print("Sorry, I'll try again.")
naming()
else:
print("Sorry I don't understand.")
naming()
I actually figured it out on my own. Here's what I did:
while True:
titles = ["Sir", "Dr.", "Reverend", "Madam", "Master", 'Miss', 'Mrs.']
descriptors = ['sane', 'feelbe', 'cross-eyed', 'bow-legged', 'mad man', 'strange', 'frail', 'old', 'insane', 'cruel', 'bonkers', 'big-headed', 'knock-kneed', 'scissor-handed', 'huge']
name = input("What is your name?\n> ")
title = titles[random.randrange(0, 6)]
descriptor = descriptors[random.randrange(0,14)]
print(f"You shall be called {title} {name} the {descriptor}")
print("Does that work for you?")
choice = input("> ")
if choice == "yes":
break
if choice == "no":
print("Sorry, I'll try again.")
else:
print("Sorry I don't understand.")
The code works fine, have you tried to atribute the return values to variables?
IE:
title, name, descriptor = naming()

How to get Python 3 to register a random word from a external file as a variable

I'm a computer science student at secondary school currently struggling with a certain aspect of my NEA, we are permitted to get help with the code. The aim of the NEA is to create a game which can choose a random song and artist from an external file and then get the user to guess which song it is. The issue I have run into is when I run the program the random aspect of the code (The Song name and artist chosen from the external file) does not seem to be registered by the if statement. I cannot think of a better way to explain my issue, but if you run the code I believe you will see the issue I'm having. I have taken out most of the excess code that is not part of the problem to make it easier to understand because like I said before I am still a novice at this. I have looked around for a while now and cannot seem to find an answer. Any sort of help would be very much appreciated.
username = 'Player1'
password = 'Password'
userInput = input("What is your username? (Case Sensitive)\n")
if userInput == username:
userInput = input("What Is Your Password? (Case Sensitive)\n")
if userInput == password:
print(
"Welcome! In this game you need to guess each songs name after being given its first letter and its artist. Good luck!"
)
else:
print("That is the wrong password. Goodbye ;)")
exit()
else:
print("That is the wrong username. Goodbye ;)")
exit()
startgame = 'Start' 'start'
userInput1 = input("Click Any Button And Click Enter To Begin Game:")
if userInput1 == startgame: 'Start'
print("Welcome To The Game")
import random
Song = [line.strip() for line in open("Songnames.txt")] #Currently in the external file I have removed all of the other songs apart from H______ By Ed Sherran.
print(random.choice(Song))
userguess = input("Whats Your Answer?\n")
if userguess == ("Happier") and (random.choice(Song)) == "H______ By Ed Sherran": #The program will continue to return 'Incorrect'.
print("Nice One")
else:
print ("Incorrect")
Any sort of help would be very much appreciated , I have looked for a while on this site and others for an answer however if it seems I have missed an obvious answer I do apologise.
When I run the code it seems to work. (My Songnames.txt contains one line, H______ By Ed Sherran.)
Is it possible that your Songnames.txt contains at least one empty line? If so, filtering the empty lines might fix the problem:
Song = [line.strip() for line in open("Songnames.txt") if line.strip()]
A few other suggestions for your code:
startgame = 'Start' 'start'
userInput1 = input("Click Any Button And Click Enter To Begin Game:")
if userInput1 == startgame: 'Start'
print("Welcome To The Game")
This doesn't make sense. Besides the misleading prompt about buttons and clicks, the if userInput1 == startgame: 'Start' doesn't do anything, not even print start. And the game starts regardless of what the user enters.
The actual game has a few issues as well, most importantly for when you actually have multiple songs is the fact that you choose a random song twice. Given enough songs, these will almost always be two different songs, so the print will be utterly misleading. Better choose one song and assign it to a variable:
import random
songs = [line.strip() for line in open("Songnames.txt") if line.strip()]
computer_choice = random.choice(songs)
print(computer_choice)
userguess = input("Whats Your Answer?\n")
if userguess.lower() == computer_choice.lower():
print("Nice One")
else:
print("Incorrect")
I took the liberty to make the comparison case insensitive by comparing the lowercase versions of the user guess and the computer's choice.

How to edit strings in a list

What I want is this - I have a list of names created from user input. now i have to come up with a way for the user to edit a name by entering the name that they what to edit and then obviously edit it into what they want and store it in the list.
if it helps heres everything I have so far. def edit() is where im struggling.
def mainMenu():
print("\nMAIN MENU")
print("1. Display Members:")
print("2. Add A Member(s):")
print("3. Remove A Member:")
print("4. Edit Member:")
print("5. Exit:")
selection = int(input("\nEnter Choice: "))
if selection == 1:
display()
elif selection == 2:
add()
elif selection == 3:
remove()
elif selection == 4:
edit()
elif selection == 5:
exit()
else:
print("Invalid choice, enter 1-5.")
mainMenu()
def display():
#displaying roster...
print(roster)
mainMenu()
def add():
#adding team members...
size = int(input("How many players are you adding?"))
global roster
roster = [0] * size
for i in range(size):
roster[i] = input("Enter members name: ")
roster.append(roster)
mainMenu()
def remove():
#removing a team member...
roster.remove(input("Enter member to be removed: "))
mainMenu()
def edit():
#edit a team member...
roster.insert(input("Enter Name to be edited: "))
mainMenu()
mainMenu()
Removing and adding elements are pretty easy in python because they are directly supported by the language. Each of them can be translated into only one instruction.
When something doesn't seem very obvious, such as the editing functionality you are trying to implement, try breaking it down to things that can be expressed as a simple operation that holds one one line (even if not in order).
To find the answer I thought this: somewhere in my code, I want to type roster[ind_name_to_edit] = new_name.
I knew then that before typing this, I would want to find the value of ind_name_to_edit. This can be done by roster.index(name_to_edit). And you already know how to get the name to be edited and the name to edit ;)
If you're still unsure how to do what you want to do, re-read this answer and see the documentation of the index method of list in python3 and maybe some examples here.
N.B: If your list is supposed to be sorted in some way, you should implement your own search algorithm instead of using index, and you should consider re-sorting the list after the edit. I know it's a long shot but just in case.

Resources