Adding items to a list until keypress - python

I have got it to work, except the list doesn't save the inputs properly; it just lists them as three periods. This is the code:
names = []
i=0
while 1:
i+=1
name=input("Please enter the name")
if name==" ":
break
names.append(names)
print(names)

Change names.append(names) to names.append(name), since you want to append name to the list names (just a typo I guess).
Also if name == " " must be changed to if name == "", since if the user presses enter without providing any name, the input is an empty string, not a white space.
Correct code here:
names = []
i = 0
while True:
i += 1
name = input("Please enter the name ")
if name == "":
break
names.append(name)
print(names)

Related

Listing names still the correct one is quess

I have no idea what I am doing wrong. Here is the question:
● Write a Python program called “John.py” that takes in a user’s input as a String.
● While the String is not “John”, add every String entered to a list until “John” is entered.
Then print out the list. This program basically stores all incorrectly entered Strings in a
list where “John” is the only correct String.
● Example program run (what should show up in the Python Console when you run it):
Enter your name :
Enter your name:
Enter your name:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This is what I have so far:
name_list = [" "]
valid_name = "John"
name = str(input("please enter a name: "))
if name != valid_name.upper():
#name = str(input("please enter a name: ")
name_list.append(name)
name_list += name
elif name == valid_name.upper():
name_list.append(name)
name_list += name
print("Incorrect names that you have added: ")`enter code here`
print(name_list[0:])
You almost got it! just need to use a while loop instead of a if/else:
name_list = []
valid_name = "John"
name = str(input("please enter a name: "))
while name != valid_name:
name_list.append(name)
name = str(input("Incorrect! please enter a name: "))
print(f"Correct! Incorrect names that you have added: {name_list}")

Adding in "else" makes my for loop not work

I am new to coding and have a list of lists that I need to search.
I want to see what lists contained in the larger list have the variable full_choice as the 3rd item in the sequence.
All lists that contain third_choice i need to print to a txt file.
the code below works and adds exactly what I need it to to the file, however I need the function to start again if there is no match for the variable full_choice.
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I have tried inserting an else: at the end of the code however while that has ends up creating the file it doesn't write anything to it.
Tried to fix your indentation. I'm guessing you wanted something like this:
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I just moved the else block forward to align with the if block you had a few lines before.
As #Haken Lid suspected, please fix indentation:
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').
replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()

How to make a proper name input program in python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How to validate person names? - Python/Django
(4 answers)
Closed 4 years ago.
I am at the part where I ask the user for their name. So far I got this:
# Import stuff
import time
# Create empty variable
Name = ""
# Ask their name
while Name = ""
Name = input("What is your name? ")
print("")
print(Name)
print("")
time.sleep(3)
So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.
How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?
I'm updating my answer to simplify the code and make it more readable.
The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.
from string import ascii_letters
def get_name():
name = input("What is your name?\n: ").strip().title()
while not all(letter in ascii_letters + " -" for letter in name):
name = input("Please enter a valid name.\n: ").strip().title()
return name
To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".
The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".
This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.
After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.
Old answer is as follows, it will still be useful.
This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.
Notice the use of str.isalpha().
def get_name():
name = input("What is your name?\n: ").strip().title()
while not (name.replace("-", "") and
name.replace("-", "").replace(" ", "").isalpha()):
name = input("Please enter a valid name.\n: ").strip().title()
return name
Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.
The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out #AGN Gazer.
Now you can just call the function later in your script, or store it for later.
name = get_name().title()
print("You said your name was " + name + ".)
The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".
Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().
You can try this :
while Name == "" or Name.isnumeric() == True:
Name = input("What is your name? ")
print("")
Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.
You can use a function like .isalpha() as this will return True if all the string contains all the alphabets:
while True:
Name = input("Please enter a valid name.\n: ")
if name.isalpha()
break
else:
print("Please enter a valid name.")
continue
print(Name)
Or You can try exception handling in python as (but this should be prevented):
try :
int(Name)
print("Please enter a valid name")
...
except:
print("Accepted")
...
This will check if the input is an integer print the error.
You can try:
This will check if variable Name containing numeric data or not.
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if not Name.isalpha():
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You also can try if name is like "harsha-biyani":
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if any(i.isdigit() for i in Name):
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You can use:
Name.isalpha()
"3".isalpha()
False
"anna".isalpha()
True

Why am I getting a AttributeError: 'str' object has no attribute 'remove' when attempting to remove an element using a variable or a string?

The purpose of this program is to create a list of names for people attending a party. I would like to be able to grant the user the ability to continue adding names until they chose YES as an option to exit the loop. However, I have am stomped when it comes to having them enter a name they would like to remove in case they added someone by accident or if they would like to edit the list and remove or replace someone.
I am currently a newbie to programming, hence the lack of classes to this code. Any help would be greatly appreciated. Thank you all in advance!
#Initialize empty list
partyList = []
#Initilize empty entry
inviteeName = ''
endEntry = ''
#Run loop until YES is entered as a value
while endEntry != "Yes":
inviteeName = input("Please enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
# Verifies if a name was not entered.
while inviteeName == "":
inviteeName = input("\nPlease enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
endEntry = input("\tPress ENTER to continue or type Yes to finish: ")
endEntry = endEntry.title()
#Append every new name to the list
partyList.append(inviteeName)
#Adds the word "and" to finish sentence if there are more than one invitees. NOTE: Make a class please!
numOfInvitees = len(partyList)
if numOfInvitees > 1:
partyList.insert(-1, 'and')
#Remove brackets and quotes.
partyList = ', '.join(partyList)
#Print message
print("\nThis will be your final message:\n" + str(partyList) + "\nYou are invited to my party!\n")
I was trying to use this to assist the user with removing names entered by accident.
submit = input('Submit?: '.title())
submit = submit.title()
if submit == 'Yes':
print('Invite has been sent!')
elif submit == 'No':
remNameConfirmation = input('Would you like to remove a name from the list?: ')
remNameConfirmation = remNameConfirmation.title()
if remNameConfirmation == 'Yes':
uninviteName = (input('Who would you like to remove?: '))
uninviteName = uninviteName.title()
Here is the line that is giving some trouble
partyList.remove(uninviteName)
print(partyList)
When your code reaches
partyList = ', '.join(partyList)
it will set the variable partyList to a string. Since it is no longer a list it does not have the .remove method.

I am trying to create an address book program that will append user input to its appropriate list

I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()

Categories

Resources