I'm new to Python and learning. I'm trying to write a program to:
User input full name (with space)
Check duplication to a list (I used split and join to compare strings)
If find a duplication, re-input new name
If not, simply break the loop and print "Thanks"
I only need to print "Duplicated" or "Thanks" 1 time, not multiple times with For loop.
My issue is when I cant re-call the input with my code (with duplicated input) or break the loop (after new name)
list=["M T", "Smith Jenkins", "P T", "C P"]
while True:
user=input("Your full name :")
usercheck="".join(user.split())
print(usercheck)
for i in list:
j="".join(i.split())
if usercheck ==j:
print("Duplicated ! Please enter new name")
else:
print("Thanks")
break
You need to think about that
if the current name in the iteratation is same :that's a dup
if the current name is different : you can't conclude there is not dup now, you need to test the others
So you can use the for/else construction, the else will be executed if no break has been seen in the loop, in your case if no duplicated has been found, there you'll be able to break the while loop
names = []
while True:
user = input("Your full name :")
usercheck = "".join(user.split())
print(usercheck)
for name in names:
j = "".join(name.split())
if usercheck == j:
print("Duplicated ! Please enter new name")
break
else:
print("Thanks")
break
If that is too tricky, you can keep with a variable that will help you know whether you've seen a duplicate or not
while True:
user = input("Your full name :")
usercheck = "".join(user.split())
duplicated = False
for name in names:
j = "".join(name.split())
if usercheck == j:
print("Duplicated ! Please enter new name")
duplicated = True
break
if duplicated:
print("Thanks")
break
Related
Made a list where I want the user to insert x followed by a number. once they have inputted, say x1, I would like x1 to be removed from the list as they are asked to input another number starting with x.
I want the list to be on loop as well, only stopping until one of the groups (of three number) has been chosen.
Disclaimer - I am a beginner at Python + Jupyter Notebook
allwins = (('x1','x2','x3'),
('x4','x5','x6'),
('x7','x8','x9'),
('x1','x4','x7'),
('x2','x5','x8'),
('x3','x6','x9'),
('x1','x5','x9'),
('x7','x5','x3'))
in_item = input("Please enter x followed by a number 1-9: ")
if in_item in allsolutions:
input("Good choice. Now pick another number starting with x: ")
else in_item not in allsolutions:
input("That did not work. Try again: ")
Idk how to keep loop for atleast a few times until the user inputs 3 diff numbers that makes a group.
You can't remove something from a tuple, so you need to make the inner tuples lists.
Then you need to loop over the main tuple, removing the input from each of them if it exists. After you do this you can check if the list is empty.
allwins = (
['x1','x2','x3'],
['x4','x5','x6'],
['x7','x8','x9'],
['x1','x4','x7'],
['x2','x5','x8'],
['x3','x6','x9'],
['x1','x5','x9'],
['x7','x5','x3'])
while True:
in_item = input("Please enter x followed by a number 1-9: ")
item_found = False
solution_found = False
for sublist in allwins:
if in_item in sublist:
sublist.remove(in_item)
item_found = True
if sublist == []:
solution_found = True
if solution_found:
print("You found all of them, congratulations!")
break
elif item_found:
print("Good choice, now pick another")
else:
print("That did not work, now try again")
Creating an access code program. I created a list and placed the file in it.
The output is: ['Cameron', 'Cameron', 'sudocode', 'Sudocode'...] ect. That part is fine.
I have tried using many different methods, mainly the 'in' operator to get boolean value of True. Never happens. I type in 'Cameron' and I get back false. Here is the code.
`
with open("kwaccess.txt") as file:
keyword1 = file.read().splitlines()
keyword_accesslist = [x.rstrip() for x in keyword1]
print(keyword_accesslist)
output is: ['Cameron', 'cameron', 'sudocode', 'Sudocode', 'Python or python']
for attempt in keyword_accesslist:
print(verify1)`
# Another attempt
if attempt in keyword_accesslist:
verify1 == True
else:
verify1 == False
If I type in Cameron, which is in the list for certain or any of the keywords, I get back False 5 times (for the 5 elements in the list, then it moves on to next part of code. Everything else works. Even the random number generator that I use the 'in' operator to compare with the user input and works perfect. It's the file into a list that has the compare jacked up. What am I missing...how do you compare a list element to the user string input with the 'in' operator.
I've gotten this error a few times during this long stretch of 'Denying' further coding day :)
TypeError: 'in ' requires string as left operand, not list...not currently, but along the way
Good luck Master coders.
HERE IS THE CODE:
def code_generator(string):
test = str(string) + str(randint(200,2000))
return test
def list_random_true():
codenumber = [number for number in range(200,2000)]
return codenumber
def access_code(attempt):
with open("kwaccess.txt") as file:
keyword1 = file.read().splitlines()
keyword_accesslist = [x.rstrip() for x in keyword1]
print(keyword_accesslist) # output is: ['Cameron', 'cameron', 'sudocode', 'Sudocode', 'Python or python']
##This is my PROBLEM AREA, can't rotate through the elements in list and compare against attempt
verify1 = False
for x in range(len(keyword_accesslist)):
verify1 = attempt == str(keyword_accesslist[x])
if verify1 == True:
x = 1
for x in range(3):
print("Verifying...")
time.sleep(3)
break
else:
x += 1
input("Access Denied. Please re-enter password. ")
if x == 3:
print("Your account has been locked. Please contact Admin Services.")
exit()
else:
pass
numbercheck = str(list_random_true()) # Each number in own element to check
for number in numbercheck:
verify2 = number in attempt
if verify2 == True: # Second Security Attemp
print("Access Granted")
break
else:
pass
BEGINNING OF PROGRAM
try:
compare = input("Please enter Secret Code. ")
except EOFError as e:
pass
attempt = code_generator(compare)
access_code(attempt)
Ok I checked out your code. With what you have, I do not understand what you are doing. verify1 = attempt == keyword_accesslist[x] will always return false as attempt is attempt is the user input but with some random digits appended to it, which is never the first element of keyword_accesslist. In addition, are you trying to check each word in keyword_accesslist and see if the attempt is equal or just the first element? Because you only iterate once every x, then if the check is wrong it will print "access denied" THEN check the next keyword_accesslist.
With some guesses, I think this is similiar to what you want:
verify1 = False
tries = 0
while tries < 3:
for password in keyword_accesslist:
verify1 = attempt == password
if verify1:
for x in range(3):
print("Verifying...")
time.sleep(3)
break
if not verify1:
tries += 1
attempt = input("Access Denied. Please re-enter password. ")
if tries == 3:
print("Your account has been locked. Please contact Admin Services.")
exit()
It's not the best, but I have changed the loop so that it probably does what you want it to do. It uses a nested loop to check for the password and the outer while loop to keep track of tries. I've attempted to use your logic, but I don't understand some of your other functions.
This feels like a debugging problem and not suited for stackoverflow, but I hope that you recieved the help you need.
I have the following 2D list
listItem = [["Apple", "TP123", "67", "77"], [
"Orange", "TP223", "55", "66"], ["Banana", "TP777", "98", "88"], ["Cherry", "TP123", "98", "88"]]
I want to compare the user input with the second element in each list in the listItem and print out the whole list if the value matches. If the value doesn't match, I will ask the user to enter the value again and again.
Here is my code:
def repeat():
tp = input("Please enter your tp: ")
for i in range(len(listItem)):
if tp == listItem[i][1]:
print(listItem[i])
break
else:
repeat()
I am facing some problems here. In the listItem, there are two "TP123". However, if the user enters "TP123", it only prints out one result instead of two. But if I didn't use the break, the code will keep asking users to enter another value even though the value they enter matches.
I am a python beginner, can anyone help me to solve this problem, thank you very much.
Use an extra variable and set it to True if their are matches, and use an if statement to trigger the repeat function again if it's False:
And also better without range:
def repeat():
tp = input("Please enter your tp: ")
match = False
for i in listItem:
if tp == i[1]:
print(i)
match = True
if not match:
repeat()
You are breaking before it can find the next item. Also no need to use range just loop through the list.
def repeat():
tp = input("Please enter your tp: ")
print(*(i for i in listItem if i[1] == tp), sep='\n')
Or in full for loop:
def repeat():
tp = input("Please enter your tp: ")
for i in listItem:
if tp == i[1]:
print(i)
I need to write a code in Python using the while loop to do the following:
Require the user to enter the names of all pupils in a class.
The user should be able to type “Stop” to indicate that the names of all the students have been entered.
Print out the total number of names the users entered after the loop has been exited.
Here is the is the code I thus far:
print ("""Enter the names of all the pupils in your class.
Type 'Stop' to indicate that all the names have been entered.""")
count_names = {}
while True:
pupil_names = input("Enter a name: ")
# I know there is code missing here, but I can not figure out what it must be
# I have 'count_names' as my counter variable
if pupil_names == "Stop":
print(f"There are {count_names} students")
break
I have searched everywhere for help but can't find anything.
Answers / Help that have come the closest:
count number of names in list in python
Counting the input in a while loop?
Try the following code
print ("""Enter the names of all the pupils in your class.
Type 'Stop' to indicate that all the names have been entered.""")
count_names = 0 # Initialize count_names to 0
while True:
pupil_names = input("Enter a name: ")
if pupil_names == "Stop":
print(f"There are {count_names} students")
break
count_names += 1 # Add 1 each time we count a pupil
By setting count_names to {} you make it a dictionary which does not suit your purpose. You would either want to save all names to a list ([]) or just keep the number of names as a number (start with 0).
names_list = [] # version 1
names_count = 0 # version 2
while True:
new_name = input("Enter a name: ")
if new_name == "Stop":
break
names_list.append(new_name) # version 1
names_count += 1 # version 2
print(f"There are {len(names_list)} students") # version 1
print(f"There are {names_count} students") # version 2
Also, I put the print statement outside of the while-block, as your task asked for it. It will run exactly the same.
change count_names to:
count_names = 0
and add the following line:
while True:
pupil_names = input("Enter a name: ")
count_names += 1
This should work
I've edited my code to the following:
while(True):
#get user to input a noun as a string variable
noun = input()
#get user to input a positive number for the integer variable
number = int(input())
#if the user inputs quit into the string variable stop program
if noun == 'quit':
break
#otherwise print the output
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
And I get the following error codes:
It looks like you edited the code since these answers, this should work
while(True):
noun, number = input().split()
number = int(number)
#if the user inputs quit into the string variable stop program
if noun == 'quit':
break
#otherwise print the output
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
Your problem was that you're calling input twice every loop. So, noun was set to 'apples 5' and number was set to 'shoes 2' which cannot be converted to an integer. You can split the input to get your noun and number.
You should be taking the input inside the loop, otherwise it is an endless loop or if you did write quit then it would just run once. Also there is no need for the == 0 condition to break from the loop according to the problem you have presented.
The problem is that you just take the first input, just get the inputs inside the loop insted.
Also the else should be idented with the if statement and you don't need the number == 0 condition, so the resulting code should be somehting like:
while(True):
#get user to input a noun as a string variable
noun = input()
#get user to input a positive number for the integer variable
number = int(input())
if noun == 'quit':
break
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
Here is how I would write. :)
while True:
noun = input("Enter a noun: ")
if noun == 'quit':
print("Quitting the program...")
break
while True:
number = input("Enter a number: ")
try:
if type(int(number)) == int:
break
except ValueError:
print("Invalid input. Please enter a number.")
if number == '0':
print("Quitting the program...")
break
print("Eating {} {} a day keeps the doctor away.".format(number, noun))