if statements in python not working - python

I recently started learning coding. On my first assignment I was asked to make a program that allows the user to choose names and then pick random ones. Here's what I came up with:
def main():
name = ["josh", "omar", "shatil", "cathrin"]
while True:
print (name)
continueProgram = input("would you like to continue")
if continueProgram.lower() =="yes":
print(changeList(name))
else:
break
def changeList(items):
changeList= input("Enter 'a' to append list, 'r' to remove an item from the list: ")
if changeList.lower() == "a":
appendList = input("what name would you like to add to the list?: ") items.append(appendList)
if changeList.lower() =="r":
removeList = input ("what name would you liket to remove from the list?: ")items.remove(removeList)
return items
main()
The last 2 if statements aren't working.

Your indenting looks suspicious.
Instead of this:
def changeList(items):
changeList= input("Enter 'a' to append list, 'r' to remove an item from the list: ")
if changeList.lower() == "a":
appendList = input("what name would you like to add to the list?: ") items.append(appendList)
if changeList.lower() =="r":
removeList = input ("what name would you liket to remove from the list?: ")items.remove(removeList)
return items
Try this:
def changeList(items):
changeList= input("Enter 'a' to append list, 'r' to remove an item from the list: ")
if changeList.lower() == "a":
appendList = input("what name would you like to add to the list?: ")
items.append(appendList)
if changeList.lower() =="r":
removeList = input ("what name would you liket to remove from the list?: ")
items.remove(removeList)
return items

Related

How do I stop my program from reading the second while loop when not needed?

I have some homework which I'm not sure how to finish.
The task given was to make a script which would ask the user to enter his name, after entering it, the script would check if the name entered matches with any of the names on a pre-existing list.
If the name matches the script would ask the user if they would like to delete the name off the list or keep it.
If the name doesn't match with any names on the list, it asks if the user if they'd like to add it on it.
The script should write the list of names in the end.
I wrote it like this:
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
while name in lk:
print("Your name is already in our list.")
if name in lk:
bris = input("Would you like to delete your name off our list?[Y/N]:")
if bris == "Y":
lk.remove(name)
print("Your name was removed.")
print(lk)
break
elif bris == "N":
print("OK!",name,"Your name will be saved.")
print(lk)
break
while name not in lk:
doda = input("Your name is not registered on our list, would you like to add it?[Y/N]:")
if doda == "Y":
lk.append(name)
print("Your name has been added.")
print(lk)
elif doda == "N":
print("Alright, goodbye",name,"!")
break
Issue is, that I have no idea how to stop it once the user chooses to delete their name off the list, it always reads the next while because the deleted name is no longer on the list.
Also, I am very sorry if this looks like poo poo I'm new to coding
If the user needs to be entered only once, why using loop?
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
if name in lk:
print("Your name is already in our list.")
bris = input("Would you like to delete your name off our list?[Y/N]:")
if bris == "Y":
lk.remove(name)
print("Your name was removed.")
print(lk)
elif bris == "N":
print("OK!",name,"Your name will be saved.")
print(lk)
else:
doda = input("Your name is not registered on our list, would you like to add it?[Y/N]:")
if doda == "Y":
lk.append(name)
print("Your name has been added.")
print(lk)
elif doda == "N":
print("Alright, goodbye",name,"!")
Your loop structure is the root of the issue. Since you're using while loops I'm assuming you want your script to loop and keep asking for new inputs. In this case you'll want one loop that you can break out of when you're done entering names based on some user input:
lk = ['Peti','John','Mary','Claire','Hellen']
while keep_looping = 'Y':
# check a name
name = input("Please enter a name: ")
if name in lk:
# name in list logic here
else:
# name not in list logic here
# ask user if the loop should continue. Entering 'N' will break the loop
keep_looping = input("Would you like to try another name? (Y/N): ")
You can reuse your existing logic for checking for names in the list and adding/removing, but you'll also want the name checking logic as an if/else block so only one condition can be met per loop. Otherwise you'll run into the same issue when a name exists and gets removed.
There are other optimizations you can do but I'll let you figure those out on your own.
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
if name in lk:
print("your name already present in list")
k= input(("would you like to delete your name from the list: [y/n]:"))
if k=="y":
lk.remove(name)
print("your name is deleted from the list")
print(lk)
else:
print("your name kept as it is in the list")
else:
print("your name is not present in list")
k= input(("would you like to add your name to the list: [y/n]:"))
if k=="y":
lk.append(name)
print("your name is added to the list")
print(lk)
else:
print("list is kept as it is")
print(lk)

How to store input to a list?

userinput = input("Enter your name: ")
names = []
My question is, how to store the input to the list?
I tried to add it like a integer, but it doesn't work.
since names is a list, you want to append the input to it.
userinput = input("Enter your name: ")
names = []
names.append(userinput)
print(names)
names.append(userinput) you this code and should work
If you want to put all answers to a list, you can use append() function.
userinput = input("Enter your name: ")
names = []
names.append(userinput)
int(userinput) makes it an int and [] makes it a seperate list so you can append it instead of adding it.
userinput = input("Enter your name: ")
names = []
names += [int(userinput)]
You could use the append method. Example:
names = []
while True:
name = input("Enter a name or <enter> if you are finished: ")
if name == '':
break
else:
names.append(name)
print(f'You entered {names}')
list1 =["Jack","Donald"]
newname = input("Enter new name: ")
list1.append(newname)

How to remove certain types of code from loop

Hi there can someone please help with something fairly simple. I have the following code to take in names until the name john or John is entered. Then it will print a string listing the incorrect names entered. The problem I am having is its asking the user to enter a name again after printing the string.
any help would be great.
my code is as follows:
user_input=""
c = []
while user_input != "John" or user_input != "john":
a = (input("Please enter your name:"))
b = c.append(a)
if a == "John" or a == "john":
print ("Incorrect names are:" + str(c[0:-1]))
Thank you
You never update user_input, and you have twice the same condition, you may ask until you have john, then print, also b is useless as append modify the current list :
user_input=""
wrong = []
while user_input != "John" and user_input != "john": # and use an 'and'
user_input = input("Please enter your name:")
wrong.append(user_input )
print ("Incorrect names are:", c[:-1])
Just break it!
user_input=""
c = []
while user_input != "John" or user_input != "john":
a = (input("Please enter your name:"))
b = c.append(a)
if a == "John" or a == "john":
print ("Incorrect names are:" + str(c[0:-1]))
break

How to update a dictionary with a user's input

I'm trying to take information from the user and then take that info to update a dictionary. It's a part of an exercise I'm doing. I've tried to use .format(var1, var2) with the way you update a dictionary, but when ends up happening is only one part of the dictionary gets updated.
name_grade = {}
while True:
name = raw_input("Please give me the name of the student [q to quit]:")
if name == 'q':
break
else:
grade = raw_input("Give me their grade: ")
name_grade['{}'] = '{}'.format(name, grade)
name_grades = {}
while True:
name = input("Please give me the name of the student [q to quit]:")
if name == 'q':
break
else:
grade = input("Give me their grade: ")
name_grades[name]=grade
print(name_grades)
Are you looking for this or something else?
You can update the dictionary by saying
name_grade[name] = grade

adding a new contact information in txt file

I have this long python code and I'm having trouble finishing or fixing it and I need help.
First I have these codes -
This will just display the menus and i have created several def functions. One is for creating data and saving to the txt file, and the other is to use a hash function to split the name. Contact info as data is created in the txt file. Finally, in a while loop I have to somehow call up the menu codes and this is where I get stuck, or I may need to fix the whole thing. Also when I put a phone number in like 555-5555, it makes an error. How would I input a number like this value?
def menu():
print("Contact List Menu:\n")
print("1. Add a Contact")
print("2. Display Contacts")
print("3. Exit\n")
menu()
choice = int(input("What would you like to do?: "))
def data():
foo = open("foo.txt", "a+")
name = input("enter name: ")
number = int(input("enter the number: "))
foo.write(name + " " + str(number))
foo.close()
def contact():
data = open("foo.txt")
file = {}
for person in data:
(Id, number) = person.split()
file[number] = Id
data.close()
while choice !=3:
if choice == 1:
print(data())
if choice ==2:
print(data())
menu()
choice = int(input("What would you like to do?: "))
It seems that the program never stops and I have to use option 3 from the menu to exit the program.
Phone number like 555-5555 is not valid integer number so keep it as a text.
Inside menu() you call menu() which call menu(), etc. It is recursion. When you choose 3 you leave last menu() and return to previous menu().
EDIT:
btw: you have to add "\n" in write
def menu():
print("Contact List Menu:\n")
print("1. Add a Contact")
print("2. Display Contacts")
print("3. Exit\n")
def data():
foo = open("foo.txt", "a+")
name = input("enter name: ")
number = int(input("enter the number: "))
foo.write(name + " " + str(number) + "\n") # new line
foo.close()
def contact():
data = open("foo.txt")
for person in data:
name, number = person.split()
print(name, number)
data.close()
#----------------
menu()
choice = int(input("What would you like to do?: "))
while choice !=3:
if choice == 1:
data()
if choice == 2:
contact()
menu()
choice = int(input("What would you like to do?: "))

Categories

Resources