Cycle "for" dosent start - python-3.x

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()

Related

can't search in list using if in python3

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()

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)

How to make an input an answer to 3 different randoms

I am trying to make a simple quiz program. But how do I get the input to be the same as the answer on the code where the user answers the question?
import random
print("what is your name \n")
name=input()
print("hello",name,"you will be asked 10 math questions goodluck")
for i in range(10):
op=["+","-","*"]
num1=random.randint(0,10)
num2=random.randint(0,12)
operation=random.choice(op)
eval(str(num1)+operation+str(num2))
print(num1,operation,num2)
while True:
try:
user= int(input())
if user=answer:
print("correct")
except:
print("invaild")
Avoid using eval, fix indendtation, address comments and you will get something like this.
import random
import operator
operators = {'+': operator.add,
'-': operator.sub,
'*': operator.mul}
print("What is your name?")
name = input()
print("Hello {name} you will be asked 10 math questions, good luck.".format(name=name))
for _ in range(10):
num1 = random.randint(0, 10)
num2 = random.randint(0, 12)
operator = random.choice(operators.keys())
answer = operators[operator](num1, num2)
print("{n1} {op} {n2} = ?".format(n1=num1, op=operator, n2=num2))
try:
user_input = int(input())
if user_input == answer:
print("Correct")
else:
print("Invaild")
except ValueError:
print('Please enter a number!')

Return to main function in python

Working on Python 3.4.3
Let's say I have created three fuctions:
def choosing(mylist=[]):
print("We will have to make a list of choices")
appending(mylist)
done = False
while(done == "False"):
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(mylist)))
done = True
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
appending(mylist)
done = False
elif(action == "Delete"):
removing(mylist)
done = False
def appending(mylist1 = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
mylist1.append(c)
print("You have inserted {} choices".format(len(mylist1)))
print("Please verify them below: ")
for x in range(0, len(mylist1)):
print(mylist1[x])
def removing(mylist2 = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
mylist2.remove(r)
print("{} successfully removed!".format(r))
Now problem is I can't just call choices() in append or remove function as choices() function will call append again and again infinitely.
So how do I get back in choices after appending or removing data in list?
As suggested by tobias_k, you should add the contents of choices() into a while loop.
I also found
some other problems:
False does not equal "False", so your while loop never runs.
You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and removing_list, so it's clearer.
You also shouldn't use False to define a while loop - instead, make a variable, then set it to True. When you have to stop, set it to False.
Here is the code with those problems fixed:
def appending(appending_list = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
appending_list.append(c)
print("You have inserted {} choices".format(len(appending_list)))
print("Please verify them below: ")
for x in range(0, len(appending_list)):
print(appending_list[x])
return appending_list
def removing(removing_list = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
removing_list.remove(r)
print("{} successfully removed!".format(r))
return removing_list
print("We will have to make a list of choices")
choosing_list = appending()
list_incomplete = True
while list_incomplete:
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(choosing_list)))
list_incomplete = False
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
choosing_list = appending(choosing_list)
elif(action == "Delete"):
choosing_list = removing(choosing_list)
Let me know if there's any problems with this code.

Ignoring quotes while sorting lists in Python?

I am making a program to read from a file, alphabetize the info, and paste it into an output.. The only issue I am having is in the information that begins with quotes ("").
The main function for the program is to auto-sort MLA works cited pages (for fun obviously).
Here is the code... I would love any criticism, suggestions, opinions (Please keep in mind this is my first functioning program)
TL;DR -- How to ignore " 's and still alphabetize the data based on the next characters..
Code:
import os, sys
#List for text
mainlist = []
manlist = []
#Definitions
def fileread():
with open("input.txt", "r+") as f:
for newline in f:
str = newline.replace('\n', '')
#print(str)
manlist.append(str)
mansort(manlist)
#print("Debug")
#print(manlist)
def main():
print("Input Data(Type 'Done' When Complete or Type 'Manual' For file-read):")
x = input()
if x.lower() == 'done':
sort(mainlist)
elif x == '':
print("You must type something!")
main()
elif x.lower() == 'manual':
fileread()
else:
mainlist.append(x)
main()
def mansort(manlist):
print("What would you like to name the file?(Exit to Terminate):")
filename = input()
manlist = sorted(manlist, key=str.lower)
for s in manlist:
finalstring2 = '\n'.join(str(manlist) for manlist in manlist)
if filename == '':
print("You must choose a name!")
elif filename.lower() == 'exit':
sys.exit()
else:
with open(filename + ".txt", "w+") as f:
f.write(str(finalstring2))
def sort(mainlist):
os.system("cls")
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?(Exit to Terminate):")
filename = input()
if filename.lower() == 'exit':
sys.exit()
elif filename == '':
print("You must type something!")
sort(mainlist)
else:
with open(filename + ".txt", "w+") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
Please keep all criticism constructive... Also, just as an example, I want "beta" to come after alpha, but with my current program, it will come first due to "" 's
sorted(mainlist, key=str.lower)
You've already figured out that you can perform some transformation on each item on mainlist, and sort by that "mapped" value. This technique is sometimes known as a Schwartzian Transform.
Just go one step further - remove the quotes and convert it to lower case.
sorted(mainlist, key=lambda s: s.strip('"').lower())

Resources