Python (py.exe) closes when 'flag' becomes False - python

When responding with 'Y' to the repeat input, the code requests another name and another mountain, as expected. If responding with 'N' to the 'repeat' input, Python closes, instead of printing what's next. Have I made a mistake somewhere?
responses = {}
polling_active = True
while polling_active:
name = input('\nPlease state your name: ')
mount = input('What mountain would you like to climb? ')
responses[name] = mount
repeat = input('Would anyone else like to attend? (Y/N) ')
if repeat == 'n':
polling_active = False
print('\nPoll is now closed. Results are:')
for name, mount in responses.items():
print(f"{name.title()} would like to climb {mount.title()}!")

Your code seems to be working well - at least for me.
One thing - you ask for input in Capital 'Y/N', and your question also mentioned using 'N' - while the code checks for small letters ('n').
You may want to do:
if repeat.lower() == 'n':
But I'm really not sure that's the issue for you.

Related

Input/If statement - correct way of writing

I am currently taking part of a beginner Python code challenge and whilst my code runs how it should, the solution is written differently to my program.
As I am just starting out, I was wondering which way is more preferable to write the program,
The solution is:
# Prompt user if they want to proceed. Y/N?
should_proceed = input("Do you want to proceed? Y/N ")
# If they want to proceed
if should_proceed.lower() == "y":
# print out to the screen "SOLD!" to confirm purchase
# TODO: Gatjer credit card information and process it.
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining -= num_tickets
# Otherwise...
else:
# Thank them by name
print("Thank you anyways, {}!".format(name))
Whereas, I have put:
# Prompt user if they want to proceed. Y/N?
proceed = input("Would you like to proceed? Y/N ").upper()
# If they want to proceed
if proceed == "Y":
# print out to the screen "SOLD!" to confirm purchase
# TODO: Gatjer credit card information and process it.
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining = tickets_remaining - ticket_request
print(tickets_remaining)
# Otherwise...
elif proceed == "N":
# Thank them by name
print("Thank you for your time, {}".format(customer_name))
Was it incorrect to call upper() on the input?
Is there any other errors I have done?
Many thanks,
Was it incorrect to call upper() on the input?
No, this is a perfectly fine way to allow case-insensitive input. Their solution shows an alternative that works just as well.
Both ways are fine with one caveat. Because you are specifically checking for both Y and N, your way is probably better in that case since you would otherwise have to call upper() twice:
proceed = input("Would you like to proceed? Y/N ")
if proceed.upper() == "Y":
doSomething()
elif proceed.upper() == "N":
doSomethingElse()
On that enhanced checking, your code is slightly different in that it does nothing if the input is neither Y nor N (the other code treats anything that's not y as n). In that case, you're probably wise to ensure it is one of those values, with something like:
proceed = ""
while proceed != "Y" and proceed != "N":
proceed = input("Would you like to proceed (Y/N)? ").upper()

How do I make the for loop work only if one or more items != 'yes'

I'm working on a HW assignment where I create a fake club with entry questions. If any of the questions are answered with "no", then the person isn't allowed to join.
I've tried going back to the og lessons about lists and loops, but I can't find what I'm trying to do on there.
Here's my code so far.
# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.
def main():
display = input('Hi! This is your application to The Aqua Project...')
display2 = input('Read the following questions and just type y or n')
# Weird list format...
user = [input('Are you at least 18 yrs old? '),
input('Can you work with other people? '),
input('Do you like animals? '),
input('Are you okay with getting dirty sometimes? ')]
# Here's the problem, I want to print 'sorry you cant join' once...
for i in range(4):
if user[i] != 'y':
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
i += 1
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
main()
When you put a 'n' for some questions it says you can join, but for others it says you can't join. I don't know why sometimes it says you can when you placed a no in the interview, it shouldn't.
The usual ways to do this are a for loop with a break and an else clause:
for answer in user:
if answer != 'y':
print('Sorry')
break
else:
print('Congratulations')
Or the any() function:
if any(answer != 'y' for answer in user):
print('Sorry')
else:
print('Congratulations')
If one "no" means decline, you can add break to exit the loop after print decline info. Just like:
for i in range(4):
if user[i] != 'y':
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
# i += 1 # <<<<<<<<<<<<<<<<<< this code may be not needed here
break # <<<<<<<<<<<<<<<<<< where to add break
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
or you can use a variable to indicate whether to decline, just like:
toDecline = False
for i in range(4):
if user[i] != 'y':
toDecline = True
if toDecline:
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
There are a few ways to do this:
Use a flag variable and just output at the end. (Slightly inefficient if the first response is a no)
Use a flag variable and a while loop to exit as soon as the user responds with no. (Can be slightly confusing)
Use the builtin any method. (Can be confusing, not recommended)
flag = True
for i in range(4):
if user[i] != 'y':
flag = False # User has answered no to something, set the flag to false
if flag: # User has answered yes to everything
# <do your `yes` output>
else: # User has answered no to something
# <do your `no` output>
there are some small points in your code that need to be changed:
# Purpose: Create a fake club that has certain requirements, ask user to
# fill out the application, and print out their answers + results.
def main():
display = input('Hi! This is your application to The Aqua Project...')
display2 = input('Read the following questions and just type y or n')
# Weird list format...
user = [input('Are you at least 18 yrs old? '),
input('Can you work with other people? '),
input('Do you like animals? '),
input('Are you okay with getting dirty sometimes? ')]
# you define a variable inside function main
# and assign a list to it
# this variable will not be visible outside
# you should just return it
return user
# Here's the problem, I want to print 'sorry you cant join' once...
# call your function before you test the answer
# and assign the the result of the function to a
# variable you can use in your check
user= main()
# define a flag variabe to
# see if the answers are ok according your check
ok= True
for i in range(4):
if user[i].lower()[:1] != 'y':
# you could also use your original code
# in the check. The code above is an example
# how you could make sure the user can enter
# upper/lower case letters and also "yes"
# and "y" [:1] cuts off 1 character
# if the string is non-empty, otherwise it
# returns an empty string
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
i += 1
# memorize that some question wasn't ok
ok= False
# I guess here you might want to exit the loop?
# so use a break, otherwise the other answers
# would be checked as well and the message
# output several times per user in some cases
break
if ok:
# this code here doesn't belong in the loop body
# I guess. It should be executed after all questions
# have been checked positive (which is only known
# after the loop has been executed)
# So here we are sure the answers were yes, because
# otherwise we would have set ok to False
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at TheAquaProject.com')
justToShowInCMD = input('')
# if you call your function here, you can't check
# the result of the input() calls because
# by the time you check it it has not been entered
I would suggest storing your questions in a list and using a for loop to ask them. Store the user's response to another list and check if there is any "n" in this list. See code below:
questions = ["Are you at least 18 yrs old?", "Can you work with other people?", "Do you like animals?", "Are you okay with getting dirty sometimes?"]
answers = list()
for question in questions:
user_answer = input(f"[y/n] {question}: ").lower()
answers.append(user_answer)
if "n" in answers:
print("Sorry, you can't join our club.")
else:
print("Congrats! You are in!!")
# you can print your desired messages as well.
Assuming you are iterating 4 times (using range(4))based on the length of user, what you can simple do is the following:
if 'n' or 'no' in user:
print('Sorry, but you can\'t join our club')
justToShowInCMD = input('')
else:
print('')
print('Congratulations, you have met all of our requirements!')
print('We will send an email soon to discuss when our team')
print('will meet up to help save some animals!')
print('In the meantime, visit our website at
TheAquaProject.com')
justToShowInCMD = input('')
You can modify the if condition to cater to other forms of negative answers like 'N' or 'No'. You don't need to iterate over user.
Comments on OP main():
A key point of programming, is code use efficiency.
Don't repeatedly call functions (e.g. input and print) when not necessary.
There are several ways your problem can be solved.
The other answers focus on your original user list, complete with repeatedly calling input
Once user executes, it essentially becomes a list of y and or n values, which you then unpack with a loop to check the values.
Another problem with the user list method, is it requires all of the questions to be answered, prior to disqualification. What if there were 40 questions? I'd be annoyed.
Incidentally, a list can be unpacked as follows: for value in user:. There is no need to address the list by index with python.
Updated main() implementation:
def print_list(values: list):
"""Print the values of a list"""
for value in values:
print(value)
def main():
"""Iterate through a questionnaire"""
# Variables at the top
intro = ['Hi! This is your application to The Aqua Project...',
'Read the following questions and just type y or n']
questions = ['Are you at least 18 yrs old? ',
'Can you work with other people? ',
'Do you like animals? ',
'Are you okay with getting dirty sometimes? ']
final = ['\nCongratulations, you have met all of our requirements!',
'We will send an email soon to discuss when our team',
'will meet up to help save some animals!',
'In the meantime, visit our website at www.TheAquaProject.com']
print_list(intro)
for i, question in enumerate(questions, start=1):
response = input(question)
if response == 'n': # can be replaced with != 'y'
print("Sorry, you can't join the club!")
break
if i == len(questions):
print_list(final)
Comments on updated main():
Instead of calling print a lot, store the text in a list and then call the print_list function to do the printing.
Keep custom functions separate
Custom functions should perform one function
values: list this is a type hint, which tells what data type the values parameter of print_list should be.
Annotations
"""""": use docstrings
Documenting Python Code: A Complete Guide
Double space between functions: How to Write Beautiful Python Code With PEP 8
main(): Defining Main Functions in Python
questions is obvious, it's just the questions from user, as a list without calling input
unpack questions with a for-loop and use the built-in function: enumerate.
There are many Built-in Functions
i goes with enumerate to count.
Other languages create a dummy variable, like count = 0, then use count+=1 to track loop iteration; this is considered not pythonic. Python uses enumerate, but only if you need a count for implementing something else.
if condition checks if response is n
If the if condition evaluates as True (e.g. when response = n, n == n is True), the user gets the sorry message, break, ends the loop, and the questionnaire is complete.
There are no nicities here, the function does not check to make certain a user enters y, it only checks for n. That wasn't in the scope of the question.
The start parameter of enumerate is set to 1. If all the questions are answered, i=4 and len(questions)=4 so i == len(questions) evaluates as True and the user gets the congratulations message.
len(questions) is used instead of 4, because it's a bad idea to hardcode in values like that, because then you have to remember you've done so. What if the number of questions changes? Then your if condition is broken.
Resources:
I'm not affiliated with RealPython, but they are a great source of incredibly in depth tutorials.
Lists and Tuples in Python
Basic Data Types in Python

If statement with input check with incorrect outputs

Backstory: I have been trying to actually learn python instead of just snipping from others. I have created a simple script that uses webbrowser. It may be a dirty script and I would love input like "you should do this", "this can be simplified". The thing i cant figure out is using if statement to handle incorrect input, prompt, then recheck the if statement. I tried searching but nothing assisted in this.
import webbrowser
a = input ('Do you want to search?(y or n)')
if a == ('y' or 'yes' or 'Y' or 'Yes' or 'YES'):
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
else:
x = input('Where do you want to go?: ')
new = 2 # open in a new tab, if possible
# open a public URL, in this case, the webbrowser docs
url = x
webbrowser.open(url)
The question is: How do i ether do a recurring that will handle incorrect answers. If they use something other then the listed yes, it will print please use ('y' or 'yes' or 'Y' or 'Yes' or 'YES'), then prompt again and allow for input. I know i will have to change it to a nested if statement to allow the same with no to move to next. Also as is, when i use the code and enter 'y' it will open with my default (firefox), but if i enter anything else, it only opens in IE without the google search but "searching" like http://fun/ instead of https://www.google.com//search?q=fun as it should.
What did leave out? Also if you could post information on in-depth the meaning behind the code to help further learning. Thank you all!
The following code should work:
import webbrowser
a = 'y'
while a != 'n':
a = input ('Do you want to search?(y or n)')
a = a[0].lower()
if a in "y":
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
elif a not in "n":
print "Please only enter 'y' or 'n'."
The while loop tells python to loop as long as the answer is not "n".
The a = a[0] tells python to only use the first letter of the response. This is to make the comparison easier later on.
The .lower() code tells python to convert the result to lowercase. Again, this is to make the comparison easier later on.
Now our answer will always be lowercase, and the first letter entered. So y ,yes, Yes, YES and n, no, No, NO will be converted to y or n. Of course, any other text will be treated the same way (lowercase and first character), but we only care about y and n.
The rest should be pretty straightforward. Since we have limited the possibilities of what the answer can be, we can do a simple comparison.
Below are modifications to check for only yes and no:
import webbrowser
a = 'y'
while a != 'n':
a = input ('Do you want to search?(y or n)')
a = a.lower()
if a in ("y", "yes"):
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
elif a in "no"
a = "n"
elif a not in ("n", "no"):
print "Please only enter 'y' or 'n'."
There's a different way to check if the value is one of the given values. You should make your if condition be like this:
if a in ('y', 'yes', 'Y', 'Yes', 'YES'):
It is fast and understandable.
Here's a reason why your condition does not work.
Let's say we entered 'no'. Let's see what happens in your if statement:
1. First, the ('y' or 'yes' or 'Y' or 'Yes' or 'YES') is evaluated. Since a non-empty string in Python converts to True, this part evaluates entirely to True
2. Then, the comparison takes place. It looks like this:
if a == True:
With a being a string 'no'. That's obviously not what you want. Use the method a described above and everything will be fine
To constantly re-ask until a correct input is received, try an endless loop with a break statement:
while True:
a = input()
if a in ...:
# process input
break
else:
print("please use 'y' or 'yes' or 'Y' or 'Yes' or 'YES'")

How to do write onto this script validation for the end "if they want to exit this program"

problem = False
while problem == False:
foo = open("solutions.txt","r")
print("What is wrong with your device?")
issue=input()
if (('wet' in issue) and ('water' in issue)):
solutions = foo.readlines()
print(solutions[0]+solutions[1])
problem = True
# (and so on).
Need it to say at the end, "would you like to exit" and have an option of yes or no then say are you sure after input and if anything other then yes or no to say invalid input and ask the question again.
The next lines WITHIN your loop would be:
answer = raw_input("Would you like to exit? Enter 'Yes' or 'No': ")
while answer not in ["Yes","No"]:
answer = raw_input("Would you like to exit? Enter 'Yes' or 'No': ")
if answer == "Yes"
problem = True # This will cause you to exit the loop
Write it more pythonic :
while True:
with open("solutions.txt") as foo:
issue = input("What is wrong with your device?")
if 'wet' in issue and 'water' in issue:
print(foo.readline() + foo.readline())
question = input("Do you want to continue? (Y/N)")
if question == 'N':
break
First off, note that you can simply use a forever-while loop with True and break the loop whenever you want, or as a question and break the loop wehn the answer is NO. Secondly, for opening the file you better to use with statement that close the file at the end of the block automatically. And for reading the first 2 line if your file is huge you better to read the lines using readline method.

how to stop a loop

I wrote this code that I'm trying to get it to work. What I am trying to do is to prompt user to enter names of employees and use a list to store the names.
Now the part that I am having trouble with is with the loop, the loop is suppose to stop when the user types 'done', and then display the number of names entered, and with another loop, display the names entered each on its own line.
I don't know what I am doing wrong with the code but, after the user enters then names it will say: 'Press enter to continues adding names' and it will also say: 'If you would like to stop adding names, type=done'
If the user hits enter, then it should ask for another name and repeat the questions to see if user wants to add more or stop. But for some reason, even if the user press enter to continue adding names, it still outputs the number of names entered and the list of names. I don't want that to happen, I'm trying to get it to where it will display the result ONLY if the user types 'done' but the word 'done, cannot be displayed in the output. I've looked over and over the code and can't figure out what if am doing wrong.
Here is my code:
employee_list=[]
stop='done'
while stop == 'done':
employee_name=input('Enter name of employee:')
employee_list.append(employee_name)
print('Press enter to continues adding names')
enter_another=input('If you would like to stop adding names, type=done ')
print()
list_size=len(employee_list)
print('The number of employees you have entered: ', list_size)
for index in range(list_size):
print(employee_list[index])
You haven't got a check in your code if a person types done.
For example:
if enter_another == "done":
stop == "finished now"
But this doesn't make sense, your check is saying "if stop is done then keep going", which makes no sense semantically.
Try this instead:
more_employees = True
while more_employees: # Never do thing == True
# ... your code
enter_another=input('If you would like to stop adding names, type=done ')
if enter_another == "done":
more_employees = False
# ... the rest of your code
As stated, PEP8 recommends against comparing thing == True:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
Try this. I have put your printing condition outside the loop.
employee_list=[]
stop='done'
while stop == 'done':
employee_name=raw_input('Enter name of employee: ')
employee_list.append(employee_name)
print 'Press enter to continue adding names'
enter_another=raw_input('If you would like to stop adding names, type=done \n')
if enter_another == 'done':
stop = 'random'
print
list_size=len(employee_list)
print 'The number of employees you have entered: ', list_size
for index in range(list_size):
print employee_list[index],

Categories

Resources