only one week ago i've started to learn Python. I've decided to create an app with jokes. My app is asking a number of a joke to display it. What should I write to make my app ask a number of joke again and again? image of code
*a1-a10 - vars with jokes
CodePudding user response:
To repeat a block of code, you would use a while loop, which will repeat a block of code as long as the condition is correct.
while(true):
num = int(input("text here"))
if num == 1:
doSomething()
else:
doSomethingElse()
As long as the condition is true, (which in this case it always will be) the program will repeat the block of code.
The loop above is an infinite loop, because the condition will always be true, so the program would need a way to exit, perhaps by adding an exit condition.
CodePudding user response:
Loops are perhaps one of the most fundamental programming concepts used so I would advise going and looking at these in more depth first.
If you wanted to ask the user to enter a number a certain of times you would use a for loop
.
for i in range(10):
#Perform action here
If you wanted to keep asking the user repeatedly until they end it themselves, a while loop
is a better option.
userInput = ""
while(userInput != "done"):
userInput = input("Enter the number of the joke: ")
#Get user input and do what you want with it
#This loop will terminate when the user inputs 'done'