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)
Related
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()
for i in s:
if i.isupper() == True:
print('True')
break
else:
if i == s[l-1:]:
if i.isupper() == False:
print('False')
break
else:
continue
elif i.islower() == False:
continue
Input:- #$%#^&*kjnk svskjnbui h 4oi3hheuh /dfh uidshvhdsuihv suihc 0hrem89m4c02mw4xo;,wh fwhncoishmxlxfkjsahnxu83v 08 n8OHOIHIOMOICWHOFCMHEOFMCOEJMC0J09C 03J J3L;JMFC3JM3JC3'JIOO9MMJ099U N090N9 OOHOLNHNLLKNLKNKNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333000000000000000000000000000000000000000000000000000000000000000000000000000
Output:- True
I have to check that this input contains any uppercase value or not, my code run well for all other inputs but for this input it is showing "False" but the correct answer is "True".
Probably because your string has a single quote in it, pass ' as \' instead.
Also Try this one liner:
if any(x.upper for x in string):
print('True')
else:
print('False')
if name == 'main':
s = input()
import re
k = re.search('[a-zA-Z0-9]',s)
if(k is None):
print('False')
else:
print('True')
k = re.search('[a-zA-Z]',s)
if(k is None):
print('False')
else:
print('True')
k = re.search('[0-9]',s)
if(k is None):
print('False')
else:
print('True')
k = re.search('[a-z]',s)
if(k is None):
print('False')
else:
print('True')
k = re.search('[A-Z]',s)
if(k is None):
print('False')
else:
print('True')
Trying to exit the program by importing sys.exit(), break and ask == False, but nothing works. Full code here
#import sys
def body_cycle(*args):
if option == "/":
error_func_for_zero(first_number, second_number, option)
print(division_option(first_number, second_number))
print()
print(begin)
def error_func_for_zero(*args):
try:
first_number / 0 or second_number / 0
except ZeroDivisionError:
print("YOU CANNOT DIVIDE BY ZERO!")
print(begin)
def division_option(*args):
return first_number / second_number
begin = " "
while begin:
print("Hello, I am calculator. ")
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\nChoose your option (+, -, *, /): ")
print(body_cycle(first_number, second_number, option))
ask = " "
while ask:
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'? \nChoice: ")
if exit_or_continue == "Y" or "y":
print("OK")
elif exit_or_continue == "N" or "n":
#break
ask == False
else:
print("Break program. ")
break
You just want to replace ask == False by ask = False.
In addition, you could really use a simpler code structure. The whole thing before begin can be compacted down to:
def operation(a, b, option):
if option == "+":
return a + b
elif option == "-":
return a - b
elif option == "*":
return a * b
elif option == "/":
try:
return a / b
except ZeroDivsionError
return "YOU CANNOT DIVIDE BY ZERO!"
The rest can be put in a single loop instead of two, like so:
print("Hello, I am calculator. ")
while True:
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\n
Choose your option (+, -, *, /): ")
# Result.
print(operation(first_number, second_number, option))
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'.\n
Choice: ").lower()
if exit_or_continue == "y":
print("OK")
elif exit_or_continue == "n":
break
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()
This code does not run. It fails during the run(gate) function. The first error I get is from the .__name__ call. This isn't my main issue, so I'm not particularly worried about this error yet
The second error I get is in the last line of run(gate). The error message says gate is not callable.
I believe my actual issue is with the structure of my program. Am I misunderstanding (or misapplying) some object-oriented principles? I would appreciate it if somebody could provide an example or a correction to my code for a better way of structuring it. Thank you!
main.py
import builtins
import logic
print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
run(logic.andGate)
elif(int(logicGate) == 2):
run(logic.nandGate)
elif(int(logicGate) == 3):
run(logic.orGate)
elif(int(logicGate) == 4):
run(logic.norGate)
elif(logicGate.lower() == 'q'):
prog = 'n'
else:
print("Invalid input. Please try again")
def toBool(s):
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError
def run(gate):
print(gate.__name__ + " Gate function")
print("Enter value for 'a'")
valA = input()
print("Enter value for 'b'")
valB = input()
print("Result: " + str(gate(toBool(valA), toBool(valB))))
And logic.py
def andGate(a, b):
if(a and b):
return True
else:
return False
def nandGate(a,b):
if(a and b):
return False
else:
return True
def orGate(a, b):
if(a or b):
return True
else:
return False
def norGate(a, b):
if(a or b):
return False
else:
return True
move your defs under imports and just remove the else: raise.... etc ect part... itnot used correctly.
import builtins
import logic
def toBool(s):
if s == 'True':
return True
elif s == 'False':
return False
def run(gate):
print(gate.__name__ + " Gate function")
print("Enter value for 'a'")
valA = input()
print("Enter value for 'b'")
valB = input()
print("Result: " + str(gate(toBool(valA), toBool(valB))))
print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
run(logic.andGate)
elif(int(logicGate) == 2):
run(logic.nandGate)
elif(int(logicGate) == 3):
run(logic.orGate)
elif(int(logicGate) == 4):
run(logic.norGate)
elif(logicGate.lower() == 'q'):
prog = 'n'
else:
print("Invalid input. Please try again")