Changing the order of operations inside a while() loop - python

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.

Related

Is there a function in python that executes two different commands receiving different specific inputs?

I am quite new to programming so if this question is really silly please don't laugh at me :(
I am looking for a function to ask for (yes or no) questions, just like the below:
if input("Question (y/n)") == "y":
print("y")
if input("Question (y/n)") == "n":
print("n")
If the input equals "y" it would execute line 2, if it equals "n" it would execute line 4
I tried using two ifs, like above, however the input function would've been executed twice if I did it like that, I also tried using elif like below:
if input("Question (y/n)") == "y":
print("y")
elif input("Question (y/n)") == "n":
print("n")
But if I used the method shown above the input command would still be executed twice
I also tried this:
if input("Question (y/n)") == "y":
print("y")
elif "n":
print("n")
Doesn't work as everything other than "y" would execute line 4
Is there a function that can be used in such situation or is there a specific method to use "if" "elif" "else" to achieve such requirements?
Much thanks! :))
Is there a function that can be used in such situation or is there a specific method
Yes, the function is called input(). In fact, you almost have it correct. The one piece you are missing is that you need to store the result in a variable. Then you can reuse that result as many times as you wish without calling input() multiple times:
answer = input("Question (y/n)")
if answer == "y":
# do something
elif answer == "n":
# do something else
else:
# print an error message
I suggest you read more about variables and how to use them to understand this.
while True:
x = input("y/n")
if x == "y":
#do suitable stuff
print(x)
elif x == "n":
#do suitable stuff
print(x)
else:
#use "break" instead of "pass" if you want to get out the "while"
pass

Why does my code make me type "yes" or "no" twice to get the result I want instead of just once?

Why does this code make me type yes or no twice to get the result I want instead of just once?
This is for the python dice roll text game, btw...
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
answer = input()
if answer == ('yes'):print("OK, here we go!")
elif answer == ("no"):print("Sorry about that, please try again another time.")
I am entering into a python class on Monday, this is one of the more common types of beginners code (granted I spiced it up by changing the dice from 6 sided to 20 sided, but it's more fun that way...lol) that I have read in some of the python books and sites I have visited, so I wanted to kind of get my feet wet a bit before I start my class.
So, any idea why I have to type yes or no twice, hitting enter after each time, to get it to run properly?
For the record, I am on Win10 right now but I also mostly use Parrot Security OS (Linux)...
Thanks for any and all feedback which anyone can provide...I know it's probably a stupid noob mistake or oversight, since I don't really know or understand the basics, but the quicker I can grasp them the better...
Python's function input() asks for users to input and waits the answer. As it can be seen in your code, you're doing it two times:
roll_again = input("Would you like to play again?")
answer = input()
The variable roll_again is being redeclarated to the first user's input, then the variable answer is getting the second user's input. You maybe meant to do something like:
roll_again = input("Would you like to play again?")
answer = roll_again
But first of all, there is no need to create an answer variable, you could simply use the roll_again on the if. Also the if statement is out of the while so your code might not work as you're trying to anyways~ (it will re-roll if user inputs yes but it will not print the message you're trying to; that will only happen when the user inputs no as that will go out of the while and blah blah blah)
This should be alright:
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
if roll_again == 'yes' or roll_again == 'y': print("OK, here we go!")
else: print("Sorry about that, please try again another time.")
Every time you call the input() function, it prompts for input. Since you call it twice for each iteration of your while loop, the user is prompted twice per iteration. You should instead only call the input() function once in your while loop.
You can also avoid using the answer variable if you just use the roll_again variable for your conditions for your if and elif.

variable not defined! (python)

I have been trying to run my first full text adventure but whenever i run it it says that answer is undefined! please help. in case if you're wondering, here's the code
accept = input("would you like to play the game??")
if accept.lower() .split() == "yes":
answer: str = input ("you wake up in a room with two doors in front of you. do you go to the left or the right?")
if answer.lower() .split() == "left":
answer2 = input(" you enter the left door. you find a phone with a peice of paper attached to the wall with the phone\n there are two numbers on the peice of paper\n will you choose to call the first one or the second one")
The reason is because the condition did not meet the if statement's requirement, so yo never defined answer. It was the .split() that made it wrong:
accept = input("would you like to play the game??")
if accept.lower() == "yes":
answer = input ("you wake up in a room with two doors in front of you. do you go to the left or the right?")
if answer.lower() == "left":
answer2 = input(" you enter the left door. you find a phone with a peice of paper attached to the wall with the phone\n there are two numbers on the peice of paper\n will you choose to call the first one or the second one")
You see, when yo have str.split(), python will return a list, not a string.
Have a look at this:
print("hello".split())
Output:
["hello"]
Your problem is similar to this:
x = False
if x:
answer = "yes"
print(answer)
Note how, because x is False, answer never gets defined and when Python reached the line where it needs to print answer, it will report the error.
You either need to define an else clause, or define the value up front, i.e.:
x = False
answer = "no"
if x:
answer = "yes"
print(answer)
Or:
x = False
if x:
answer = "yes"
else:
answer = "no"
print(answer)
Whether you pick a default or an explicit alternative should depend on what makes more sense for your code, they are both valid ways of solving this. In your case, it depends on what you need to do if they player does not answer "yes".

How to return an input within a def function with python

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

user input is asked for twice, only accepts second input

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

Categories