def main():
add_triangle_check = 1
while add_triangle_check > 0:
print "test"
add_triangle()
add_triangle_check= add_triangle()
def add_triangle():
add_triangle_check = 0
user_input = raw_input("Do you want to add more triangles? Y/N")
if user_input == ("y") or user_input == ("Y"):
add_triangle_check = 1
return add_triangle_check
main()
The above code returns the following:
test
Do you want to add more triangles? Y/N
Do you want to add more triangles? Y/N
why is it repeating? I only need the user input once.
You have called function add_traingle() twice.
Remove first add_traingle() and check if it works.
nvm, I thought I had to add the function add_triangle to the while statment so it would repeat properly, by removing it everything is running smoothly
Related
This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 2 years ago.
I keep getting the error "break is outside of loop" I've read a lot and I'm clearly missing something.
again = input(" again? y/n")
if again == "y" or \
again == "Y":
main()
else:
print("Thanks for using my calculator!")
again = input("Would you like to calculate again? y/n")
if again == "y" or \
again == "Y":
main()
else:
print("Thanks!")
#BREAK !!!!????
main()
while(True):
again = input("Would you like to calculate again? y/n")
if again == "y" or again == "Y":
main()
else:
print("Thanks!")
break
Try to use "break" in lower case. And, try to put it inside a loop. Please mark my answer if right. The "main" can have loop inside but that is independent of the while loop that I specified at the top.
I think a much simpler code would be something like this...
#set value of again to y. then go into the loop
#again.lower() will convert to lowercase allowing you to check against 'y'
again = 'y'
while again.lower() == 'y' :
main() #this will call main only if again is y
again = input("Would you like to calculate again? y/n")
print("Thanks!") #print thanks after you exit the loop
It seems like you may be coming from C++ where main and break are used. See if this helps. Note, calling a function has to be below/after you have defined it, if you are running python in interactive mode.
# Functions
def main():
print("Start calculator")
def myfunc(again):
if again in ("y", "Y"):
main() # call your calculator
else:
print("Thanks!")
# Run tests
print("Starting Test: 'y'. \n ")
again = 'y' # Set again to 'y'
myfunc(again) # Expect 'Start calculator' output
print("Starting Test: 'Y'. \n ")
again = 'Y' # Set again to 'Y' capital
myfunc(again) # Expect 'Start calculator' output
print("Starting Test: 'n'. \n ")
again = 'n' # Set input to 'n'
myfunc(again) # Expect 'Thanks!' output
print("Starting Test: 'error'. \n ")
again = 'error' # Set input to a random string
myfunc(again) # Expect 'Thanks!' output
I'm new to python and defining functions!
I'm writing a code and, on it, I'll sometimes ask the same question, this is why I want to use a function for it. I'm trying like this:
def cont():
ans = input("Continue? ")
return ans
But it's not storing anything on ans, cause every time I call it, I get an error saying that ans has not been declared!
Could anybody help me?
There's nothing wrong with your function. Here's an example:
def cont():
ans = input("Continue? ")
return ans
for i in range(2):
print(cont())
Output:
Continue? y
y
Continue? n
n
If you need to use it in an if-statement:
for i in range(3):
result = cont()
if result == 'y':
print('yes')
elif result == 'n':
print('no')
else:
print("I don't understand")
Output:
Continue? y
yes
Continue? n
no
Continue? p
I don't understand
However, if you don't plan on expanding the cont() function, and doing something more complex with it, as it is now, it's pretty useless because you can simply use input("Continue? ") wherever you use cont().
Your ans is only defined inside the scope of your cont() function, you cannot access it directly from outside that function. You are most of the way to sending this ans back out to the rest of your code with return ans, now you just need to store that value in something you can access from the rest of your code. Here is a sample code where I saved the output of cont() in the variable check in each pass of a while loop.
def cont():
ans = input("Continue? ")
return ans
gonna_continue = True
while gonna_continue:
check = cont()
if check == "no":
gonna_continue = False
print("All Done")
SAMPLE OUTPUT
Continue? 1
Continue? 2
Continue? 5
Continue? sbdj2
Continue? no
All Done
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.
I just started learning Python. Basically I just want to repeat the loop once if answer is yes, or break out of the loop if answer is no. The return True/False doesn't go back to the while loop?
def userinfo():
while true:
first_name=input("Enter your name here:")
last_name=input("Enter your last name:")
phonenum=input("Enter your phone number here")
inputagain=rawinput("Wanna go again")
if inputagain == 'no':
return False
userinfo()
Instead of while true: use a variable instead.
Such as
while inputagain != 'no':
Instead of looping forever and terminating explicitly, you could have an actual condition in the loop. First assume that the user wants to go again by starting again as 'yes'
again = 'yes'
while again != 'no':
# ... request info ...
again = input("Wanna go again?: ")
though this while condition is a bit weak, if the user enters N, n, no or ever no with space around it, it will fail. Instead you could check if the first letter is an n after lowercasing the string
while not again.lower().startswith('n'):
You could stick to your original style and make sure the user always enters a yes-like or no-like answer with some extra logic at the end of your loop
while True:
# ... request info ...
while True:
again = input("Wanna go again?: ").lower()
if again.startswith('n'):
return # exit the whole function
elif again.startswith('y'):
break # exit just this inner loop
I'm new to python and am taking a class so far my program looks like:
if choice=="1":
def addition():
print("You are doing addition. X+Y=Z")
X = int(input("Enter X:"))
Y = int(input("Enter Y:"))
sum = X + Y
print ("your total is:")
print (sum)
Well = "y"
while Well == "y":
again = input("Would you like to go again? (y/n)")
if again == "y":
addition()
if again == "n":
project()
else:
print("sorry re-enter choice")
it asks if I wan to go again before showing the actual addition part. how do I fix this? Thanks for your help :)
Lots of ways, but you could put your addition() function at the top like this:
Well = "y"
while Well == "y":
addition()
again = input("Would you like to go again? (y/n)")
if again == "n":
project()
if again not in ("n", "y"):
print("sorry re-enter choice")
Just add a flag which changes from false to true on first run, so that you don't see the "again" statement on first run.
A few points:
You shouldn't use sum as a variable name. It is a Python built in.
Look at what variable you use for your loop check, you will notice it quickly.
I think it would make more sense to ask if you want to go again at the end of the loop, after you do your stuff:
while loop_condition:
#do_your_stuff:
bla bla bla
#see if you should go again
bla bla = raw_input("Do you want to go again")
In fact, 99% of the time your while loops will follow this pattern (check condition, run body of loop, update condition) and if you are doing things in a different order (like iupdating the condition before running the body) its usually a sign you might be doing something wrong.