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'")
Related
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()
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.
I have a little piece of code in Python where I'm trying to compare a user input to a specific element in an array. Here is the code:
movies = ["movie 1", "movie2", "movie3"];
answer = raw_input("What is your guess: ")
if answer == movies[1]
then print ("yes that is correct")
else:
print ("no that is incorrect")
I know the indentation above looks wrong becasue I typed it out in the text box and I'm new to this site as well as python.
I also know that I probably need to use some sort of conditional loop, maybe a while loop, but I'm having trouble finding where I can compare user input string value to a string value in my array. Any ideas how I might accomplish this?
Have fun with Python! I guess you are trying to make a loop which keeps receiving inputs from user to compare with the desired input until user types the correct input. If so, one way, it can be implemented as following (but think of adding a break condition, like input == "Bored" , to avoid infinite loop and hard stopping your code):
movies = ["movie 1", "movie2", "movie3"]
correctAnswer = movies[1]
is_notCorrect = True
while(is_notCorrect):
answer = raw_input("What is your guess: ")
if answer == correctAnswer:
print("Yes, that is correct")
is_notCorrect = False
else:
print("No, that is incorrect")
In the code above, when is_notCorrect turns into False. At next condition checking, it will break condition, and done with the loop.
Your code has some issues
movies = ["movie 1", "movie2", "movie3"]; # No need the semi-colon in Python
answer = raw_input("What is your guess: ")
# Need a colon here after if condition, new line, and indent.
#If you don't like the colon, you need to write a different way with one line of code Eg: <Do A> if <Condition happens> else <Do B>
if answer == movies[1]
then print ("yes that is correct") # No then in if-else statement in Python
else:
print ("no that is incorrect")
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.
I began scripting today and don't know pretty much.
But how do I get it to end?
passwort = "Admin"
Logout = "Logout"
versuch = 0
while versuch != passwort:
versuch = str(input("Passwort: "))
while versuch !=Logout:
print ("Menu:Logout")
vesuch = str(input(">"))
if str(input) == "Logout":
print ("Do you really want to Logout?")
print("Y / N")
Main issue here is in second while loop:
while versuch !=Logout:
print ("Menu:Logout")
vesuch = str(input(">")) #Precisely here
You are not checking with the same variable in the while loop condition and in the assignment, may be mistyping mistake (in While loop condition it is: versuch, and in your assignment it is vesuch). so you should change it in your assignment to versuch
Another mistake here, is here:
if str(input) == "Logout":
you are not calling the input function here but just getting its reference, you need to add parenthesis to call the function: input()
Last thing, use raw_input() instead of input() to avoid explicitly adding the double quotations in the user input otherwise it will not match, so with your code, if I enter : Admin , it will not match, but if I enter "Admin" it will work,
You don't want to bother the user to each time add the double quotations to their input, right?
Also don't need the str() function if you use raw_input() because it already returns a string
If you're using Py3+ (which you are, judging by the print()) you don't have to explicitly convert the input to a string!
versuch = input("Passwort: ")
Doing the above is enough!
Coming to the if, you probably want to do something along the lines of:
while something:
fooo foooo
fooo foooo
if versuch == "Logout":
fooo
if input() == "Y":
break
Don't forget to indent it enough to put the if statement inside the while block!
PS: Welcome to Python!