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")
Related
I am trying to make a simple program that uses for loops, if-elif-else statements, and input to take three "employees" salaries and compare them to see if A, any of them have the same salary. Or B if non of them have the same salary. So far, this is what I got but both strategies I've tried haven't been successful and I don't understand why :(. All help is appreciated, and spare me for I'm still new to coding and I'm trying to teach myself through these exercises. Thank you kindly!
salarylist = []
salarylist = list(map(int, salarylist))
maxLengthList = 3
while len(salarylist) < maxLengthList:
salary_of_employee = int(input("Enter your salary: "))
salarylist.append(salary_of_employee)
print("salary of employees are:\n")
print(type(salarylist))
print(salarylist)
print(type(salarylist))
x = salarylist
if salary_of_employee == salarylist[x]:
print(f"these are the same salary.{salary_of_employee} and {salarylist[x]}")
else:
print('non of the salaries are the same.')
############################################################################
empOne = salarylist[0]
empTwo = salarylist[1]
empThree = salarylist[2]
if empOne == salarylist[0]:
print("these are the same salary.")
elif empTwo == salarylist[1]:
print('these are the same salary')
elif empThree == salarylist[2]:
print('these are the same salary')
else:
print('non of the salaries are the same.')
I have tried running your code and it gives a horrible error.
I clearly understood your desire. Most of your logic don't meet it.
So I decided to RE-Code everything based upon your requirements {for loops, if, elif, else statement, 3 employees etc..}
MAX_LEN = 3
COUNTER = 1
LIST_SAL = []
while MAX_LEN >= COUNTER:
ASK_SAL = int(input('Enter your salary :'))
LIST_SAL.append(ASK_SAL)
COUNTER+=1
print(LIST_SAL)
for check in LIST_SAL:
if LIST_SAL.count(check)>1:
print('Same salaries presented in the list')
break
else:
print('Salaries of employees are unique!')
break
Okay so ..
I created a variable max_len = 3 which is the total number of employees and then I initiated the variable COUNTER to 1 so that it iterates in the while loop and gets incremented by 1 each time.
Therafter a variable named ask_sal asks the user for salaries {3 times} and appends each input to the LIST_SAL variable {a list}. And then I printed the list for visualisation.
There after I accessed the elements in the list {list_sal} by a for loop with the variable check which looks for the number of time an element repeats in the list all by the help of count() function Which, IF greater then one prints "SAME salaries presented" OR else prints "Unique salary"..
You might be wondering why have I used 2 break statements..
Well they are used to break the further iteration as the if or else condition are met in the first iteration.
If you try removing the break statements, the print function will work the number of times the same salaries occur in the list.
Hope I helped you.. I am too , a newbie in programming yet I love it and practice a lot .
Keep grinding and Working hard
When you have the list of salaries, create a set from that list and compare the length, if same length then salaries will be unique, otherwise there will be at least one common salary
lst2 = set(salarylist)
if(len(lst2) == len(salarylist)):
print("Non of the salaries are the same.")
else:
print("Same salaries found")
To find the same salaries loop through the the set and check count of elements in the list, if greater than one, then duplicate.
for sal in lst2:
if(salarylist.count(sal) > 1):
print("Duplicate here")
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.
I mostly have experience programming in visual basic, and am trying to learn python. I am trying to make a conditional loop in the form of a do until loop. I am not sure how to do it in python and i could use some help. I have a do until loop with an if statement within it. this is what i have.
number = 18
do while number = 1
if number%2==0 then
number = number/2
else number = (number*3)+1
loop
print(number)
Any help would be great. Thanks
There is no do … while loop in Python. I believe somewhere in the FAQ it explains why, and how to work around it.
But that doesn't matter because what you've written isn't a do … while loop, it's just a plain while loop. The whole point of a do … while in every language that has one is that you put the test condition after the loop body, instead of before, which guarantees that the loop will run at least once, and which allows you to avoid doing pre-loop setup that you'd have to duplicate inside the loop.
So, to translate your code to Python:
number = 18
while number == 1:
if number%2==0:
number = number/2
else:
number = (number*3)+1
print(number)
However, it's worth noting that since number = 18 before the loop, it will never be == 1 the first time through, so this is just going to skip the whole thing and print out 18.
You may have wanted while number != 1 or while number > 1, but you have to figure out what you actually want to write before anyone can write it.
There is no 'do/while' in Python. The closest is a loop that is guaranteed to loop once then get an exit test after 1 iteration.
while True: # kinda like 'do'
# do something at least once
if fail_condition(): # here is your 'while' test
break # end the loop if 'fail_condition' is True
# loop again if 'fail_condition' is not True
Roughly your code (Collatz/Hailstone?) would look like this:
number, i = 18, 0
while number>1:
i+=1
if number%2==0:
number = number/2
else:
number = (number*3)+1
print 'Reached {} after {} loops'.format(number,i)
# prints 'Reached 1 after 20 loops'
is that above code even in python? instead of do while, have it just be while. and after the if statement, dont have then. a quick reformatting would look something like this:
number = 18
while number == 18:
if number%2==0:
number = number/2
else:
number = (number*3)+1
print(number)
do while is not a usual construct in python. Simply use a while loop.
https://wiki.python.org/moin/WhileLoop
Your code could be modified as follows for instance.
number = 18
while number == 1:
if ( number % 2 ) == 0:
number = number / 2
else:
number = ( number * 3 ) + 1
print number
One of the biggest differences between these languages is that python is all about tab delimitation. You need not specify the start and end of a loop, the tabs do that for you. Additionally not the ':'s after conditional statements.
I would note however that the above code would not yield any valid answer. Perhaps you meant for the loop to run while number was not equal to 1?
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:
Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?
Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True
Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!
My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.