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.
Related
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.
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():
Here's the problem: my while loop doesn't repeat AT ALL, it just returns a blank line in the Python Launcher and doesn't carry on the code, i added a print function at the end to check if it did just skip.
I used several ways of getting the code to repeat, such as While True: and While 0 == 0 so i have started to think there is a problem somewhere else in the code. The code in question is:
while True:
while i <= dice_amount:
dice_output = random.randint(0,dice_range)
print("dice number ", i, " is ", dice_output)
i +=1
while input_answer == "unknown":
input_answer = input("would you like to throw the dice again? Y/N")
if input_answer == "N":
time.sleep(2)
os.exit
elif input_answer != "Y":
input_answer = "unknown"
print("code is broken") #to see if code just skips loop
This is what happens when i try to repeat
I would much appreciate the help and I'd just like to say I'm new to coding so I know it may not be optimised, however a comment saying how i could optimise it would be helpful.
At the start the variables are defined as such:
dice_amount = int(input("how many times would you like to roll the dice?"))
dice_range = int(input("how many numbers would you like on the dice?"))
input_answer = "unknown"
i = 1
You need to set i to one after "while True", and set input_answer to "unknown" before the second inner loop. Corrected code:
while True:
i = 1
while i <= dice_amount:
dice_output = random.randint(0,dice_range)
print("dice number ", i, " is ", dice_output)
i +=1
input_answer = "unknown"
while input_answer == "unknown":
input_answer = input("would you like to throw the dice again? Y/N")
if input_answer == "N":
time.sleep(2)
os.exit
elif input_answer != "Y":
input_answer = "unknown"
print("code is broken") #to see if code just skips loop
I have finally realized the problem, after reading the other comments and answers I came up with this fix. First of all I realized I didn't need to use the input_answer if none of the answers were Y or N, i just made it a repeating loop and if the were neither Y or N it just repeated the question, Y breaks the loop and N ends the program. if the reply was Y i added i = 1 so that it would repeat.
Here's the fixed code:
import random
import time
dice_amount = int(input("how many times would you like to roll the dice?"))
dice_range = int(input("how many numbers would you like on the dice?"))
i = 1
while True:
while i <= dice_amount:
dice_output = random.randint(0,dice_range)
print("dice number ", i, " is ", dice_output)
i +=1
while True:
input_answer = input("would you like to throw the dice again? Y/N")
if input_answer == "N":
time.sleep(2)
os.exit
elif input_answer == "Y":
i = 1
break
from random import randint
from time import sleep
fight = False
def start_up():
print("Fight Simulator - Test Stages.")
userInput = str(input("Enter your name "))
user_name = userInput
return user_name
def intro():
userName = start_up()
while True:
userInput = str(input("Welcome to the dojo, {}. To commence the first battle, type 'Start', or 'Begin'".format(userName)))
if userInput == "Start" or "start" or "Begin" or "begin":
return userInput
else:
print("Enter a valid response")
break
def fight_commence():
userInput = intro()
if userInput == "Start" or "start" or "Begin" or "begin":
fight = True
userHp = 100
opponentHp = 100
while fight == True:
userDmg = randint(0,100)
opponentDmg = randint(0,100)
opponentHp -= userDmg
if opponentHp <= 0:
opponentHp == 0
print("You did {} damage".format(userDmg))
sleep(1)
print("Opponent has {} hp remaining".format(opponentHp))
sleep(1)
if opponentHp <= 0:
print("You killed him!")
fight = False
else:
print("Enter a valid action")
fight_commence()
So for some reason the code doesn't print("Enter a valid response") when a response other than "Start" or "start" or "Begin" or "begin" is given. I want it to loop back to userinput stage, but instead it just carries on with the program as if everything is A ok. I can't figure out where I messed up.
Secondly, I want the opponentHp to automatically equal 0 when the health dips below 0. For instance, when opponentHp = -45, opponentHp should equal 0.
Any help is appreciated.
Well a big problem with the testing of the 'valid input' is the way your testing.
if userInput == "Start" or "start" or "Begin" or "begin"
This is not a valid python condition. Instead do something like this:
if userInput in ["Start", "start", "Begin", "begin"]
This comparison happens twice and is no good. For the opponenthp being 0, you currently have this as your statement and result:
if opponentHp <= 0:
opponentHp == 0
The condition is perfectly fine, but the == in the action is another conditional operator, you need to change it to:
if opponentHp <= 0:
opponentHp = 0
ADDITION
Also, in addition to the above items, when you use the break statement you will end the infinite loop you have set up and end the function without a returned value, you may want to consider changing it to a continue or pass statement, or simply remove it.
The conditions (if-clause) are wrong. You should repeat 'userInput==' for every or.
Or, more concisely this:
userInput.lower() in ["start", "begin"]
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