How to fix IF/ELSE statments? - python

I'm trying to create an authorization process and it always says name unauthorized, despite the name not being assigned to the unauthorized variable.
I've tried different organization of the code, ie different order, but the problem hasn't improved.
Tessa=str
un = Tessa
n1=str
n2=str
input(n1("What is the name of player one?"))
if n1 == un:
print("Name unauthorised, try again")
else:
print ("Name authorised")
input(n2("What is the name of player two?"))
if n2 == un:
print("Name unauthorised, try again")
else:
print("Name authorised")
print("Welcome")
I expect any inputted name other than Tessa to result in the phrase "Name authorized" but instead it prints the unauthorized message."

I don't understand the statements n1 = str. Please check my code.
un = 'Tessa'
n1 = input("What is the name of player one?")
if n1 == un:
print("Name unauthorised, try again")
else:
print ("Name authorised")
n2 = input("What is the name of player two?")
if n2 == un:
print("Name unauthorised, try again")
else:
print("Name authorised")
print("Welcome")
and the result will be as below.
What is the name of player one? lam
Name authorised
What is the name of player two? rio
Name authorised
Welcome

you're clearly new to Python, so here are some things that you should fix:
Python doesn't need variables to have certain type. There is no need for what you were intending with n1 = str.
If you want to assign an actual string value, you can do so using quotes: "my string value".
If you want to do repeated checks, do it as part of a loop
If you want to store multiple values, use a list. (like for player names)
If you might have multiple values to check against (you might have multiple unauthorised names), use a list.
In light of these, consider the following code snippet:
unauthorised_names = ["Tessa"]
player_names = []
while len(player_names) < 2:
name = input("Please enter a name for player {}:".format(len(player_names) + 1))
if name in unauthorised_names:
print("Unauthorised name, please try again")
else:
player_names.append(name)
print(player_names)
Here unauthorised_names holds every name that cannot be entered. It can be one, it can be many.
player_names contain the names of the players.
You run it, until you got a sufficient number of valid player names, with the while loop
You take the input, with the number of the player as a parameter
Check it if it's on the list of invalid names, and store it, if it isn't.
Once you have the right number of names, you proceed with your program.
Try it for yourself!

To take an input and keep the value in n1, you need to do this:
n1 = str(input("What is the name of player one?"))
Also, I have no idea where you're going with the n1 = str, etc., so I suggest you scrap it.

Related

Simple length validation to a key in a dictionary in python?

I'm currently making a validation system to check the length of the key in my dictionary and remove any added value when it goes over a specific length but the thing is when I try to making it doesn't seem to work and . Here's what I've done
team1 = {"Team Ahab":["Martin","Kaz","Simba","Davis","Yas",],"Score":[]}
username = input("What is your name:")
if len(team1["Team Ahab"]) > 5:
team1["Team Ahab"].pop(username)
print("This team is full so please join another one instead")
else:
team1["Team Ahab"].append(username)
print(team1)
Here's my ideal output
username = "Paul"
This team is full so please join another one instead
Your validation logic validates the team after adding the wrong member and then corrects this error. Using this logic, you should always append the new member to the team before performing any validations:
team1["Team Ahab"].append(username)
if len(team1["Team Ahab"]) > 5:
team1["Team Ahab"].pop(username)
print("This team is full so please join another one instead")
else:
print(team1)
Alternatively, you could check if the team's size is exactly five before appending to it. Note that in this case yu should not pop the last member of the team:
if len(team1["Team Ahab"]) == 5:
print("This team is full so please join another one instead")
else:
team1["Team Ahab"].append(username)
print(team1)
I've modified code as below:
team1 = {"Team Ahab":["Martin","Kaz","Simba","Davis","Yas",],"Score":[]}
username = input("What is your name:")
if len(team1["Team Ahab"]) >= 5 :
if(username in team1["Team Ahab"]):
team1["Team Ahab"].remove(username)
print("This team is full so please join another one instead")
else:
team1["Team Ahab"].append(username)
print(team1)
Changes:
Condition needs to be len(team1["Team Ahab"]) >= 5 and (username in team1["Team Ahab"])
list.pop(index) expects a index, not str. Here, you can use remove function.

How to include 1st, 2nd, 3rd instead of writing it out

# extension
modify = input("Would you like to modify your recordings? Yes or No? ")
if modify == ("Yes","yes","Y","y"):
print ("OK")
if modify == ("No","no","n","N"):
print ("You may now exit the program")
print("")
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
if name == ("Jane, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Grant, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Lilly, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Henry, Over 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Jane, Over 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Naomi, Over 11"):
answer = input ("Would you like to add or delete data? ")
if answer == ("add" ,"Add"):
pos = input ("Type in the position(s) you would like to add: ")
elif answer == ("delete" ,"Delete", "del", "Del"):
delete = input ("Would you like to delete position or name?")
if delete == ("pos","Pos","Position","position"):
print ("Position deleted. Here is the final outcome: ",name)
elif delete == ("Name", "name"):
print ("Name deleted. There is no data now")
if pos == ('1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th','11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'):
print ("Posititon added. Here is their final score: ", name, " ", pos)
Hello. I am new to SO so I'm not sure if this is the correct way to do this however I am trying to answer a question where I am told to use pickle and store data inside a file. I am also told that the code should be able to let the user select a list to delete, be able to change a player position(its about a tennis competition) and be able to store the position of players in their last three tournaments. I need to do it in certain age categories
Everything works well so far however I need to do the positions as 1st 2nd 3rd and so on up to 1000. I have started writing it out(see penultimate line) but it would take extremely long to write it out so does anyone know a way to save time and solve this problem??
This is an odd little program, which will break if you don't enter answers with exactly what you're expected to enter.
I was able to get your error when I typed "No" (accidentally) after the prompt "Whose score would you like to modify?"
Since you haven't instantiated the variable answer before your if statements (as #Enes pointed out) and since none of your if statements are true, I didn't have anything stored in the answer variable, when you called
if answer == ("add" ,"Add"):...
this threw an error.
So if you fix the error that #Schlator mentioned
(Change
if modify == ("Yes","yes","Y","y"):
to
if modify in ("Yes","yes","Y","y"):
everywhere)
and if you instantiate your variable answer as Enes mentioned
(Add
answer = ""
before
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
)
then at least your fragile little program will exit gracefully.
It appears that you are mistaken with the syntax
It shouldn't be
if modify == ("Yes","yes","Y","y"):
rather it should be
if modify in ("Yes","yes","Y","y"):
Similarly for other if conditions that you have used in other parts of the program.
The way you've written your program, you will always drop through to if answer == with answer being undefined. Your input and test sequence:
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
if name == ("Jane, Under 11"):
cannot possibly match the choices you've given, because every input will contain a newline. You need to either include that in your test, or strip it from the input before checking.

is it possible to have an if/else statement with permutations

my program is simple, you enter your name, you select the desired amount of names youd like to enter and it prints out all the combinations... my only issue is not being able to add an if statement arount this couple lines of code so that the user wont be able to enter duplicate names or use any numbers in the name. i have tried a couple of things but i cant remember the exact code
names = []
for i in range(n):names.append(raw_input("Enter name "+str(i+1)+": "))
count = 0
def perm(a,k=0):
global count
if(k==len(a)):
print a
count += 1
else:
for i in xrange(k,len(a)):
a[k],a[i] = a[i],a[k]
perm(a, k+1)
a[k],a[i] = a[i],a[k]
my entire code can be found here if you'd like to paste it and run it, its kinda fun. in other words, if anyone could help me out just for the fact of where or how to achomplish this if/else statement, around the
(raw_input("Enter name "+str(i+1)+": "))
line of code. thank you all in advance
names = []
while len(names) < n:
name = raw_input("Enter name "+str(len(names)+1)+": ")
if validate_name(names, name):
names.append(name)
def validate_name(names, name):
return re.match("^[Sa-zA-Z]*$", name) and not name in names

Getting python 3+ comparison on return value and inputted value

Its been several months since I have worked with python. Im not getting an error, but im also not receiving the desired output too.
I have a function:
def set_account(gather_accounts):
print("gather_accounts():\n")
for a in gather_accounts:
print('Value: {}'.format(a[1]))
if decision_enter_account == 'Y':
bool_add_account = True
while bool_add_account == True:
prompt_account_url = input('What is the account\'s url?\n')
prompt_account_name = input('\nWhat is the account name? \n')
#TODO check for duplicate account names, and disallow
for a in gather_accounts:
if prompt_account_name == a[1]:
print('Sorry you already had an account with {} try again.\n'.format(prompt_account_name))
prompt_account_name = input('\nWhat is the account name? \n')
Im trying to implement a check for duplicates against the return value gather_accounts, specifically, in a for loop a[1] gets a value like Chase
However, when i run this script if I enter in Chase it doesnt hit: if prompt_account_name == a[1]
How can i fix this to compare the user inputted value of prompt_account_name and compare it to the value in a[1]?
Thanks
I'm guessing you are running in Python2, If in Python2, you need to use prompt_account_name = raw_input('\nWhat is the account name? \n') instead of prompt_account_name = input('\nWhat is the account name? \n') in this case.
Actually, in Python3, the input() is equivalent to raw_input() in Python2.
While the raw_input() is removed in Python3.

Dictionaries: How to get duplicate input by the user and count how many times it was entered?

names = []
print("Duplicate names won't be in the list!") # reminder
while True:
userInput = input("Enter a name: ")
if userInput == "": # condition to terminate loop
print("You've entered these names, duplicated names won't be included")
print(names)
break
elif userInput not in names: # condition to see if input is duplicated
names.append(userInput) # if satisfied, adds it to the list
else:
print("value exists!") # reminder about the value entered is duplicate
That's my code so far, I don't know how could I count how many times a specific duplicate value was entered, a Dictionary will solve it a lot of people say but I am not too familiar yet with it. In the output, When the input of names is complete, the console user should be able to search the list for
names by simply typing the name at the console. The program should output either “Not
found” or display the name and the number of times it was entered.
When the searching is complete, the console user should be able to delete names from the list
by typing the name. If a name is not found, the program should output “Not found”. If a name
is found then it should be removed from the list and the name is displayed along with a
“Deleted” message to the user e.g. “Deleted Ted”.
Thank you very much to people that would help!
You should use a Counter.
c = Counter() #Initialize the counter
print("Duplicate names won't be in the list!")
while True:
userInput = input("Enter a name: ") #input used to be raw_input in Python 2
if userInput == "":
print("You've entered these names, duplicated names won't be included")
print(c.keys())
break
elif userInput not in c:
c.update([userInput]) # if satisfied, adds it to the counter. You have to provide a list, hence the [ ]. If you provide a string, it will be broke down into characters.
else:
print("value exists!")
In order to show a specific count,
print c[word]
You can also see the most common terms, etc.
However your code forbids that a name be entered more than once, but if you want to count the number of times people enter your name, this is the way to go.
A dictionary consists of a key and a value, a key in a dictionary should always be unique, so unless you have a unique key with every value you use, it wouldn't support duplicate values and will not suit your purposes.

Categories