How to stop the whole loop? - python

I have a problem in the loop below for python.
It doesn't stop as soon as totalout=4, but only when the whole loop for scorein is over. (i.e. the thrid loop)
For example, if the totalout=4 in scorein number 2, it runs the loop till it reaches 10
#global value
totalturn=0
totalscorein=0
totalout=0
def main
numberofturn=int(input("Number of score:"))
no_turn=['1','2','3','4','5','6','7','8','9','10']
#while loop condition
while totalturn<numberofturn and totalout<10:
#increasement
totalscore+=1
#for loop for score
for t in range(1,numberofturn+1):
turns=s*1
print("\n\n\nThe turn"+no_turn[t]+":",turns)
#for loop for number to appear from list
for c in range (10):
#list for random number to appear
numscore = ['1','2','3','4','5','6','7','8','9','o']
#random choice from numscore list to appear
from random import choice
scorein=choice(numscore)
print ("\n\nScores :",scorein)
if scorein.isdigit():
totalscorein=totalscorein+int(scorein)
if scorein.isalpha():
totalout+=1
if totalturn==numberofturn:
print("\nTotal turn played:",totalturn)
elif totalout==4:
print("\nTotal turns played",totalturn)
break
else:
print("")

Do you want the break to break out of the 3 loops? I guess you are judging from the title of the question
In this case, since it is the end of the function, you could just replace break with return

Try changing the and operator to or. That seems to be what you want.
while totalscore<numberofscore or totalout<10:

Related

Getting out after a for loop

I have a random function that creates two lists with random numbers ranging between 1 to 11.
I want to check if any of those two lists of random numbers contain numbers, any number from 9 to 11.
If numbers 9-11 are contained in any of the lists, I want the program to print a message and then stop the iteration. In other words, I would like the message to be displayed once.
I've tried the following, but the code prints the message multiple times during the execution.
split = [9,10,11]
container = []
for count in range (2):
rand_num = random.randrange (1, 11 + 1)
print(f"player_1 card is : {rand_num}")
container.append(rand_num)
for place in container:
if place in split :
print("you can go double down")
Your if statement is checked each time the for loop is run. You can use a break statement to exit the loop after finding it the first time. e.g:
for place in container:
if place in split:
print("you can go double down")
break
All you need is a break statement inside your loop.
break it when a certain condition is met.
# Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
outputs:
s
t
r
The end
Read this on breaking out of loops in Python.
This is another good article on working with indefinite loops
Try this one:
import random
split = [9,10,11]
container = []
for i in range (1):
rand_num = random.sample(range(1,12),2)
print ( f"player_1 card is : {rand_num}" )
container.append(rand_num)
for place in split:
if place in rand_num :
print("you can go double down")

#Python newbee. I am trying to print number after taking input from user using While loop

Python newbie. I am trying to print number after taking input from user using while loop.
my code takes int from user and then runs the loop. after printing the first number the code asks to continue after which the loop will continue.
My code is below:
i = 1
ans = 'n'
x = int(input("enter a number to loop: " ))
while(i<x):
print('\n')
print(i, end= " ")
ans = input('\ndo you want to print the next number? ')
if ans == 'y':
i += 1
else:
print('thanks')
The code is doing and extra loop and then after getting the answer terminates the loop. On top of that on the last loop if the answer is 'n' it keeps running.
You just have to add a break statement in your code, right before the print("thanks") line. That will exit the loop.
else:
break
print('thanks')
All loops will continue unless told to break or become false.
Break and continue are very important in programming. I suggest you read this https://www.tutorialspoint.com/python/python_loop_control.htm

How to break a loop with an input?

I'm new to Python, so please bear with me. I'm trying to write a program involving a function that takes a number K as an input, reads K names one at a time, stores them into a list, and then prints them.
Not sure whether or not I should use a "for" or "while" loop, so I'm trying with "while" loop first.
k = input ("How many names?\n")
def names():
lst = []
while True:
name = input("Enter name:")
if = int(k)
break
return lst
names()
What I'm hoping to see is a list of names, and that list would be cut off after K number of names.
I've been receiving this error message:
File "<ipython-input-21-24a26badc1b5>", line 7
if = int(k)
^
SyntaxError: invalid syntax
The difference between while and for loops is thus:
If you want to do something a specific number of times, or once for every element in some collection, use a for loop.
If you want to do something an indefinite number of times, until a certain condition is met, use a while loop.
The way to implement what you want using a for loop is this:
k = input("How many names?\n")
def names():
lst = []
for i in range(int(k)): # creates a list `[0, 1, 2, ..., k-1]` and iterates through it, for `k` total iterations
name = input("Enter name:")
lst.append(name)
return lst
names()
Now, you could do this using a while loop - by setting a variable like x=0 beforehand, and increasing it by one for every iteration until x == k, but that's more verbose and harder to see at a glance than a for loop is.
#Green Cloak Guy explained very well why a for loop would be appropriate for your task. However if you do want to use a while loop you could do something like this:
def get_names(num_names):
names = []
i = 1
while i <= num_names: # equivalent to `for i in range(1, num_names + 1):`
current_name = input(f"Please enter name {i}: ")
names.append(current_name)
i += 1
return names
def main():
num_names = int(input("How many names are to be entered? "))
names = get_names(num_names)
print(f"The names are: {names}")
if __name__ == '__main__':
main()
Example Usage:
How many names are to be entered? 3
Please enter name 1: Adam
Please enter name 2: Bob
Please enter name 3: Charlie
The names are: ['Adam', 'Bob', 'Charlie']
Equality comparisons in Python are done with a
==
You also need some sort of thing to compare int(k) to. If you're trying to count loops you could do something like
x = 0
while True:
name = input("Enter name:")
lst.append(name)
x+= 1
if x== int(k)
break
That's exactly what a for loop is for - looping "for" a certain number of times. A while loop is for indefinite loops where you keep looping until something is no longer true.
Still, it might be instructive to see both, so you can better understand the difference. Here's the for loop. It will loop k times. See the Python wiki for more details.
k = int(input ("How many names?\n"))
def names():
lst = []
for i in range(k):
name = input("Enter name:")
lst.append(name) # I'm assuming you want to add each name to the end of lst
return lst
names()
And here's the same thing as a while loop. The loop continues until the loop condition is not true, so you just need to come up with a conditional that is true for the first k loops, and not thereafter. This will do:
k = int(input ("How many names?\n"))
def names():
lst = []
i = 0
while i < k:
name = input("Enter name:")
lst.append(name) # I'm assuming you want to add each name to the end of lst
i += 1
return lst
names()
Notice how in a while loop you have to initialise and increment the iterator (i) yourself, which is why a for loop is more suitable.
Finally, notice how neither example uses break. break is a fine way to end a loop, but if it's not necessary then you're better off not using it - generally it is only used to end a loop by exception (that is, for some reason that is not the main loop conditional). Using it for normal loop endings leads to less logical code that is harder to follow.

Calculating an average in "Rock, Paper, Scissors"

Last night I was thinking to my self about the probability of getting the same outcome in "Rock, Paper, Scissors" 10 times in a row. I worked out how to do that and completed that task but then I wanted to challenge myself a bit, so I wanted to adapt the program so it ran the initial program a number of times (10,000) and then outputted the average result, which I hoped would be close to the probability of getting the same 10 times in a row. Please note that I am not taking into account tactics, just that both players randomly pick either r, p, or s.
def rps():
num=0 # num is the number of times i want the programme to run while roll<10:
total=0 # this should be close to 3^10 * 10000, its the result of all the tries added together
while num <10001:
tries=0 # this is how many times the programme has tried to get p1=p2
roll=0 # this is the amount of times it has counted p1=p2 (it gets re-set everytime it reaches 10)
import random
while roll <10:
p1=random.randint(1,3)
p2=random.randint(1,3)
if p1==p2:
roll=roll+1
else:
tries=tries + 1
roll=0
num=num+1
if roll==10:
total=total+roll
roll=0
if num==10000:
print (num)
print (total/num)
rps()
There are quite a few problems with the program, for once, there isn't any use for the second for loop, I get that you are using the second for loop to reset the counter if the number of consecutive rolls reaches 10, but you are already doing that here
if roll==10:
total=total+roll
roll=0
by setting roll=0, you are resetting it.
also, the last if condition adds to the complexity,
if num==10000:
print (num)
print (total/num)
instead of this, you can just print the average outside the loop like this
if roll==10:
total=total+roll
roll=0
print (total/10000) #this being outside the while loop
one more thing, you are incrementing num only when roll1 != roll2, this adds to the number of times the loop has to run
This is how the program came out after the changes
import random
def rps():
num=0 #num is the number of times i want the programme to run while roll<10:
total=0 #this should be close to 3^10 * 10000, its the result of all the tries added together
roll = 0
while num <10001:
tries=0 #this is how many times the programme has tried to get p1=p2
p1=random.randint(1,3)
p2=random.randint(1,3)
if p1==p2:
roll = roll+1
else:
tries = tries + 1
roll = 0
if roll==10:
print(roll)
total += roll
roll=0
num = num + 1
print (total/10000)
print(tries)
rps()
The answer coming out was 0,I guess it was highly unlikely that you get 10 in a row.
Some self-explanatory code (so you can also learn to write clean code):
import random
def get_10_outcomes():
return [
(random.randint(1, 3), random.randint(1, 3))
]
def have_we_got_10_in_a_row():
return (
len(set(get_10_outcomes()))
== 1
)
def how_many_10_in_a_row_in_10000():
return len(list(filter(
None,
[have_we_got_10_in_a_row() for _ in range(10000)]
)))
def get_chance_of_10_in_a_row():
return how_many_10_in_a_row_in_10000() / 10000
chance = get_chance_of_10_in_a_row()
print('{:.3%}'.format(chance))

Creating a list with inputs prompted by the user?

I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.

Categories

Resources