# Dice Rolling Random Number and Guessing Game
import random
user_choice = 'y'
while user_choice != 'N' or user_choice != 'n':
print(random.randint(1,6))
user_choice = input("Do you want to continue: ")
print("You are exited")
The logic of the while condition is wrong.
Your loop runs forever, because the character will ALWAYS be different from one of the suggested characters. So the while condition is always true as at least one of the two parts is always true.
You want something like
while user_choice != 'N' and user_choice != 'n':
...
If you want to go for a more 'pythonic' way, query a set in the while condition:
while user_choice not in {'n', 'N'}:
....
There are many similar ways with tuples, lists, ... to express the condition other than querying every character individually in a chain of 'and' conditions.
As far as coding is concerned, the question is answered already, but I'd like to offer a more deep explanation of why the answer was the and operation instead of or.
The question "Did the user enter neither 'n' or 'N'?" can be expressed using Boole Algebra as
Answer = Not('n' or 'N'), and using the DeMorgan theorem this can be rewritten as
Answer = Not('n') and Not('N')
In your code, the first of the two ways to write this would look like
while !(user_choice == 'N' or user_choice == 'n'):
I hope this clears up the logic behind your question.
Related
Let me explain with a quick bit of code.
Code:
choice = raw_input("Do you like pineapple? Y/N: ")
if choice == "y".lower() or choice == "ye".lower() or choice == "yes".lower():
print("Sammmmeee")
else:
print("Nani! You criminal!")
How could I make it so instead of doing:
if choice == "y".lower() or choice == "ye".lower() or choice == "yes".lower():
it automatically accepts, "y", "ye" or "yes" without needing to do or so much?
First of all, you shouldn't be applying lower to the right hand side, which is a constant and already lowercase. You should be applying it to the variable input:
choice = raw_input(...).lower()
There are a number of ways to check for the match you are looking for. The easiest is to use startswith:
if 'yes'.startswith(choice):
Another way would be to explicitly check for containment in a set or tuple:
if choice in ('y', 'ye', 'yes'):
This is only necessary for cases that don't fit into a simple method check, like if you wanted to add ok to the list of options.
If you wanted to have multiple function checks, you could use any with a generator expression:
if any(f(x) for f in ('yes'.startswith, 'ok'.startswith)):
All of the tests here are properly short circuiting, just like your original expression.
You can use startswith to achieve this:
if 'yes'.startswith(choice.lower().strip()):
print('You said "yes"!')
This will case-insensitively match exactly 'y', 'ye', and 'yes':
choice = raw_input("Do you like pineapple? Y/N: ")
if choice.lower() == 'yes'[:len(choice)]:
print("Sammmmeee")
else:
print("Nani! You criminal!")
You can just pick the first character of the input to compare with 'y'. Also note that you need to make the input lowercase. So the code becomes:
choice = raw_input("Do you like pineapple? Y/N: ")[0]
if choice.lower() == "y":
print("Sammmmeee")
else:
print("Nani! You criminal!")
(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop.
again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #**
while again2 == "y":
print("\nOK! Thanks for using this GTIN-8 calculator!\n\n")
restart2()
break #Break ends the while loop
restart2()
I'm struggling to think of ways that will allow me to respond with an output when they input neither of the choices given. For example:
if again2 != "y" or "n"
print("Not a valid choice, try again")
#Here would be a statement that sends the program back to the line labelled with a **
So, when the user's input is not equal to "y" or "n" the program would return to the initial statement and ask the user to input again. Any ideas that still supports an efficient code with as little lines as possible? Thanks!
def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"):
while True:
result = input(prompt)
if result in choices: return result
print(error)
is probably a nice generic way to approach this problem
result = get_choice("Enter A,B, or C:",choices=list("ABCabc"),error="Thats not A or B or C")
you could of coarse make it not case sensitive... or add other types of criteria (e.g. must be an integer between 26 and 88)
A recursive solution:
def get_input():
ans = input('Y/N? ') #Use raw_input in python2
if ans.lower() in ('y', 'n'):
return ans
else:
print('Please try again.')
return get_input()
If they're really stubborn this will fail when it reaches maximum recursion depth (~900 wrong answers)
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
What I'm trying to do is that, if I ask a question only answerable by Yes and
No, I want to make sure that yes or no is the answer. Otherwise, it will stop.
print("Looks like it's your first time playing this game.")
time.sleep(1.500)
print("Would you like to install the data?")
answer = input(">").lower
if len(answer) > 1:
if answer == "no":
print("I see. You want to play portably. We will be using a password system.")
time.sleep(1.500)
print("Your progress will be encrypted into a long string. Make sure to remember it!")
else:
print("Didn't understand you.")
elif len(answer) > 2:
if word == "yes":
print("I see. Your progress will be saved. You can back it up when you need to.")
time.sleep(1.500)
else:
print("Didn't understand you.")
First:
answer = input(">").lower
should be
answer = input(">").lower()
Second, len(answer) > 1 is true for both "no" and "yes" (and anything larger than one character, for that matter). The elif block will never be evaluated. Without modifying significantly the logic of your current code, you should do instead:
if answer == 'no':
# do this
elif answer == 'yes':
# do that
else:
print("Didn't understand you.")
Something like:
if word.lower() in ('yes', 'no'):
would be the simplest approach (assuming case doesn't matter).
Side-note:
answer = input(">").lower
Is assigning a reference to the lower method to answer, not calling it. You need to add parens, answer = input(">").lower(). Also, if this is Python 2, you need to use raw_input, not input (In Python 3, input is correct).
I have a line in a function filter3 is a dict that I create via a shuffle function.
answer = shuffle(filter3)
print(answer)
userConfirm()
What I want to do is implement my userConfirm() function and if the user is unhappy with the output they select "N" and it will make answer go again.
Just not sure what to put in my "N" response in my function to make this happen.
import sys
def userConfirm():
"""get user confirmation to proceed"""
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == "N":
#What to do here
elif userChoice == "Q":
sys.exit("You Quit the Program")
elif userChoice == "Y":
print("OK Proceeding")
goto is considered harmful since the end of the sixties. Google for "goto considered harmful", there's an article by Dijkstra about that topic which became so famous that the phrase "considered harmful" nowadays is often reused for similar topics.
The reason is plain an simple: With goto you can create code which is hard to understand, hard to debug and hard to extend.
Use a proper loop for what you want. Rethink your problem from "I want to go back under this condition" to "I want to repeat this until this condition is met." Then writing it as a loop comes much easier and more natural.
Unfortunately, Python has no repeat … until for loops testing at the end. You only have for loops (for a specific list of iterations to perform) and while loops which test at the beginning, not the end. But you can use a while True for this and test explicitly in the end yourself:
while True:
do_something()
if break_condition:
break
Your second issue (given only in the comment below your question) can be solved by letting userConfirm() return a value stating whether the user wishes a repetition or not:
def userConfirm():
"""get user confirmation to proceed"""
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == "N":
return False
elif userChoice == "Q":
sys.exit("You Quit the Program")
elif userChoice == "Y":
print("OK Proceeding")
return True
while True:
do_something()
if userConfirm():
break
import sys
def userConfirm():
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == 'N':
return False
elif userChoice == 'Q':
sys.exit("You Quit the Program")
elif userChoice == 'Y':
print "OK Proceeding"
return True
while True:
answer = shuffle(filter3)
print answer
if userConfirm():
break
goto is always considered a bad programming practice after the advent of modern programming languages. It becomes hard to debug, track bugs/errors or even try to understand what in the hell you've written a few months ago(especially when your program deals with multiple nested if/else statements or loops). The best way to solve a problem without using goto is by structuring your program well. Grab a paper, design the structure. Now after you have a concrete plan with good logic, start coding. Use LOOPS, use BREAK and CONTINUE statements where necessary. These simple tricks/methods will help you build neat programs and save you from headaches. As they say "weeks of coding saves you hours of paperwork".