Input/If statement - correct way of writing - python

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

Related

Function Remain Without Looping (Recursion Error)

This is difficult without just laying the function out first so here we go. FYI, this is essentially a medical diagnostic program I'm making.
def patient_discussion(patient, q_count): #q_count keeps track of the number of questions asked.
response_list = ['n', 'menu']
if q_count == 0:
question = input('''What would you like to ask the patient? You can ask them for/about:
N = Their name.
Or type "main" to go back to the main screen. ''')
else:
question = ('What would you like to ask the patient? ') #This is to avoid spitting out a huge block of text. I think it's important the first time but not the rest.
if question.lower() == "n":
print("My name is "+ patient['Name'] + ". ")
q_count += 1
print()
patient_discussion(patient, q_count) #This is to loop back in case the player wants to ask additional questions.
if question.lower() == "main": #To bring the patient back to the main screen if they want.
menu(patient)
if question.lower() not in response_list: #To prevent an error.
print("What the heck are you even asking me, doc?")
print()
q_count += 1
patient_discussion(patient, q_count)
When I do this, there's a recursively loop error.
RecursionError: maximum recursion depth exceeded while calling a Python object
And I know what's happening. The original function is called as
patient_discussion(patient, 0)
And when I ask a question, the q_count goes up to 1 then 2 and so on and so forth. I just don't know why it's even looping to an incorrect answer since "n" would be in the above list.
I'd appreciate any help.

Using a While Loop to check whether user's input (string) belongs to a List?

I'm new to Python, with a bit of background in C. I'd like to set up a while loop with try - except - else construction. I have successfully done this when trying to verify a data type (using except: ValueError), for instance prompting the user for an integer. However for this program, the the user inputs a string and the program needs to check that string against a list of strings, and if it's not in there, ask the user again. My code so far runs but regardless of the user's input, the loop breaks. Here it is now:
senses = ["touch", "smell", "sight", "hearing", "taste"]
while True:
try:
choice = input("What is your favorite sense? ")
except:
if choice not in senses:
print("Sorry, I don't think that's a sense")
#try again, return to start of loop
continue
else:
break
Originally my code looked like this and it worked but there is the issue of redundancy with the input method:
senses = ["touch", "smell", "sight", "hearing", "taste"]
choice = input("What is your favorite of the 5 human senses:")
while choice not in senses:
choice =input("What is your favorite of the 5 human senses")
A matter of personal preference / problem suitability, but I would tend to use something like this
senses = ["touch", "smell", "sight", "hearing", "taste"]
choice = ""
while choice not in senses:
choice =input("What is your favorite of the 5 human senses")
This initializes choice as something not in senses, thus forcing the first loop
I'd write that like:
senses = {"touch", "smell", "sight", "hearing", "taste"}
while True:
choice = input("What is your favorite of the 5 human senses? ")
if choice in senses:
break
This way you're only asking the question in one place. while True means "do this forever", and break stops the loop once the condition is met.

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'")

Am I using the isalpha() method in my while loop correctly (Python)?

I want to allow the user to construct an argument using premises (sentences that support your argument) and a conclusion. I want the program to raise a question (yes/no) if the user wants to add an additional premises after the first one. If yes --> premises: ____, If no --> Conclusion: ____. The problem is that i can write no for the additional premises question (or anything) and it'd take that input and make another premises.
Thank you in advance for any help!
print("Welcome to the argument-validity test!")
def premises_conclusion():
premises_1 = raw_input("Premises: ")
premises_qstn = raw_input("Would you like an additional premises(yes/no)? ")
additional_premises = raw_input("Premises: ")
while premises_qstn.isalpha():
additional_premises = raw_input("Premises: ")
if premises_qstn == 'yes':
additional_premises = raw_input("Premises: ")
elif premises_qstn == "no":
break
else:
print("Please enter yes or no.")
conclusion = input("Conclusion: ")
premises_conclusion()
# When i use additional_premises in line 7, the while statement asks the additional
# premises even if i say 'no'.
# When i delete additional_premises in line 7, the while statement only skips
# to the conclusion (acts like i said no for yes). No matter what I say it
# skips to the conclusion.
These lines seem problematic:
premises_qstn = raw_input("Would you like an additional premises(yes/no)? ")
additional_premises = raw_input("Premises: ")
It asks if you want additional premises, but doesn't check the input (premises_qstn) before immediately asking for more no matter what.
Then, the first line inside the while loop asks for premises again, but the loop breaking condition of elif premises_qstn == "no": still hasn't been checked.

Integer, Input, print

The main problem I have is with the printing, It doesn't work as it gives me the error:
NameError; the name 'ask2' is not defined
I am an absolute beginer in Python, therefore I have literally NO idea how to make it global, or something in those lines.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
if int(ask) == 1:
print("========================================================================")
ask2 = ""
while ask2 != 'exit':
ask2 = input("Please enter it in such form (XX00XXX): ")).lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
# This 'elif' is optional, it just provides a bit better feedback to the user so he knows he manually stopped
elif ask2 == 'exit':
#There are other parts of the code, but it's not necessary
else:
plate = ""
# This randomly adds two capital letters (your own code)
for i in range(2):
plate += chr(random.randint(65, 90))
print()
print(plate)
print("The program, will determine whether or not the car "+str(plate),ask2+" is travelling more than the speed limit")
Your code is currently structured like this:
if some_condition:
ask2 = ''
else:
...
print(ask2)
The problem is that when some_condition is False and the else block executes, after the if/else when you try to print ask2, you're getting the NameError since the if block never ran and ask2 is undefined.
You need to do:
ask2 = ''
if some_condition:
...
else:
...
print(ask2)
Also, unrelated, but there's absolutely nothing wrong with using break.
The error does say it fairly well. ask2 doesn't seem to be defined.
Did you define int somewhere before? You won't be able to use it, if you haven't declared it somewhere before.
if int(ask) == 1:
print("========================================================================")
ask2 = ""
while ask2 != 'exit':
it seems like you are calling on ´ask2 being != 'exit' ´ but you did not did not assign any value to it. It just says ask2 ="". Try to assign it some value before, either by defining it or by having one automatically assigned.

Categories

Resources