How to loop through a list based on a condition? - list

Here is my hypothetical situation:
There is a list of people waiting outside of the club. The bouncer only allows people with ids 18 or older in the club. If they are younger than 18 they are denied admission. Suppose you know the ages of people in line that want to enter they are 18, 27, 16, 17. I created a code to try to run through it, but just cannot get it to work. It works for testing all the items 0 to 99, but I only want it to test items in the list. Can someone help me?
ages_of_people_waiting_outside_club = [18,27,16,17]
ages_of_people_waiting_outside_club = range(0,100)
for ids in range(0,100):
if ids >= 18:
print("you may enter")
else:
print("sorry, you can not come in")

In this instance, I would recommend using a foreach loop then nest in an if and else statement. The foreach loop will go through the whole list, then you can basically add in the if and else statements you showed above. Here would be an example using PHP:
foreach($age_of_people_waiting as $age) {
if($age >= 18){
print("you may enter");
}else{
print("sorry, you can not come in");
}
}
What this is doing is the array that contains the ages, in this case, $age_of_people_waiting, is being converted to an individual value for each section in the array, that value will be passed as $age. The if statement will then check if that particular $age value that it is on is 18 or over. If it is, it prints "you may enter" if not, it prints "sorry, you can not come in." I'm not sure what coding language you are using, but foreach loops are pretty common and exist in multiple languages, so it's your best bet.

That should work:
ages_of_people_waiting_outside_club = [18,27,16,17]
#ages_of_people_waiting_outside_club = range(0,100)
for ids in ages_of_people_waiting_outside_club:
if ids >= 18:
print("you may enter")
else:
print("sorry, you can not come in")

Related

Using for loop within if statements in Python

I am really having a hard time with loop statements for python, please see below:
I want it to check the users age, so if they are over 18, it will say "old enough, if they are over 16, it will say "almost there" and if they are younger than this, it will say "sorry you're too young"
I got the following code below:
age = int(raw_input("Enter your age:"))
if age >= 18:
print "You are old enough!"
elif age >= 16:
print "Almost there"
else:
print "You're just too young"
my problem is, how do I write code the includes an if statement and a for loop that will print out all the numbers from 0 that are less than the user's inputted age?
do I say:
for age in range (0,num)
if num <= age
print ....
else:
print...
Please kindly help. I'm new at this and still learning :(
So you could construct a variable that contains a list of numbers that is smaller than the user's age. You can construct this using python's range function; something like range(age) would do this nicely.
Then you need to use a for loop to loop through all these numbers and print them to the command line. Something like for x in range(age) would be a good place to start.
Then, in the loop, you'd just need to turn x from an integer into a string using the str() function, and print it to the command line.
So as pseudo-code:
if the age is greater than 18:
print that they're old enough
else if the age is greater than 16:
print that they're nearly old enough
otherwise:
print that they're not old enough.
for each number between 0 and age:
print the number
Come back when you have some code and we can help you with any trouble you have.

Python - values only being used if they are after the initial in a list

I'm trying to make a program that finds likely friends by finding similarities in user scores in different topics:
def similarity(user,d_list):
user_data=()
user_score=[]
for item in d_list:
if user in item:
user_data=item[1]
if item[0]!=user :
local_score=0
local_score=sum(a*b for a,b in zip(user_data,item[1]))
user_score.append(local_score)
print user_score
return
When using:
ratings=(("mark",[4,8,0,7]),("bob",[3,6,9,1]),("jim",[11,4,6,3]),("steve",[22,19,1,0]))
As the d_list and "mark" as the user, the program works as expected, giving:
[67, 97, 240]
When bob is used, the comparison with mark is set to 0.
[0, 114, 189]
When steve is used the set is just zeros. I'm at a loss.
Got it. The calculation was still nested inside the first iteration through d_list.
def similarity(user,d_list):
user_data=()
user_score=[]
for item in d_list:
if user in item:
user_data=item[1]
for item in d_list:
if item[0]!=user :
local_score=0
local_score=sum(a*b for a,b in zip(user_data,item[1]))
user_score.append(local_score)
print user_score
return

How to create multiple loops in python

I'm trying to create a basic maths program which will randomly generate a numerical question and then allows 3 attempts to complete it before it moves onto the next question however cant figure out how to make it do both together.
My code currently looks like this
print "What is your name?"
score = 0
Attempt = 0
loop = True
Name = raw_input()
import random
for i in range (1,6):
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
print "What is", question_1_part_1, "+", question_1_part_2, "?"
while Attempt <3: # inputing this while loop here means it will retry the same question.
Guess = raw_input()
Guess = int(Guess)
answer = question_1_part_1 + question_1_part_2
if Guess == answer:
print "Well done"
score = score + 1
else: print "try again"
Attempt = Attempt + 1
if Attempt == 3: print "You failed"
print Name, "your score is", score
A simple break statement will take you out of the loop when the answer is correct.
if Guess == answer:
print "Well done"
score += 1
break
else: print "try again"
Note the change to your assignment; this is considered a cleaner increment.
To answer your comment ... you don't use this when the person gets the question wrong. Your program logic freezes out the user after three wrong guesses total, on all questions. If you want them to have up to three guesses on every problem, then you have to reset the Attempt counter for every question. Pull that line into the outer loop:
for i in range (1,6):
Attempt = 0
loop = True
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
In the future, I strongly recommend that you program incrementally: get a few lines working before you add more. Insert tracing print statements to check that the values and program flow are correct. Don't remove them until that part of the code is solid -- and even then only comment them out until the entire program is working. Some of your problems stem from trying to write more than you can comfortably hold in your mind at once -- which is common at most levels of programming. :-)
Add another argument to your while loop.
while Attempt <3 and Guess != ... :
rest of loop code
Then you are exiting your loop when they get the correct answer. Or you could break from the statement when they get the answer right.

Unknown syntax error involving greater than value

I do not know why there is a syntax error, this is so simple but keeps coming up wrong.
number = float(input("How much shall you be spending today?")
if number>10
print("You get 20% off")
else
print("You get 10% off ")
Your if/else statement is indented, and shouldn't be. Additionally, you need : after the if/else statements, and a second ) on the first line. Finally, you should be using raw_input() with Python 2.7. Your code block should look like this:
number = float(raw_input("How much shall you be spending today? "))
if number > 10:
print("You get 20% off")
else:
print("You get 10% off")
In your first line, you said 'input' but the correct function was raw_input. Also, the indentation for your if statement is wrong which can cause problems.

Python input, ifstatement, return

I have to create a function that takes an input, and returns a corresponding Grade.
So for example if the user inputs A+ output is 90%
or
if the input is A output is 80%
or
if the input is B output is 70%
I have some sort of Idea on how to do this... but I am having trouble on wrapping my head around on how I can return the statement??
def percent (percentage):
if ( percentage )== A+
return ("90%")
elif (percentage)== A
return ("80%")
Is this the correct way of going about it?
OK, so first, welcome to Python. Second, this is Pythonic way of doing this - define a dict:
grades = {'A+': "90%", 'A': "80%", ...}
then
return grades[precentage]
will do the job.
You need to protect against the case where the grade is not in the dict, for example, if the user entered some mistake, like G. There are a few ways to go about that:
A simple if:
if precentage in grades:
return grades[precentage]
else:
return "bad precentage"
After you get used to Python you will be more aesthetic about your code and will want to do better than state twice bote grades and precentage, so you can do simply:
return grades.get(precentage, "bad precentage")
Or using a special dict with default values:
import collections
grades = collections.defaultdict(lambda: "bad precentage", [("A+", "90%"), ("A", "80%")])
then
grades[precentage]
will automatically return "bad precentage" upon bad input.
#user2829744 You don't want to have to repeatedly call if statements based on what the percentage is, that would make the code unnecessarily long.
Instead, you want to have a list or tuple (a variable which stores multiple elements) that the program can compare the user's inputted value to, and then calculate the percentage mark.
Take this for example:
def percentage(per):
grades=["A+","A","B","C","D","E","F"]
percentage=("90%","80%","70%","60%","50%","40%","30%")
for i in range(7):
if per.upper()==grades[i]:
return percentage[i]
d="a"
print(percentage(d))
What happens is that i counts up to the number seven, and if the value of i in grades (let's say i is 5, then that would be grades[5] which would be an "E") then the function returns the value of i in the percentage tuple. In my case, the interpreter outputs 80%
Logically, your way of going about it (by actually dealing with every grade possible in separate if statements) would work too, however like I said your code would be longer and chances are you'd make a few typos along the way that you'd have to edit. Of course, my code has a few problems too, like what if the user enters a grade which I don't have in the tuple. This is easily fixable though as you would just need to tell the interpreter what to do if that happens.
A bit brief I know, but I hope this helps
You could do something like this
user_input = int(input("percentage: ")
if user_input < 0 and user_input > 10:
print('F")
And then you can just duplicate the code and change the numbers and the return grade
Hope it helps :)