Can't figure out this For loop in Python - python

I'm trying to get this For loop to repeat itself for an amount equal to "totalNumStudents"
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
However, the code never gets to this loop and restarts from the beginning.
Here is the first half of the code including the loop.
freshman = 0
sophomore = 0
junior = 0
senior = 0
test_score = 0
totalTestScores = 0
totalNumStudents = freshman + sophomore + junior + senior
# Start a while loop.
while True:
# Display the menu of choices.
print("\nPress '1' to enter a student")
print("Press '2' to quit the program")
print("NOTE: Pressing 2 will calculate your inputs.\n")
# Prompt to enter a choice.
choice = input("Enter your choice: ")
# If the choice is 1.
if choice == '1':
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
# Otherwise, display an error message.
else:
print("Invalid test score! Test score " +
"must be between 0 and 100.")
# Calculate total test scores
totalTestScores = totalTestScores + test_score
What am I missing here?

Since you add up before get those numbers, your totalNumStudents is all always zero. You should put the add up statement after you get the numbers:
...
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
# add up here
totalNumStudents = freshman + sophomore + junior + senior
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
...
BTW since your while True loop only runs once, you don't need the loop. Just remove it.

Related

Program exits too early

My code is working properly the only thing I want to change in my program is after congratulations message the program should ask user again to input a number until user input zero as quit.
Til now if I run my code after congratulations message program exits.
import random
import datetime
e = datetime.datetime.now()
print(e.strftime("%B %d,%Y # %H:%M:%S"))
number = random.randint(1, 100)
print(number)
name = input("\nEnter your name: ")
def main():
print(f"Hi, {name}, Welcome to the Guessing Number Game ")
x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
if x == 0:
print("You quit? Goodbye!")
else:
playGuessingGame(x)
def playGuessingGame(x):
times = 1
while number != x:
times += 1
if x < number:
print("Too low, try again")
x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
elif x > number:
print("Too high, try again")
x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
print(f"Congratulations {name}!, you guessed the right number with {times} tries!")
main()
After congratulations message the program should ask user again to input a number until user input zero as quit.
since you have not added break inside while loop in playGuessingGame(). so program continuously asking to enter number even though you have entered zero
def playGuessingGame(x):
times = 1
while number != x:
times += 1
if x < number:
print("Too low, try again")
x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
break #since this was missing, program doesn't break the while loop
elif x > number:
print("Too high, try again")
x = int(input("Enter a number between 1 and 100, or 0 to quit: "))
break #since this was missing, program doesn't break the while loop

Python if elif and loops

I wrote this for my beginner class and I don't know how to get the NAME of the SECOND STUDENT with the 2nd highest score. After testing it, I believe the code works for the first student.
I think what I need is to store the highest score in to variable high_score and then the next highest in to second_score and then compare the third score to both the highest and second score. But I am confused on how to get the name of the second highest scoring student.
num_students = int(input("enter number of students: "))
high_score = 0
high_name = ""
second_name = ""
second_score = 0
for i in range(1,num_students + 1):
if num_students < 2:
break
if num_students >= 2:
name = input("enter student name: ")
score = int(input("enter student score: "))
if score > second_score:
if score > high_score:
second_score = high_score
high_score = score
high_name = name
elif score < high_score:
second_score = score
second_name = name
print()
print("Top Two Students")
print()
print(high_name,"'s score is", high_score)
print(second_name,"'s score is", second_score)
In addition to Gary02127's solution, I'd like to point out a few other improvements:
You should move if num_students < 2 outside of your loop. It would be enough to check the condition once after the user inputted the number of students.
You could also write for i in range(num_students). It doesn't matter if the range starts with 0 or 1 since you are not using i.
Also, if you are not using a variable, you could use _ (throwaway variable) instead. See more about for _ in range(num_students) here: What is the purpose of the single underscore "_" variable in Python?.
Instead of:
if score > second_score:
if score > high_score:
# ...
else:
# ...
You could also write:
if high_score < score:
# ...
elif second_score < score:
# ...
Here is a verbose solution considering suggested improvements:
num_students = int(input("Enter number of students: "))
if num_students < 2:
exit()
highest_name = None
highest_grade = 0
second_highest_name = None
second_highest_grade = 0
for _ in range(num_students):
name = input("Enter student's name: ")
grade = int(input("Enter student's score: "))
if highest_grade < grade:
second_highest_name = highest_name
second_highest_grade = highest_grade
highest_name = name
highest_grade = grade
elif second_highest_grade < grade:
second_highest_name = name
second_highest_grade = grade
print(highest_name, highest_grade) # highest grade
print(second_highest_name, second_highest_grade) # second highest grade
You could also use a list and sorted() (built-in function):
from operator import itemgetter
num_students = int(input("Enter number of students: "))
if num_students < 2:
exit()
grades = []
for _ in range(num_students):
name = input("Enter student's name: ")
grade = int(input("Enter student's score: "))
grades.append((name, grade))
grades = sorted(grades, key=itemgetter(1), reverse=True)
print(grades[0]) # highest grade
print(grades[1]) # second highest grade
You could also use a specialized list such as SortedList (requires external package):
from sortedcontainers import SortedList
num_students = int(input("Enter number of students: "))
if num_students < 2:
exit()
grades = SortedList(key=lambda record: -record[1])
for _ in range(num_students):
name = input("Enter student's name: ")
grade = int(input("Enter student's score: "))
grades.add((name, grade))
print(grades[0]) # highest grade
print(grades[1]) # second highest grade
Notes:
Difference between sorted() and str.sort(). sorted() creates a new sorted list whereas str.sort() modifies the current list.
itemgetter(1) is equals to lambda record: record[1].
You can install SortedList with: pip install sortedcontainers.
Here's a solution based on my previous comments to your original post.
num_students = int(input("enter number of students: "))
high_score = 0
high_name = ""
second_name = ""
second_score = 0
for i in range(1,num_students + 1):
if num_students < 2:
break
# if num_students >= 2: # don't need this "if" after previous "break"
name = input("enter student name: ")
score = int(input("enter student score: "))
if score > second_score:
if score > high_score:
second_score = high_score
second_name = high_name # NEW
high_score = score
high_name = name
else: # simplified to just a plain "else:"
second_score = score
second_name = name
print()
print("Top Two Students")
print()
print(high_name,"'s score is", high_score)
print(second_name,"'s score is", second_score)
Notice that simplifying that last "elif ...:" to a simple "else:" also solves a simple bug where entering the current high score again can be ignored and not captured. If you were to run your code as is and use input values "100 80 100", you would find the 2nd high score set to 80 instead of 100.
You can simply store the details in a list. And use list.sort() to sort the values according to the score.
Here is the working code:
num_students = int(input("Enter number of students: "))
scores = []
if num_students < 2:
print('Number of students less than 2')
exit()
for i in range(num_students):
name = input("Enter student's name: ")
score = int(input("Enter student's score: "))
scores.append([name, score])
scores.sort(key=lambda details: details[1], reverse=True)
print("Top Two Students")
print()
print(f"{scores[0][0]}'s score is {scores[0][1]}")
print(f"{scores[1][0]}'s score is {scores[1][1]}")

Validate the score in python

array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
Change the if statement:
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(input("Invalid score, please re-enter: "))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
Here, the score at the same time can't be less than 0 and greater than 100. So as you want to break of the score is between 0 and 100, we use 0 <= score <= 100 as the breaking condition.
Also the loops were reversed, since you won't get what you expected to.
try this one:
array = []
total = 0
num_of_students = int(input("How many students in your class: "))
print("\n")
for x in range(num_of_students):
score = int(input("Input score {} : ".format(x + 1)))
while True:
if score < 0 or score > 100:
score = int(input("Invalid score, please re-enter: "))
else:
array.append(score)
break
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/num_of_students))
I renamed some of your variables. You should always try to using self explanatory variable names. I am also using string interpolation (should be possible for Python +3.6) and comparison chaining.
score_list = []
total = 0
number_of_students = int(input("How many students in your class: "))
print("\n")
for student in range(number_of_students):
score_invalid = True
while score_invalid:
score_student = int(input(f"Input score {student + 1} : "))
if (0 <= score_student <= 100):
score_invalid = False
else:
score_invalid = True
if score_invalid:
print("Invalid score!\n")
score_list.append(score_student)
print("\n")
print(f"Maximum: {max(score_list)}")
print(f"Minimum: {min(score_list)}")
print(f"Average: {sum(score_list) / number_of_students}")
You could try something like this:
score = -1
first_time = True
while type(score) != int or score <= 0 or score >= 101 :
if first_time:
score = int(input("Input score: "))
first_time = False
else:
score = int(input("Invalid score, please re-enter: "))
array.append(score)

Adding a running subtotal to a created food menu

I have made a program that adds up the orders of a fast food menu. I need to add a running subtotal after I have made an order. As I am a python novice, I am not quite sure what to do. I also need to make sure my order dictionary is modified, but am unsure how to do so.
I thought about making a loop with a range to keep the total but I do not want a range as I want the program to be able to take as many orders as possible.
# menu and order options
menu = {"burger":5.00, "fries":3.50, "drink":1.00}
order = {"burger":0, "fries":0, "drink":0}
bcount = 0
fcount = 0
dcount = 0
while True:
print("Please make a selection:")
print("1. Burger = $5.00")
print("2. Fries = $3.50")
print("3. Drink = $1.00")
print("4. Quit")
choice = int(input('Please order: '))
if choice == 1:
amount = int(input("Enter number of Burgers: "))
bcount += amount
elif choice == 2:
amount = int(input("Enter number of Fries: "))
fcount += amount
elif choice == 3:
amount = int(input("Enter number of Drinks: "))
dcount += amount
elif choice == 4:
sub = (bcount * 5.00) + (fcount * 3.50) + (dcount * 1.00)
tax = sub * 0.075
total = sub + tax
print('Number of Burgers: {0}'.format(bcount))
print('Number of Fries: {0}'.format(fcount))
print('Number of Drinks: {0}'.format(dcount))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
The expected result is after each order, the program would give me a running subtotal.
Example: after an order of a burger is entered would look like:
Your subtotal is: $5.00
Then the next order is an order of fries and a drink
Your subtotal is: $9.50 (adding the burger from the previous order)
One way to do this is to add a variable called subtotal in the beginning called subtotal. Attached one example for the burger that can be applied to the rest. I agree with previous commenter regarding reset of variables instead of break.
subtotal=0
bcount = 0
fcount = 0
dcount = 0
if choice == 1:
amount = int(input("Enter number of Burgers: "))
bcount += amount
subtotal+=(amount*5)
print("Your total is: ",subtotal)
I assume, for option 1 - 3, you need to show the subtotal and for option 4 you need to show the full report.
I have updated the code as following:
added calculate_sub_total method.
displayed subtotal for option 1-3.
separated the if-elif-else to two partitions.
Used the menu dictionary to fetch prices for items both in sub total calculation and in displaying the menu.
Used the order dictionary to keep track of the number of items as intended. Removed bcount, dcount, fcount variables as they are not needed anymore.
Updated code:
# menu and order options
menu = {"burger":5.00, "fries":3.50, "drink":1.00}
order = {"burger":0, "fries":0, "drink":0}
def calculate_sub_total():
return (order["burger"] * menu["burger"]) + \
(order["fries"] * menu["fries"]) + \
(order["drink"] * menu["drink"])
while True:
print("Please make a selection:")
print("1. Burger = ${}".format(menu["burger"]))
print("2. Fries = ${}".format(menu["fries"]))
print("3. Drink = ${}".format(menu["drink"]))
print("4. Quit")
choice = int(input('Please order: '))
show_subtotal = False
if choice == 1:
amount = int(input("Enter number of Burgers: "))
order["burger"] += amount
show_subtotal = True
elif choice == 2:
amount = int(input("Enter number of Fries: "))
order["fries"] += amount
show_subtotal = True
elif choice == 3:
amount = int(input("Enter number of Drinks: "))
order["drink"] += amount
show_subtotal = True
sub = calculate_sub_total()
if show_subtotal:
print('Subtotal: {:0.2f}'.format(sub))
if choice == 4:
tax = sub * 0.075
total = sub + tax
print('Number of Burgers: {0}'.format(order["burger"]))
print('Number of Fries: {0}'.format(order["fries"]))
print('Number of Drinks: {0}'.format(order["drink"]))
print('Subtotal: {:0.2f}'.format(sub))
print('Tax: {:0.2f}'.format(tax))
print('Total: {:0.2f}'.format(total))
break
Output:

Trying to call read/write functions

I am a beginner programmer learning python in my intro game development class. The current homework assignment is to create a function to read and write files. We have to do it also where we can use user input to find the file directory. The problem I'n currently having is that I can't figure out how to write the function to open and close the files. I'll post my code for any help. Thank you. I am only focused on Option 8 for the time being.
enter = 0
start = 0
Roger = ()
text_file = ()
line = open("read.txt", "r")
def read_file(line):
for line in text_file:
print(line)
return line
def close_file(text_file):
text_file.close()
return close_file
def update_score(scores, person, amount):
for score in scores:
if score[0].lower() == person.lower():
score[1] += amount
return scores
def update_score1(scores, person, amount):
for score in scores:
if score[0].lower() == person.lower():
score[1] -= amount
return scores
def addition(num1):
return num1 + num1
def square(num):
print("I'm in square")
return num * num
def display(message):
"""Display game instuctions"""
print(message)
def instructions():
"""Display game instuctions"""
print("Welcome to the world's greatest game")
def main():
str1 = ["Roger", 3456]
str2 = ["Justin", 2320]
str3 = ["Beth", 1422]
instructions()
scores = [str1, str2, str3]
start = input("Would you like to view the high score options? y/n ")
if start == "y":
print("""\
Hello! Welcome to the high scores!
Here are the current high score leaders!:
""")
print(scores)
print("""\n\
0 - Sort high scores
1 - Add high score
2 - Reverse the order
3 - Remove a score
4 - Square a number
5 - Add 2 numbers together
6 - Add to a score
7 - Subtract from a score
8 - Read a file
9 - Write to a file
""")
option = int(input("Please enter your selection "))
while option < 8:
print(scores)
if option == 0:
scores.sort()
print("These are the scores sorted alphabetically")
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 1:
print(scores)
print("Please enter your name and score; After entering your name, hit the return key and enter your score")
name = input()
score = int(input())
entry = (name,score)
scores.append(entry)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 2:
print(scores)
scores.reverse()
print("\nHere are the scores reversed")
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 3:
print(scores)
print("Please enter the high score you would like to remove. After typing the name, hit the return key and enter the score")
name1 = input()
score1 = int(input())
remove = (name1,score1)
scores.remove(remove)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 4:
val = int(input("Give me a number to square"))
sqd = square(val)
print(sqd)
option = option = int(input("Please enter your selection"))
elif option == 5:
val0 = int(input("Give me one number"))
val1 = int(input("Give me another number"))
addi = (val0 + val1)
print(addi)
option = option = int(input("Please enter your selection"))
elif option == 6:
print(scores)
sc0 = input("Please enter player whose score you would like to increase. ")
sc1 = int(input("Please enter the amount would would like to add to their score. "))
scores = update_score(scores, sc0, sc1)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 7:
sc2 = input("Please enter player whose score you would like to decrease. ")
sc3 = int(input("Please enter the amount you would like to subtract from their score. "))
scores = update_score1(scores, sc2, sc3)
print(scores)
while option <= 8:
if option == 8:
print (line)
text_file.close()
option = option = int(input("Please enter your selection"))
main()
Function to return a file's contents:
def read_file(filename):
return open(filename).read()
To write to a file:
def write_file(filename, toWrite):
file = open(filename, 'w')
file.write(toWrite)
file.close()
Example usage:
stuffInFile = read_file("myfile.txt")
write_file("myfile.txt", "I just wrote this to a file!")

Categories

Resources