python how to GOTO/REDO - python

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".

Related

Is there an if function in python for ASCII art? [duplicate]

I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.
For example, if I were to say
prompt1=input('Can I make this stupid thing work?')
I would have something along the lines of
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!
You are pretty close. Read a good tutorial :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True will loop the program forever.
Use == to test for equality.
Use .lower() to make it easier to test for answers regardless of case.
if/elif/elif/.../else is the correct sequence for testing.
Here's a Python 2 version:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
print is a statement instead of a function. Don't use () with it.
Another example, this time as a function.
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()

I am unable to exit From the while loop

# 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.

Force Python code to restart itself properly

I have tried to figure out a way on how to restart my code in Python, but I can't get it to work properly.
if keepLooping == True:
if userInput == randomNumber:
if attempt == 1:
print()
print("Correct, First try!")
stop = time.time()
print("It took", int(stop - start), "seconds.")
replay = input("Do you want to play again?: ")
if replay.lower() in ("yes"):
print()
os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv) # Restart code. You are here
elif replay.lower() in ("no"):
break
else:
print("Invalid input, Yes or No?")
continue # Restart segment. You are here
replayAttempt += 1
print()
As you can see, I have tried using os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv). Sure, it works, but then one of my inputs turn red, as you can see here. I have been trying to solve this but I can't find a solution.
I found a solution for the text being red, I added '\033[37m' before my inputs. The only problem I have now is that it can only restart once. When I try it again I get this error code here.
One way to this is to encapsulate thing into function
going from this
#start of scrip
#... game logic
#end of script
to
def game():
#...game logic
game()
encapsulated like this allow for easier reuse of stuff, and allow you to reduce repetition, if you do same thing in your code two or more times that is when you should factor that out into its own function, that is the DRY principle, Don't Repeat Yourself.
You can do something like this for example
def game():
#...game logic
return game_result
def main():
done=False
result=[]
while not done:
result.append( game() )
reply = input("Do you want to play again?: ")
if reply=="no":
done=True
#display the result in a nice way
main()
Here the main function do a couple of simple thing, play one round of the game, save the result, ask if you want to play again and display the result, and the game function do all the heavy work of playing the game.
Here is a simple working example of guess the number between 0 and 10
import random
def game(lower,upper):
answer = str(random.randint(lower, upper))
user_answer = input(f"Guess a number between {lower} and {upper}: ")
game_result = user_answer == answer
if game_result:
print("you win")
else:
print("you lose, the answer was:",answer)
return game_result
def main(lower=0,upper=10):
done=False
result=[]
while not done:
result.append( game(lower,upper) )
reply = input("Do you want to play again?: ")
if reply=="no":
done=True
print("Your result were",sum(result),"/",len(result) )
main()
Notice that the game function take 2 arguments, so you can play this game not just with 0 and 10, but any two number you desire, in turn the main function also take those same arguments but assign them default value so if you don't call this function with any of them it will use those default value and use them to call the game function, doing so allow for flexibility that you wouldn't have if you lock it to just 0 and 10 in this case.
(the sum(result) is because boolean are a subclass of int(numbers) so in math operation they are True==1 and False==0)

I need to figure out how to make my program repeat. (Python coding class)

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.

python - checking string for certain words

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

Categories