can't search in list using if in python3 - python-3.x

always search function return bad search string
I'm trying to find if the searching matches the movie_list and print if true or false
movie_list = []
def menu():
data = input(' please type A to add S to seach')
while data != 'q':
if data == 'a':
additz()
elif data == 's':
searchit()
else:
print('unkown command')
data = input(' please type A to add S to seach')
print(movie_list)
def additz():
name = input('please enter movie name')
year = input('please enter the movie realsed year')
movie_list.append(
{
'name':name,
'year':year
}
)
return movie_list
print(movie_list)
def searchit():
seaching = input('what are you seaching for boy ??')
if seaching in movie_list:
print('okay')`enter code here`
else:print('bad seach')
menu()

Pls check this code for searching()
def searchit():
seaching = input('what are you seaching for boy ??')
for i in movie_list:
#print(i)
if i['name']==seaching or i['year']==seaching:
print('okay')
menu()
else:print('bad search')
menu()

Related

How can I add the constraint to input statement in python

As you can see i am trying to check if the entered input by the user is string or not. If not, I have to display invalid name.
student_name = input("Enter the name of the student")
x = type(student_name)
if x!=str:
print('invalid name')
else:
print(student_name)
student_name = input("Enter the name of the student")
try:
int(student_name)
print('invalid name')
except ValueError:
print(student_name)
or
import re
student_name = input("Enter the name of the student")
num_format = re.compile(r'^\-?[1-9][0-9]*$')
for c in student_name:
it_is = re.match(num_format,c)
if it_is: it_is = True
if it_is:
print('invalid name')
else:
print(student_name)
the difference is on the first one you can pass through numbers with characters (more like username) but second one you should enter only characters.

Cycle "for" dosent start

class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self, question):
print(question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
for response in self.responses:
print("Survey results: ")
print('- ' + response)
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.show_question(question)
print("Enter 'q' at any yime yo quit. \n")
while True:
response = input("Languge: ")
if response == 'q':
break
my_survey.store_response(response)
print("\nThank's everyone ")
my_survey.show_results()
My response in terminal:
What language did you first learn to speak?
Enter 'q' at any yime yo quit.
Languge: Spanish
Languge: English
Languge: q
Thank's everyone
Survey results:
- q
''''''''''''''''In results displayed only value 'q', but i want to displayed values "Spanish", "English". Value 'q' just finish the programm''''''''''''
Fix the placement of your my_survey.store_response(response) it should be in the while loop.
Then, the print("Survey results: ") should be above the for loop
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self, question):
print(question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
print("Survey results: ")
for response in self.responses:
print('- ' + response)
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.show_question(question)
print("Enter 'q' at any yime yo quit. \n")
while True:
response = input("Languge: ")
if response == 'q':
break
my_survey.store_response(response)
print("\nThank's everyone ")
my_survey.show_results()

how to use functions inner variable in python

i'm doing a small script that received name from user and then search for name, if found prints his/her name otherwise print "not found".
def std_record():
print("1. Enter data.")
print("2. Search student")
user_input = int(input("Enter Choice: "))
if user_input == 1:
name = input("Whats your name: ")
elif user_input == 2:
search = input("Enter keyword: ")
if search in name:
print("data found: " + name +".")
else:
print("not found")
while True:
std_record()
UnboundLocalError: local variable 'name' referenced before assignment
you need to initialize strings before using them, either as an empty string or none
so name = ""
or name = None
Try initializing the name variable:
name = None
def std_record():
print("1. Enter data.")
print("2. Search student")
user_input = int(input("Enter Choice: "))
if user_input == 1:
name = input("Whats your name: ")
elif user_input == 2:
search = input("Enter keyword: ")
if name:
print("data found: " + name +".")
else:
print("not found")
while True:
std_record()

A permanent list change(Save python file)

I am a noob in python and i need help.I have made a phonebook where you can add the contacts.But the problem is that when i exit the program the changes to the list are not saved.I want the user to be able to make permanent changes to the list.I have seen posts about a file=open("something",'w') code to do this(I think) but i dont know where to insert this code and i dont really understand what it is.Could someone help me understand what this is about..Here is the full code:
name = ["ranga","hari"]
number = [9895497777,9]
book = {name[0]:number[0],name[1]:number[1]}
def search():
print("Contacts:")
for x in book:
print(x,':',book[x])
while 1:
count = 0
a = 0
ch1 = input("search: ")
try:
ch1 = int(ch1)
except ValueError:
while a < len(name):
result = name[a].find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count = count + 1
if count == 0:
print("Not available.Try again")
continue
else:
break
ch1 = str(ch1)
while a < len(number):
sumber = str(number[a])
result = sumber.find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count += 1
if count == 0:
print("Not available.try again")
continue
else:
break
def add():
print("What is the name of the contact you want to add?")
name1 = input()
name.append(name1)
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
number.append(number1)
book[name1] = number1
break
def remoe():
print("Reference:")
for x in book:
print(x,':',book[x])
while 1:
print("What is the name of the contact you want to remove?")
name2 = input()
if name2 in book:
increment = name.index(name2)
name.pop(increment)
number.pop(increment)
del book[name2]
break
else:
print("Not available.Please try again")
while 1:
print("Contacts:")
for x in book:
print(x, ':', book[x])
print("\nWhat do you want to do?\n1.Search for a person\n2.edit the phone book\n3.exit")
choice = input()
try:
choice = int(choice)
except ValueError:
print("Type 1,2 or 3")
continue
if choice == 1:
search()
elif choice == 2:
while 1:
print("Do you want to:\n1.Add a contact\n2.Remove a contact\n3.Go back to main menu")
ch2 = input()
if ch2 in['3']:
break
else:
try:
ch2 = int(ch2)
except ValueError:
print("Type 1 or 2..")
if ch2 == 1:
add()
elif ch2 == 2:
remoe()
elif choice == 3:
exit()
else:
print("Type 1,2 or 3")
I appreciate the help.
When you choose to add a contact, it does properly add the name and number to the list. But, that is it.
When you re-run the program, the list gets re-assigned due to the first 2 lines of your code:
name = ["ranga","hari"]
number = [9895497777,9]
So, you won't see the last changes.
This is where you should maintain a file which lives outside the scope of your code, rather than a list.
You can modify your add function like this:
def add():
print("What is the name of the contact you want to add?")
name1 = input()
#name.append(name1)
# Just add the name1 variable's value to the file
with open('contacts_list.txt', 'a+') as f:
f.write(name1 + '\n')
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
#number.append(number1)
# Similarly, append the number1 variable's value to file again.
with open('contacts_list.txt', 'w+') as f:
f.write(number1)
#book[name1] = number1
with open('contacts_list.txt', 'r') as f:
print(f.read())
break
Note: You would also need to change the other functions search and remove to read and write from the file. I've just given you a taste of how things are done. You need to modify your code and make it work.
Let me know if it helps.
I took your advice and made a new text file but i still did not know how to do it but after reading ur answers i understood and at last i came to this..
removelist = []
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
def add():
print("Type the name of the contact:")
name = input()
while 1:
print("Type the number of this contact:")
number = input()
try:
number = int(number)
except ValueError:
print("Please type a number")
continue
number = str(number)
with open('output.txt', 'a+') as f:
f.write('\n' + name +' ' + number)
break
def remoe(): #this is where the problem comes in
while 1:
remove = str(input("Remove: "))
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
if not remove in["Remove", "remove"]:
removelist.clear()
data = line.find(remove)
if not data == -1:
removelist.append(line) #This saves all the lines coming from the search to a
print(removelist) #removelist which can be accessed when you type in remove
line = f.readline() #But the problem is that if there is a \n at the end of the
else: #string then the remove function does not work
line = f.readline()
else:
print(removelist)
with open('output.txt', 'r') as f:
d = f.readlines()
f.close()
with open('output.txt', 'w') as f:
for i in d:
if i not in removelist:
f.write(i)
f.truncate()
f.close()
break
while 1:
with open('output.txt', 'r') as f:
data = f.read()
print("Contacts:")
print(data)
print('''What do you want to do?
1.Search for a contact
2.Edit contacts
3.Exit''')
f.close()
choice = input()
if choice in["1"]:
search()
elif choice in["2"]:
while 1:
print('''What do you wanna do:
1.Add a contact
2.Remove a contact
3.Exit to main menu''')
ch1 = input()
if ch1 in["1"]:
add()
elif ch1 in["2"]:
remoe()
elif ch1 in["3"]:
break
else:
print("Please type 1,2 or 3")
elif choice in[3]:
print("Ok bye")
else:
print("Please type 1,2 or 3")
Now the problem seems to be the remove function..if i try to remove a line with \n at the end of it then it wont work while the opp. seems to work.Any guess what i am doing here?
And thanks for the help Mayank porwal
At the first you should know name = ["ranga","hari"], number = [9895497777,9] that you have defined are in the code and you can not change those value, and after exit() they will reset to default value.
you should use of file (for example .txt file) in this issue:
1. you must create a .txt file in your project (for example Contacts.txt)
2. and write your information in there (for example in first line: Kourosh +98938....)
3. at the first step in your program you must read Contact.txt and load it in a structure like a list or dictionary (for example
>>> with open('workfile') as f:
... read_data = f.read()
>>> f.closed
)
4.now you can edit, add, remove structure.
5.and finally you can write structure in the file, before exit()
for example:
>>> with open('workfile') as f:
... f.write(s)
>>> f.closed

python while loops in a function

Can anyone please tell me why the "While loop" in the following code is not working as I am expecting to work? I want this code to ask for two inputs and then print.
def make_album(artist_name, album_title):
''' This function uses return option'''
album_details = artist_name + '' + album_title
return album_details
while True:
print("\n enter artist_name")
print("\n enter q to quit")
artist_name = input("artist_name: ")
if artist_name == 'q':
break
album_title = input("album_title: ")
if album_title == 'q':
break
album_details_Raj = make_album(artist_name, album_title)
print(album_details_Raj)
A python function works as
def add(x, y):
return x+y
The function uses whatever is passed into them.
You also have the function call itself. This is only useful if you are trying to have recursion, but it does not seem like you need it.
Try having the code look like this:
def make_album(artist_name, album_title):
''' This function uses return option'''
album_details = artist_name + '' + album_title
return album_details
while True:
print("\nenter artist_name")
print("\nenter q to quit")
artist_name = input("artist_name: ")
if artist_name == 'q':
break
album_title = input("album_title: ")
if album_title == 'q':
break
album_details_Raj = make_album(artist_name, album_title)
print(album_details_Raj)
Hope that helps.
You have a return statement before the while loop. Using return in a function will cause the function to not continue further.
I think you meant to not indent the loop. It does not need to be in the function. Otherwise, the return statement prevents the loop from starting
def make_album(artist_name, album_title):
''' This function uses return option'''
album_details = artist_name + ' ' + album_title
return album_details
while True:
print("\n enter artist name and album title")
print("\n enter q to quit")
artist_name = input("artist_name: ")
album_title = input("album_title: ")
if artist_name == 'q' or album_title == 'q':
break
album_details = make_album(artist_name, album_title)
print(album_details)

Resources