If loop stops after only one iteration without condition being met - loops

I don't understand why this code is not iterating properly?
income = 0
expenses = 10
profit = income - expenses
if profit <= 0:
income += 1
print(profit)
I would expect it to increment the income by one until 10, however it only runs once, outputting:
-10
Sincere thanks for answering something at the very, very bottom of the food chain.

You can use while loop as follows:
income = 0
expenses = 10
profit = income - expenses
while (profit <= 0):
income += 1
profit = income - expenses
print(income)

You print the difference profit which is indeed -10. Add a loop (while, for) to imcrement, if you have to, and then print income outside the loop.

Hi IF statement won't loop. It will execute the statements under it when the condition is satisfied.
Use While where it loops until the condition is satisfied.

Related

Average of a player

I have a record that contains stat for a certain cricket player.
It has columns having dates, oppositions, Runs, Balls, Dismissals, Match_Number.
I want to do a query (SQL SERVER) to find out the batting average where every runs (Sum) is to be added; innings having a count of all innings except DNB but dismissal should not have a count of "Not Out", "Retired Hurt", "DNB" grouped by the opposition.
Note : DNB means Did not Bat.
The query doesn't have the required number of innings to calculate the average
So the problem is can't gather information for a single entity (count of no. of innings) having two set of parameters.
Without DNB
Without DNB, Not Out, Retired Hurt.
Please suggest.
You can put a case expression within an aggregate to exclude certain rows from a count/sum/average etc. So you could use something like this:
SELECT a.Opposition,
Matches = COUNT(*),
Innings = COUNT(CASE WHEN a.Dismissal <> 'DNB' THEN 1 END),
Runs = SUM(a.Runs),
Average = SUM(a.Runs) / NULLIF(COUNT(CASE WHEN a.Dismissal NOT IN ('DNB', 'Not Out', 'Retired not out') THEN 1 END), 0)
FROM dbo.SRTundlkarODI AS a
GROUP BY a.Opposition;
N.B. I have wrapped the COUNT for the average in NULLIF(<exp>, 0) so that should the batsmen have never got out you avoid a divide by zero error.

Python loop to print salaries within range of the average

I'm an absolute beginner to Python and am tasked with creating a program that does a few things:
Inputs employee names into a list.
Inputs that employee's salary after inputting their name.
Totals the salaries in a list, (2 lists: names[] and salaries[]).
Finds the average salary after totaling.
Prints employees that earn within $5,000 of the average salary (Where I'm stuck).
Please see my code below:
# function to total the salaries entered into the "newSalary" variable and "salaries[]".
def totalSalaries(salaries):
total = 0
for i in salaries:
total += i
return total
# Finds the average salary after adding and dividing salaries in "salaries[]".
def averageSalaries(salaries):
l = len(salaries)
t = totalSalaries(salaries)
ave = t / l
return ave
# Start main
def main():
# Empty names list for "name" variable.
names = []
# Empty salaries list for "salary" and "newSalary" variables.
salaries = []
# Starts the loop to input names and salaries.
done = False
while not done:
name = input("Please enter the employee name or * to finish: ")
salary = float(input("Please enter the salary in thousands for " + name + ": "))
# Try/except to catch exceptions if a float isn't entered.
# The float entered then gets converted to thousands if it is a float.
try:
s = float(salary)
# Message to user if a float isn't entered.
except:
print("Please enter a valid float number.")
done = False
newSalary = salary * 1000
# Break in the loop, use * to finish inputting Names and Salaries.
if name == "*":
done = True
# Appends the names into name[] and salaries into salaries[] if * isn't entered.
# Restarts loop afterwards if * is not entered.
else:
names.append(name)
salaries.append(newSalary)
# STUCK HERE. Need to output Names + their salaries if it's $5,000 +- the total average salary.
for i in range(len(salaries)):
if newSalary is 5000 > ave < 5000:
print(name + ", " + str(newSalary))
# Quick prints just to check my numbers after finishing with *.
print(totalSalaries(salaries))
print(averageSalaries(salaries))
main()
Any info is greatly appreciated. I hope the rest of the functions and logic in this program makes sense.
Your haven't written your iterator correctly. With an array, you can just use for element in array: and the loop will iterate over array by putting each element in element. So your for loop becomes for salary in salaries.
Also, You need to split your condition in two and use additions and substractions. Your code should check if the salary is higher or equal to the average minus 5000 and if it is lower or equal to the average plus 5000. If you want to formalize this mathematically it would be:
Salary >= Average - 5000
and
Salary <= Average + 5000
So the condition at line becomes if salary >= (average - 5000) and salary <= (average + 5000)
Finally, you do not call averageSalaries before entering the loop, so the average salary haven't been computed yet. You should call the function and put the result in a variable before your for loop.

Stata year-quarter for loop

I am trying to create a loop in Stata. I run a model for the data <= year and <= quarter. Then predict one year look ahead. That is the model is run all time points upto the loop, while the prediction happens in the next quarter out of sample. So my question is how do I handle so that when yridx = 2000, and qtr = 4, the next quarter inside the loop look ahead would be year = 2005, and year = 1.
foreach yridx of numlist 2000/2012 {
forvalues qtridx = 1/4 {
regress Y X if year <= yridx and qtr <= qtridx
predict
}
}
It sounds as if it would be much easier to work in terms of quarterly dates. Here is one of several ways to do it.
gen qdate = yq(year, qtridx)
forval m = `=yq(2000,1)'/`=yq(2012, 4)' {
regress Y X if qdate <= `m'
predict <whatever>
}

Need help determining the lowest and highest value within an algorithm using pseudocode

I'm having a lot of trouble dealing with with a particular question in my critical thinking class.
The task is this:
Task
Develop an algorithm to prompt for and obtain maximum daily temperatures for a whole year. However, in order to consider leap years, your algorithm should first prompt the user for the number of days in this particular year. That is, your algorithm should expect 365 or 366 as the first input number followed by input temperature values.
In addition, for this particular year, your algorithm must also determine and display the average, maximum, and minimum of these temperatures values.
Here's an example of what needs to happen:
Prompt for number of days in a year
(let's say they enter 365)
Then prompt user for MAXIMUM daily tempretures for 365 days.
Take those 365 (individual) maximum tempretures, find the lowest value that will = Min_temp.
Take those 365 (individual) maximum tempretures, find the highest value that will = Max_temp.
Sum up all 365 invidual max tempretures and divide it by the number of days in the year (365) = Avg_temp.
Print Min_temp
Print Max_temp
Print Avg_temp
So far this is what I have:
1. Prompt operator to enter Number_Of_Days within year.
2. WHILE Number_Of_Days = 365 or 366 THEN
3. IF Number_Of_Days is = 365 THEN
4. Year = 365
5. ELSEIF Number_Of_Days = 366 THEN
6. Year = 366
7. ENDIF
8. ELSEWHILE Number_of_Days is NOT = 365 or 366 THEN
9. Print ‘ERROR: Please enter a number that is 365 or 366.’
10. Prompt operator to enter Number_Of_Days within year.
11. ENDWHILE
12. DOWHILE MaxDayTemp = 1 to Year
16. Prompt operator for MaxDailyTemp
15. ENDO
From here we're meant to get an average of all the maximum temps provided by the user, that's easily done by AVG_TEMP = Sum of Temps / Days in the year.
What I can't work out is how to take the values of each day and find the lowest and highest values that are provided.
I've been trying to work it out with an array but I'm totally confused by it.
Please help! :(
I think you are expecting something like this, tried to use your conversion. Format it as you want.
i=0;
tempsum=0;
tempmax=0;
tempmin=100;
currenttemp=0;
no_days=0;
// variables used to store values
do
(prompt user for number of days)
no_days = user input
while no_days!=365 or no_days!=366 // will loop until user enter 365 or 366
while i<no_days
do
(Prompt operator for MaxDailyTemp)
currenttemp = userinput
while (currenttemp value is invalid) // thinking in the same way as above
if currenttemp > tempmax
tempmax = currenttemp
else if currenttemp < tempmin
tempmin = currenttemp
tempsum = tempsum + currenttemp
i = i+1
end
display average temp. = tempsum/no_days
display max temp. = tempmax
display min temp. = tempmin
I don't know what syntax is required for your class but this
max = (1 st value)
min = (1 st value)
i = 2
WHILE i < year THEN
IF (i th value) > max THEN
max = (i th value)
ELSIF (i th value) < min THEN
min = (i th value)
i = i + 1
would get the min and max value.

Create Loop So Whole Task Repeats

import sgenrand
# program greeting
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
#print("Enter coins that add up to 81 cents, one per line.")
total = 0
#prompt the user to start entering coin values that add up to 81
while True:
final_coin= sgenrand.randint(1,99)
print ("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
total = total + user_input
while total != final_coin:
user_input = int(input("Enter next coin:"))
total = total + user_input
if user_input == input(" "):
break
if total > final_coin:
print("Sorry - total amount exceeds", (final_coin))
if total < final_coin:
print("Sorry - you only entered",(total))
if total== final_coin:
print("correct")
goagain= input("Try again (y/n)?:")
if goagain == "y":
if goagain == "n":
print("Thanks for playing ... goodbye!" )
I've been trying to create this loop, so it can repeat the whole program at the end when the user accepts/ if he accepts to do it again at the end.
I know you have to have a while statement around your whole program, but with my while true statement at the top, it only repeats the first part of my program and not the whole thing.
Well one thing you should be careful of is that you do not set the
total = 0
at the start of each loop. So when the user plays the game again. He will continue using his previous total. You should move total = 0 to the start of the loop
while True:
total = 0
Additionally, you need to deindent you first
while True
statement as it does not align properly with the rest of your code.
Finally, you need to allow the user to exit the while loop after he selects No for trying again.
if goagain == "n":
print("Thanks for playing ... goodbye!" )
break
This can be done by applying a break statement.

Resources