I have some problems with this small program for rolling two dices.
Why the program stops before it finishes the loop and instead it asks a loop times "do you want to play again?"
Thank you for your help!
#Program which simulates the rolling of two dice
import random
def rolling_dices(repetitions):
a = repetitions
b = 1
while b <= a:
i = (random.randrange(1,7))
y = (random.randrange(1,7))
b +=1
print(i, y, "\t =>", int(i+y))
answer = input("do you want to play again? (Y/N)")
if answer.lower() == "y":
continue
else:
break
rolling_dices(5)
Seems like you want to remove the question from the dice-rolling loop and instead put the dice-rolling loop into a loop with the question prompt.
import random
def rolling_dices(repetitions):
a = repetitions
b = 1
while b <= a:
i = (random.randrange(1,7))
y = (random.randrange(1,7))
b +=1
print(i, y, "\t =>", int(i+y))
rolling_dices(5)
while input("do you want to play again? (Y/N)").lower() == "y":
rolling_dices(5)
print("done.")
Make sure to correctly indent the while loop:
#Program which simulates the rolling of two dice
import random
def rolling_dices(repetitions):
a = repetitions
b = 1
while b <= a:
i = (random.randrange(1,7))
y = (random.randrange(1,7))
b +=1
print(i, y, "\t =>", int(i+y))
answer = input("do you want to play again? (Y/N)")
if answer.lower() == "y":
continue
else:
break
rolling_dices(5)
More info on indentation in python: http://www.diveintopython.net/getting_to_know_python/indenting_code.html
Related
The condition is simple. If sum<=20 then print sum or else loop the starting from the input. However, this is looping even if the input is valid. How should I fix this? My code is in the picture
code in the picture
You need to specify that you wish to update the global variable.
invalid_input = True
def start():
x = int(input("number1: "))
y = int(input("number2: "))
z = int(input("number3: "))
sum = x + y + z
if (sum <= 20):
global invalid_input
invalid_input = False
print(sum)
else:
print("return and give valid input")
while invalid_input:
start()
Alternatively, you could return a boolean from the function.
def start():
x = int(input("number1: "))
y = int(input("number2: "))
z = int(input("number3: "))
sum = x + y + z
if (sum <= 20):
print(sum)
return True
else:
print("return and give valid input")
while True:
if start(): break
Related post: python-function-global-variables
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed last year.
I am fairly new to programming and I scrapped some code together to make a sequence calculator using python.
I'm trying to restart it at the "user_continue = input ("Would you like restart [y/n]? ")" part whenever the user would input an invalid answer, but I don't know how to do that, help?
import time
from time import sleep
while True:
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")
???
import time
from time import sleep
def sumOfAP( a, d,n) :
sum = 0
i = 0
while i < n :
sum = sum + a
a = a + d
i = i + 1
return sum
def takeInputs():
numsterm = int(input("Enter Number OF terms: "))
firstterm = int(input("Enter First Term: "))
difference = int(input("Enter The Difference: "))
print (sumOfAP(firstterm, difference, numsterm))
# restart here
takeInputs()
while True:
user_continue = input ("Would you like restart [y/n]? ")
if user_continue == ('y'):
takeInputs()
print("Continuing...")
sleep(0.5)
elif user_continue == ('n'):
print ("Thank you for using this program")
print ("")
print ("-PettyRap")
sleep(2)
break
else:
print("Error Command Not Found")
So I'm new to programming and all, and tried doing it but the prompt somehow ends the loop. Is there any simple alternative for this?
import time
import win32api
c = 1
x = 1
while x == 1:
if c==1:
a=win32api.MessageBox(0, "*Question here*?(y/n)", "Prompt")
c=c+1
y = win32api.GetKeyState(0x59)
n = win32api.GetKeyState(0x4E)
if y<0 and n>=0:
x=x+1
print("y")
a.close()
elif y>=0 and n<0:
x=x+1
print("n")
a.close()
time.sleep(0.05)
I want to input a series of numbers and end with "stop", the while loop is to check if x is not equal to the 'stop', it continues add up the input number and output the sum for each loop, however the while loop falls into infinity. For example, my input is:
12
35
56
23
56
455
556
344
22
22
stop
#read the input
x = input()
#add up by a loop
T = 0
x_int = int(x)
while x != 'stop':
for i in range(1, 10):
T += x_int
print(i, T)
You need to prompt for the next input in the while loop. As stands, you never prompt for additional data and so you will never see the stop. I added a prompt so that it is more clear.
#add up by a loop
T = 0
while True:
x = input("enter data: ")
if x == 'stop':
break
x_int = int(x)
for i in range(1, 10):
T += x_int
print(i, T)
Several of us are confused about how you want to enter data. If you don't want any prompts and want to read any number of lines from the user (or perhaps piped from another program) you could read stdin directly.
#add up by a loop
import sys
T = 0
for line in sys.stdin:
x = line.strip()
if x == 'stop':
break
x_int = int(x)
T += x_int
print(i, T)
Try this program and see if it works. The problem with your code was there is no need of a for loop. I didn't understand why it was used there in your program, hope you understood.
T = 0
i = 0
while True:
x = input("enter data: ")
if x == 'stop':
break
else:
i =i+1
x_int = int(x)
T += x_int
print(i, T)
I know the line "goto Start" is wrong just put it there, that's where I want the code to loop back to the start of the code but cannot figure out how to do it at all. Please help....
dsides = int(input("how many sides do your dice have?"))
print("Your dice has " + str(dsides) +" sides")
dint = int(input("How many dice do you want to roll?"))
print("You are rolling " + str(dint) + " dice")
import os
answer=0
import random
y=0
while( y < dint ):
out = random.randint(1, int(dsides))
print(str(out))
y=y+1
while (True):
answer = raw_input('Run again? (y/n): ')
if(answer in ("y", "n")):
if(answer == "y" ):
goto start
else:
print("GoodBye")
break
else:
print ("Invalid input.")
break
wrap the code in a function and call the function:
def my_function(output=''): # <-- change 1
dsides = int(input("how many sides do your dice have?"))
print("Your dice has " + str(dsides) +" sides")
dint = int(input("How many dice do you want to roll?"))
import random
y = 0
while y < dint:
out = random.randint(1, int(dsides))
output += "{} ".format(out) # <-- change 2
# print(str(output)) # <-- change 3
y=y+1
while True:
answer = raw_input('Run again? (y/n): ')
if answer in ("y", "n"):
if answer == "y":
my_function(output) # <-- recursive call
else:
print(output) # <-- change 4
print("GoodBye")
return
else:
print ("Invalid input.")
break
Example output:
how many sides do your dice have?6
Your dice has 6 sides
How many dice do you want to roll?6
Run again? (y/n): n
2 1 3 4 6 5
GoodBye