Select parts of my code have been greyed out - python

I wrote a while loop asking the user whether they're male or female. Everything after "else" has been greyed out. When I hover over it with my mouse it says:
"Code is unreachable Pylance".
sex = input('What is your sex? (m/f/prefer not to say) ')
while True:
sex = input('What is your sex? (m/f/prefer not to say' )
print('success:)')
else:
print("sorry doll, I can't help you:( let's try again.")
print("we're out of the loop")
How can this be fixed?

Note the differences. the break exit the loop totally.
The while loop continues operation as long as it condition evaluates as True. so therefore you need to create condition to either break from the loop within your code or modify the loop to evaluate as false.
Also, you would realise that when the loop eventually turns false only then is the else statement called. However, the else wont be called if break keyword was used to exit the loop.
tries = 5
opt =('m','f','prefer not to say')
while tries: #evaluates True but false if tries = 0
sex = input('What is your sex? (m/f/prefer not to say' ).lower()
if sex not in opt:
print("sorry doll, I can't help you:( let's try again.")
tries -=1
continue
print('success:)')
tries=0 # note here the bool(0) == False
else:
print('happens if there is no break from the loop')
print("we're out of the loop")
#opt 2
while True:
sex = input('What is your sex? (m/f/prefer not to say' ).lower()
if sex not in opt:
print("sorry doll, I can't help you:( let's try again.")
continue
print('success:)')
break. # completely exits the loop
else:
print("sorry doll, I can't help you:( let's try again.")
print("we're out of the loop")

Related

How to make a while loop continue to loop if certain parameters aren't met?

still a beginner at programming, so forgive the mistakes:
I am trying to make my user-defined function loop until the user types in "no."
However, when I was adding extra functions to foolproof the loop, i.e. check to make sure what they typed was actually "yes" or "no" and not random garbage/numbers, it seems to run into problems. Here is the loop statement:
while True:
percentConvert()
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop) #added for debugging
if stop != "no" or "yes":
print("INVALID INPUT")
elif stop == "no":
break
else:
continue
First "if" is checking whether the input was not "no" or "yes", next "elif" is checking if the input was "no" and if so stop the program, and "else" (yes) continue. Instead, it asks if I would like to continue, tells me "INVALID INPUT" no matter what, and continues. What am I doing wrong?
stop != "no" or "yes" is not the correct syntax. What you want is either not (stop=="no" or stop=="yes") or stop not in ["no","yes"].
Consider the following modified version of your code:
while True:
percentConvert()
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop) #added for debugging
if stop not in ["no","yes"]:
print("INVALID INPUT")
elif stop == "no":
break
Note that the above, while it technically runs, will run percentConvert() in response to an invalid input. Here's a script that behaves in what I suspect is the desired way.
while True:
percentConvert()
while True:
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop)
if stop not in ["no","yes"]:
print("INVALID INPUT")
else:
break
if stop == "no":
break
In the loop as it's currently written, the condition is being interpreted as (stop != "no") or ("yes"). "yes" is a non-empty string, which Python considers to be a "truthy" value, which means that the or and if treat "yes" as if it were True, which means that the if-block always executes.
This is a good use case for using custom error handling.
First define the base class for errors, and a custom exception.
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class InvalidInputError(Error):
"""Rasied when user input is not yes/no"""
pass
Then in your while loop, you can use the exception.
percentConvert()
while True:
try:
stop = input("Would you like to continue? yes or no: ".lower())
if stop == 'yes':
percentConvert()
continue
elif stop == 'no':
break
else:
raise InvalidInputError
except InvalidInputError:
print("Must enter either yes/no")

How to request input Iterations from users in python code

Pardon my cheap question, I am still a beginner!
Task: In the block of code below, I want the user to be able to try 3 wrong names,
and the program should possible print ‘you have reached the maximum attempts’
before the ‘Break’ command will execute. How can I achive this?
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
name = input()
#[I need to add some iterations here!]
break
print('Thank you!')
Try this:
tries=1
while True:
name = input('Please type your name\n')
if name != 'Louis':
if tries!=3: #==== If tries is not equal to 3
print('Name is incorrect check and enter your name again!')
tries+=1 #=== Add 1 to tries
else:
print("You have reached maximum attempts.")
break #=== Break out of loop
else:
print('Thank you!')
break #=== Break out of loop
Here, this should help. You just iterate over the number of attempts you want to give the user (here it is 3 attempts). You could also use the while True loop with a counter.
nbr_of_tries = 3
for i in range(nbr_of_tries):
print('Please type your name')
name = input()
if name == 'Louis':
print('Thank you!')
#[I need to add some iterations here!]
break
elif i < nbr_of_tries-1:
print('Name is incorrect check and enter your name again!')
else:
print('Maximum number of tries reached. Exiting')
you can do something like this:
x=0
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
name = input()
#[I need to add some iterations here!]
if x==3:
print("you have reached the limit")
break
else:
x=x+1
else:
print('Thank you!')
break
count = 0
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
count += 1
#[I need to add some iterations here!]
if count > 2:
break
else:
print ("Required name entered")
break
print('Thank you!')
You can do this without break, something like this.
attempt = 0
while True and attempt < 3:
attempt += 1
print('Please type your name')
name = input()
if name != 'Louis':
if attempt == 3:
print('you have reached the maximum attempts')
else:
print('Name is incorrect. Please check and try again!')
print('Thank you!')
like this?
while True:
print('Please type your name')
name = input()
attempts = 3
while attemps:
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
attempts -= 1
name = input()
else:
print('maximum attempts reached')
print('Thank you!')
Explanation:
During the while loop the attempts-counter will be decremented if the if statement is True and the user can enter another name. If the counter reaches 0, the loop will stop and the maximum attempts reached message will be printed.

Use of continue in python - how to break out of an individual loop?

I have written some code that contains several while loops.
answer = "yes"
while answer == "yes":
name = input("what is your name?")
while len(name) > 0 and name.isalpha():
print("okay")
break
else:
print("error")
continue
job = input("what is your job?")
while job.isalpha():
print("great")
else:
print("not so great")
continue
age = input("how old are you?")
while age.isnumeric():
print('nice')
else:
print("not so nice")
continue
What I want the code to do is check for a valid name entry, and if it is invalid re-ask the user for their name. I want it to do the same thing with their job. Unfortunately, when I use continue after the job statement, instead of just re-asking for their job, it re-asks for their name as well. Does anyone know how to make it only re-ask for the job, and not re-do the whole program? Does anyone know how I could replicate this for multiple while loops I.e. Asking for job, name, age, star sign etc.?
Thank you.
You can use while True because answer never change.
It's useless while for 1 expression and 1 break.
You should put everything on a while True and check:
while True:
name = input("what is your name?")
job = input("what is your job?")
if len(name) > 0 and name.isalpha() and job.isalpha():
print("great")
break
print("error")
I moved the question into a seperate fuction to de-duplicate the code. It will ask again and again as long as the answer is not satisfactory.
def ask(s):
r = ""
while not r or not r.isalpha():
r = input(s)
return r
name = ask("What is your name?")
print("Okay. Your name is {}.".format(name))
job = ask("What is your job?")
print("Great. Your job is {}.".format(job))

How do I fully break out of a while loop nested inside a while loop? [duplicate]

This question already has answers here:
How can I break out of multiple loops?
(39 answers)
How can I fix the if statements in my while loops?
(1 answer)
Closed 5 years ago.
I am wondering if someone can help me figure out how to fully break out of my while loop(s) and continue with the rest of my program. Thanks!
import time
while True:
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
break
#Continue with rest of my program
The solution below adds a flag to control when to break out of the external loop that is set to break out each loop, and set back if no break has occurred in the internal loop, i.e. the else statement has been reached on the inner loop.
import time
no_break_flag = True
while no_break_flag:
no_break_flag = False
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
no_break_flag = True
#Continue with rest of my program
Obviously as you have a condition of while True on the inner loop you will always exit by breaking, but if you had some other condition this would break the external loop only if a break statement was reached on the inner loop.

Is there a use of break statement in python?

Is there a use of break statement in python? I noticed that we can end the while loop with another faster ways.
As an example we can say:
name=""
while name!="Mahmoud":
print('Please type your name.')
name = input()
print('Thank you!')
instead of:
while True:
print('Please type your name.')
name = input()
if name == 'Mahmoud':
break
print('Thank you!')
and what is the meaning of while True?
break is useful if you want to end the loop part-way through.
while True:
print('Please type your name.')
name = input()
if name == 'Mahmoud':
break
print('Please try again')
print('Thank you!')
If you do this with while name != 'Mahmoud':, it will print Please try again at the end, even though you typed Mahmoud.
while True: means to loop forever (or until something inside the loop breaks you out), since the looping condition can never become false.

Categories