this is a crabs simulator. Im having trouble with my while loop. Where it says
while val == True:
Is where the problem happens. It stays in the while loop but nothing happens. If you find anything, I will be most grateful.
Here is the full code. (I have tried to validate everything)
import time
import random
control1 = False
control2 = True
x = True
val = True
z = True
def throw(n):
for i in range(1,n+1):
dice_1 = random.randint(1,6);dice_2 = random.randint(1,6)
print "roll",i,", die 1 rolled",dice_1,"and die 2 rolled",dice_2,",total",dice_1+dice_2
time.sleep(2)
return n
while z == True:
if x == True:
while control1 == False:
try:
amount_1 = int(raw_input("Welcome to crabs.\nHow many times would you like to roll:"))
control1 = True
except ValueError:
print ("Enter a valid number.")
throw(amount_1)
x = False
else:
while val == True:
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
val = False
while control2 == True:
try:
amount_2 = int(raw_input("How many times would you like to roll:"))
control2 = False
except ValueError:
print ("Enter a valid number.")
throw(amount_2)
z = True
elif roll_again == "2":
val = False
exit()
else:
val = True
After your first run through the program x and val are both False, but z is still True. As a result, the outer loop just keeps on rolling.
Put this line:
print z, x, val
Underneath that while statement.
You'll see that after you respond to the "Would you like to roll again: " question with "2", both x and val are false. That means that it'll go through every part of your if..else statement and just keep looping back infinitely.
It's stuck in an endless loop after the else branch (of if x) is executed, because you set the value to False. In the next iteration you then say while val == True and since this statement is not False and there is no other statement to consider, you run in an endless loop.
To see what I mean simply add a print statment here:
else:
print val
while val == True:
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
Now, I don't know if you need all those booleans for your actual program, but if I'd to make it work, I'd start eliminating the booleans I don't need. I think you have a too complex structure.
Edit:
Here's a suggestion to make the program simpler.
import time
import random
x = True
z = True
def throw(n):
for i in range(1,n+1):
dice_1 = random.randint(1,6);dice_2 = random.randint(1,6)
print "roll",i,", die 1 rolled",dice_1,"and die 2 rolled",dice_2,",total",dice_1+dice_2
time.sleep(2)
return n
def ask(x):
if x:
print "Welcome to crabs."
try:
amount = int(raw_input("How many times would you like to roll:"))
except ValueError:
print ("Enter a valid number.")
throw(amount)
while z:
ask(x)
x = False
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
continue
else:
break
Related
import random
given_number = round(float(input("Enter a number;\n")))
loop = True
while loop:
def Possibility(maximum):
count = 0
while count == 0:
x = random.randint(0, maximum)
if x:
print("X is True")
else:
print("X is false")
count += 1
print("Possibility calculated")
answer = input("Do you want to try again? Y/N")
if answer == "N":
loop = False
Possibility(given_number)
When I run the code even if I type N to answer as input program still continues to run any idea why this is happening?
import random
given_number = round(float(input("Enter a number;\n")))
def Possibility(maximum):
count = 0
while count == 0:
x = random.randint(0, maximum)
print(x)
if x:
print("X is True")
return True
else:
print("X is false")
count += 1
print("Possibility calculated")
answer = input("Do you want to try again? Y/N")
if answer == "N":
return False
while Possibility(given_number):
given_number = round(float(input("Enter a number;\n")))
Possibility(given_number)
the issue is, is that the function possibility was in a while loop, which means that the function would not be executed until it ended, which it couldnt, as the end condition was in the function.
this should fix your issue, by making it loop the function itself rather than the definition.
to break out of the loop, you would use the return function, which is an easy way to end the loop in this case.
I'm new to Python and I am trying to create a simple calculator. Sorry if my code is really messy and unreadable. I tried to get the calculator to do another calculation after the first calculation by trying to make the code jump back to while vi == true loop. I'm hoping it would then ask for the "Enter selection" again and then continue on with the next while loop. How do I do that or is there another way?
vi = True
ag = True
while vi == True: #I want it to loop back to here
op = input("Input selection: ")
if op in ("1", "2", "3", "4"):
vi = False
while vi == False:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
break
#Here would be an If elif statement to carry out the calculation
while ag == True:
again = input("Another calculation? ")
if again in ("yes", "no"):
ag = False
else:
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
exit()
elif again == "yes":
print("okay!")
vi = True #I want this part to loop back
Nice start. To answer your question about whether there's another way to do what you're looking for; yes, there is generally more than one way to skin a cat.
Generally, I don't use while vi==True: in one section, then follow that up with while vi==False: in another since, if I'm not in True then False is implied. If I understand your question, then basically a solution is to nest your loops, or call one loop from within the other. Also, it seems to me like you're on the brink of discovering the not keyword as well as functions.
Code
vi = True
while vi:
print("MENU")
print("1-Division")
print("2-Multiplication")
print("3-Subtraction")
print("4-Addition")
print("Any-Exit")
op = input("Input Selection:")
if op != "1":
vi = False
else:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
print("Placeholder operation")
ag = True
while ag:
again = input("Another calculation? ")
if again not in ("yes", "no"):
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
ag = False
vi = False
elif again == "yes":
print("okay!")
ag = False
Of course, that's a lot of code to read/follow in one chunk. Here's another version that introduces functions to abstract some of the details into smaller chunks.
def calculator():
vi = True
while vi:
op = mainMenu()
if op == "\n" or op == " ":
return None
x, y = getInputs()
print(x + op + y + " = " + str(eval(x + op + y)))
vi = toContinue()
return None
def mainMenu():
toSelect=True
while toSelect:
print()
print("\tMENU")
print("\t/ = Division; * = Multiplication;")
print("\t- = Subtract; + = Addition;")
print("\t**= Power")
print("\tSpace or Enter to Exit")
print()
option = input("Select from MENU: ")
if option in "/+-%** \n":
toSelect = False
return option
def getInputs():
inpt = True
while inpt:
x = input("insert first number: ")
y = input("insert second number: ")
try:
tmp1 = float(x)
tmp2 = float(y)
if type(tmp1) == float and type(tmp2) == float:
inpt = False
except:
print("Both inputs need to be numbers. Try again.")
return x, y
def toContinue():
ag = True
while ag:
again = input("Another calculation?: ").lower()
if again not in ("yes","no"):
print("Please input a 'yes' or a 'no'.")
if again == "yes":
print("Okay!")
return True
elif again == "no":
print("Done, Thank you for using Calculator!")
return False
It is a simple maze game I did for school. I have tried different solutions but still cant figure out how. I don't necessarily need a full solution; any tips would help.
x = 1
y = 1
valid_selection = True
while True:
if x == 1 and y == 1:
if valid_selection == True:
print("You can travel: (N)orth.")
valid_selection = True
choice = input("Direction: ")
if choice.lower() == "n":
y += 1
else:
print("Not a valid direction!")
valid_selection = False
elif x == 1 and y == 2:
if valid_selection == True:
print("You can travel: (N)orth or (E)ast or (S)outh.")
valid_selection = True
choice = input("Direction: ")
if choice.lower() == "n":
y += 1
elif choice.lower() == "e":
x += 1
elif choice.lower() == "s":
y -= 1
else:
print("Not a valid direction!")
valid_selection = False
elif x == 3 and y == 1:
print("Victory!")
break
You could have your function recieving x and y as parameters, removing the While True and replacing it with its creation, like def MyFunc(x,y), putting the valid_selection variable inside it and removing x and y attributions. And then you call it in the end of the code passing 1 and 1 as your desired parameters, like MyFunc(1,1)
There are many ways to create a function.
First, you need to abstract what your program do. The name of the function have to express this.
Second, you need to know what are the inputs. In your case the input must be x and y, or the proper names to these input.
The answer which your function will return is a important thing to know. The user will see a print or the user of the function will use a number, string or other object to feed other function.
I hope this not confusing.
import random
control = True
main = True
count = 0
user = input("Would you like to play Guess The Number?")
if (user == "yes"):
while (control == True):
randgen = random.randrange(0, 100)
print("Guess a random number")
while main == True:
number = int(input())
if (number == randgen):
print("Great Job you guessed the correct number")
print("You have tried ", count, "time(s)")
main = False
control = False
if (number < randgen):
count += 1
print("Your number is smaller than the random number")
print("You are at ", count, "trie(s)")
main = True
if (number > randgen):
count += 1
print("Your number is larger than the random number")
print("You are at ", count, "trie(s)")
main = True
again = int(input("Would you like to play again?1 for yes and 2 for no."))
if (again == 1):
control = True
user = ("yes")
if (again == 2):
control = False
print ("Ok bye bye")
##user ("no")
if (user == "no"):
print ("OK then Bye")
This Code works except for the part that when I want to play again it does not work. I have a coding background in java that's why I know some code but I made the guess the number game in java and I cannot figure out whats wrong with my python version(posted above).
Please make these changes:
if (again == 1):
control = True
main=True
user = ("yes")
I was making code on python but it showed an asterisk where the number goes on the cell, I tried making a print program to see if it was the code but it still didn't work. Please help, this is the code.
Items = ""
Total = 0
def adding_report(report):
while True:
X = input("please input integer to add or Q to quit")
if X.isdigit() == "True":
X = int(X)
Total = Total + X
if report == "A":
Items = Items + X
elif X == "Q":
print("Your result is")
if report == "A":
print("Items")
print(Items)
print("total")
print(Total)
break
else:
print("invalid input.")
adding_report("T")
You are stuck in an infinite loop.
Moreover, you cannot compare to the string "True", but rather to True only:
if X.isdigit() == True:
Instead of:
if X.isdigit() == "True":
You can also skip the comparison to True altogether
if X.isdigit():