Number average for nobody - if-statement

I cant execute the break when i put in 999 it just keeps asking for more scores somone help
score = 0
total_score = 0
while True:
scores = float(input("Enter test score: ")
if score in range (0,100):
total_score = score + total_score
score = score + 1
elif score = 999:
break
else:
print("Test score must be from 0 through 100")
average_score = total_score / score
print("Total score", total_score )
print("Average Score", average_score)

As #Peter mentioned, using score and scores is confusing. It is better to use a variable like cnt to keep score count. Note that range(0,100) only goes to 99. Use range(0,101) to include 100. You also have some syntax errors causing issues.
Try this code:
total_score = 0 # sum of scores
cnt = 0 # score count
while True:
score = int(input("Enter test score (0-100): "))
if score in range (0,101): # 0-100
total_score += score
cnt += 1
elif score == 999:
break
else:
print("Test score must be from 0 through 100")
average_score = total_score / cnt
print("Score count", cnt )
print("Total score", total_score )
print("Average Score", average_score)
Output
Enter test score (0-100): 20
Enter test score (0-100): 30
Enter test score (0-100): 40
Enter test score (0-100): 50
Enter test score (0-100): 60
Enter test score (0-100): 999
Score count 5
Total score 200
Average Score 40.0

Related

Why is the average not calculating correctly, and why does the average letter grade remain F no matter the number?

This is my code for the program that calculates 5 user inputs of test scores, displays the letter grade, and then calculates the average score and letter grade. However, the grade comes back as the wrong average, and the letter grade stays F no matter the number.
import os
#constants
PROG_ID = "\nFilename: Average_Grade.py\n"\
"Homework: 09\n"\
"Source Code Author: \n"\
"Reference: Chapter 5\n"\
"Date: 9 April 2022\n"
USER_PROMPT = "Please enter a test score. "
GRADE_TAG = "The letter grade is "
OUTPUT_TAG = "The average grade is "
#display program id
def progId ():
print(PROG_ID)
print()
#prompt user
def getInput(testScore, gradeList):
for item in range (5):
testScore = int(input(USER_PROMPT))
gradeList.append(testScore)
determineGrade(testScore)
print()
#letter grade
def determineGrade(testScore):
if testScore >= 90: print (GRADE_TAG, "A")
elif testScore >= 80: print (GRADE_TAG, "B")
elif testScore >= 70: print (GRADE_TAG, "C")
elif testScore >= 60: print (GRADE_TAG, "D")
else: print (GRADE_TAG, "F")
#show average
def calculateAverage(testScore, gradeList):
avg = sum(gradeList)/len(gradeList)
print(OUTPUT_TAG, format(avg, ".0f"))
avg = testScore
determineGrade(testScore)
def housekeeping():
input ("Press enter to exit.")
os._exit(1)
#control
def main():
#variables
testScore = avg = 0
gradeList = [testScore]
#calls
progId()
getInput(testScore, gradeList)
calculateAverage(testScore, gradeList)
main()
housekeeping()
If for some reason your main does not get called before the rest your gradeList is never initialised and calling methods on it would do nothing? I would initialise the array at the beginning of the file. You should test if at any point your array does not only contain 0, or nothing at all with a console.log().

how to get total number of earnings using Thinkscript?

I want to count the total number of earnings on the chart. if this is 1 year daily chart, I should get 4 earnings back. no error message,but label is not showing on the chart.
def earningCount = if IsNaN(earningCount) then 0 else if hasEarnings() then earningCount + 1 else earningCount;
AddLabel(yes, "There are total " + earningCount + " earnings");
What you have to do is start with the first day and iterate through each previous day asking hasEarnings(). Unfortunately, without any for/while loop functionality in thinkscript, this will be extremely tedious:
def earningCount;
#get latest date
def today = getYYYYMmDd();
#get first date in chart
def firstDay = first(today);
#get number of days to iterate through:
def numOfDays = CountTradingDays(firstDay,today);
#Ask for each day one at a time: if hasEarnings() then earningCount + 1 else Double.NaN;
#today
today
#day before
today[1]
#day before that... etc..
today[2]
#... until first day in chart
today[numOfDays]
Not the optimal solution you would have wanted. Alternatively, you could ask how many years in the chart and multiple by 4 as you know there are usually 4 earnings/yr...
def earningCount = if IsNaN(earningCount[1]) then 0 else if hasEarnings() then earningCount[1] + 1 else earningCount[1];
AddLabel(yes, "There are total " + earningCount + " earnings");

This code is saying Invalid Syntax, and pointing out at my "guessNum" variable. What is wrong?

from random import randint
myNumber = randint(1000,9999)
guessNum = 0
correctNumbers = 0
Input = False
Userguess = 0
print ("Welcome to Guess The Number")
print ("try to guess my number between 1000 and 9999")
while Input == False:
Userguess = int(raw_input("Guess a number betweeb 1000 and 9999: ")
guessNum += 1
if Userguess == myNumber:
print("Well Done, you guessed the number in" + str(NumberGuesses) + "guesses")
Input = True
The program is a guess the number game where the user has to guess a randomly generated number between 1000 and 9999.
Missing bracket at line no 13.
Userguess = int(raw_input("Guess a number betweeb 1000 and 9999: "))

Python Salary Program Using Conditionals

I get an error # line 19, the Bonus function and I can't figure out why. I'll probably get an error for the other functions too. I've checked my spaces, my numbers vs. my strings, and my DOM. My first problem were about my globals and I fixed it from global comrate to `comrate = 0; . I've got debugging blindness. Thank you guys in advance!
def main():
#Welcome user and get sales number
print("Welcome to the Bonus Qualification Calculator! Please honestly answer the following questions:")
name = str(input("What is your name? "))
sales = float(input("What is your sales total? "))
jobtime = float(input("How many months have you been with the company? "))
vacationtime = float(input("How many vacation days have you taken? "))
#Define Global Vars
comrate = 0;
compedsalary = 0;
bonussalary = 0;
finalsalary = 0;
#Begin calculations
Bonus(sales, jobtime)
vacation(vacationtime)
print(str(name) + ", your salary based on the information you provided is " + str(format(finalsalary,'.2f'))
def Bonus(sales,jobtime):
#Calcultate commission
if sales < 10000:
comrate = 0
elif sales > 10000 and sales <= 1000000:
comrate = .02
elif sales >= 100001 and sales <= 500000:
comrate = .15
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 1000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
elif sales >= 500001 and sales <= 1000000:
comrate = .28
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 5000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
elif sales > 1000000:
comrate = .35
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 100000)
elif jobtime > 60:
bonussalary = float(compedsalary + 101000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
def vacation(finalsalary):
if vacation > 3:
finalsalary = float(bonussalary - 200)
else:
finalsalary = bonussalary
main()
You're using full quotes where you should be using apostrophes. You're using contractions in your print statements, which confuses Python. Just put "do not" instead of "don't" in your print statements.

inserting a while loops into a for loop

I want to apply this while loop into the for loop below.
I have tried putting the while loop before the if statements, in each if statement.
When i put it before the if statement( in the for loop ) it asks the user once and then returns the same input for the whole range (1,8).
I want this while loop to apply to each question, the seven items 2 to 8
how do i implement it. can anyone help please, Thanks
def valid_entry ():
price = 110
invalid_input = 1
while price< 0 or price> 100:
if invalid_input >=2:
print "This is an invalid entry"
print "Please enter a number between 0 and 100"
try:
price= int(raw_input("Please enter your price : "))
except ValueError:
price = -1
invalid_input +=1
End of the while loop
def prices ():
x = range (1,8)
item=2
price=0
for item in x:
item +=1
print "\n\t\titem",item
price = int(raw_input("Enter your price : "))
if price <10:
price=1
print "This is ok"
if price >9 and price <45:
price +=5
print "This is great"
if price >44 and price <70:
price +=15
print "This is really great"
if price >69:
price +=40
print "This is more than i expected"
print "\nYou now have spent a total of ",price
prices ()
Is the lack of responses a sign that its a stupid question or is it not possible to do?
does this make it any clearer ?
def prices ():
x = range (1,8)
item=2
price=0
for item in x:
item +=1
print "\n\t\titem",item
valid_entry ()#should it go here
price = int(raw_input("Enter your price : "))
valid_entry ()#should it go here
if price <10:
valid_entry ()#should it go here and so on for the following 3 if conditions
price=1
print "This is ok"
if price >9 and price <45:
price +=5
print "This is great"
if price >44 and price <70:
price +=15
print "This is really great"
if price >69:
price +=40
print "This is more than i expected"
print "\nYou now have spent a total of ",price
You could try something like this (apologies if this isn't what you were looking for). Happy to explain anything that doesn't make sense - overall idea is that it loops through a range of 8 items, asking for a valid price each time and continuing to ask if the entered value is either not a number or not in the specified range. As this may be for an assignment, I tried to keep it as closely aligned to the concepts you already demonstrated that you knew (the only exception here may be continue):
def valid_entry():
# Here we define a number of attempts (which is what I think
# you were doing with invalid_input). If the person enters 10
# invalid attempts, the return value is None. We then check to
# see if the value we get back from our function is None, and if
# not, proceed as expected.
num_attempts = 0
while num_attempts < 10:
# Here we do the input piece. Note that if we hit a ValueError,
# the 'continue' statement skips the rest of the code and goes
# back to the beginning of the while loop, which will prompt
# again for the price.
try:
price = int(raw_input("Enter your price : "))
except ValueError:
print 'Please enter a number.'
num_attempts += 1
continue
# Now check the price, and if it isn't in our range, increment
# our attempts and go back to the beginning of the loop.
if price < 0 or price > 100:
print "This is an invalid entry"
print "Please enter a number between 0 and 100"
num_attempts += 1
else:
# If we get here, we know that the price is both a number
# and within our target range. Therefore we can safely return
# this number.
return price
# If we get here, we have exhausted our number of attempts and we will
# therefore return 'None' (and alert the user this is happening).
print 'Too many invalid attempts. Moving to the next item.'
return None
def prices():
# Here we go from 1-8 (since the upper bound is not included when
# using range).
x = range(1,9)
# Here we use a variable (total) to store our running total, which will
# then be presented at the end.
total = 0
# Now we iterate through our range.
for item in x:
print "\n\t\titem",item
# Here is the important part - we call our valid_entry function and
# store the result in the 'price' variable. If the price is not
# None (which as we saw is the return value if the number of attempts
# is > 10), we proceed as usual.
price = valid_entry()
if price is not None:
if price <10:
# Note this should probably be += 1
total += 1
print "This is ok"
elif price >= 10 and price < 45:
total += 5
print "This is great"
elif price >= 45 and price < 70:
total += 15
print "This is really great"
# We know that price >= 70 here
else:
total += 40
print "This is more than i expected"
# Now print out the total amount spent
print "\nYou now have spent a total of ", total
prices()