Why will no more code run after using a while loop? - python

I am new to Python.
I am creating a GPA calculator. The first part is taking a student number and checking if it is valid. It is valid if the sum of the numbers are divisible by seven (that part works).
If the number is valid, then the user must enter their letter grades for all their classes. The code must keep accepting input until a blank line is submitted. I am using a while loop for this part.
But once all their grades are submitted, and they enter a blank line, I need to take the raw input and use it to calculate their GPA. My problem is that no other code seems to run after the while loop ends. I want to run a for loop to check the input and translate them into GPA scores, but no matter where I put it/what I put in it, the code will just end after the input is submitted.
Here is what I've done:
student_number=raw_input("What is your 5-digit student number?")
added_digits=sum(int(x) for x in student_number)
div_7=added_digits%7
if div_7==0 and len(str(student_number))==5:
print "Your student number is valid."
grades=raw_input("To find out your average GPA, please list your letter
grades for each class.\n")
while grades!="":
grades=raw_input()
grade_value=0
for x in grades:
if x=="A":
grade_value+=4.0
print grade_value
if x=="B":
grade_value+=3.0
print grade_value
else:
print "That is not a valid student number."`enter code here`
No matter what input I put in, the for loop after the while loop never seems to run. I can't seem to make the code do anything else after the while loop.
Thanks!

Your while-loop ensures that grades ends up empty (it throws anything non-empty away), and your for-loop then goes over that empty grades. So of course it has nothing to do.

the problem is that your for-loop use grades while grades is not a list, in my opinion, you should use one more list to store you grades:
student_number=raw_input("What is your 5-digit student number?")
added_digits=sum(int(x) for x in student_number)
div_7=added_digits%7
if div_7==0 and len(str(student_number))==5:
print "Your student number is valid."
grades=raw_input("To find out your average GPA, please list your letter grades for each class.\n")
grade_list = [grades] #use a list to store your grades
while grades!="":
grades=raw_input()
grade_list.append(grades) #store every input in grade_list
grade_value=0
for x in grade_list: #use grade_list, not grades
if x=="A":
grade_value+=4.0
print grade_value
if x=="B":
grade_value+=3.0
print grade_value
else:
print "That is not a valid student number."

raw_input will take the grades as input by itself. You don't need to take them again using a loop.
So, this is one way to do what you're trying to do.
student_number=raw_input("What is your 5-digit student number?")
added_digits=sum(int(x) for x in student_number)
div_7=added_digits%7
if div_7==0 and len(str(student_number))==5:
print "Your student number is valid."
grades=raw_input("To find out your average GPA, please list your letter grades for each class.\n")
#while grades!="":
#grades=raw_input()
grade_value=0
for x in grades:
if x=="A":
grade_value+=4.0
print grade_value
if x=="B":
grade_value+=3.0
print grade_value
else:
print "That is not a valid student number."

Related

How can I store data using loops

I have an assignment
(Find the highest score) Write a program that prompts the user to enter the number
of students and each student’s score, and displays the highest score. Assume that
the input is stored in a file named score.txt, and the program obtains the input from
the file.
However we haven't learned how to store data in a .txt file yet so the teacher told us to just treat it as inputs.
What I have so far:
grade = 0
students = eval(input("enter number of students: "))
for i in range(1, students + 1):
grade = eval(input("enter student score: "))
I understand how to input number of students and store it in to a variable (students).
And I know how to write a loop to repeatedly ask for the input (student score) equal to the number of students
but I don't know how to store each students score separately other than doing it once under the for loop (grade).
students = int(input("enter number of students: "))
highest_grade = 0
for i in range(1, students + 1):
grade = int(input("enter student score: "))
if grade > highest_grade:
highest_grade = grade
print("Highest score is {}".format(highest_grade))
I just run and tested. Its working fine
Well you can also try using dictionary. Store student names as well as their scores. Then check for the highest score. You code:
students=int(input ("Enter no of students: "))
scores={}
hg=0
for i in range(students):
name=input("Enter name of student= ")
score=int(input ("Enter score: "))
scores[name]=score
if score>hg:
hg=score
print("Highest score is ",hg)
Explaination: we'll take input for both name as well as score from user and store it in dictionary. By default, we'll save hg(highest score) as 0. Then while taking user input for score, we'll check whether it greater than hg, if yes, update hg to new score and keep checking it until the loop terminates and finally print it
You do this stuff without dictionary and list, I just suggested dictionary because it can save data in more systematic way showing both name as well as score

How do you use a while loop to check if index is in range of a list for removing items from a shopping cart?

I am trying to use a while loop to keep asking which item to remove from a list until the user enters an existing index in python. Basically when the user is asked, "What item would you like to remove?" the user should be able to enter a number starting from 1 instead of zero, and up to whatever number of items, there are. For example, if there are ten items, the user should be able to enter 1 -10, not 0 - 9. I have already converted the user input to a zero-based index. Now I need to be able to keep asking "What item would you like to remove?" until the user inputs an existing index.
Here is the code that I am getting stuck on:
items = []
prices = []
quantities = []
item = input("\nWhat item would you like to remove? ").strip()
while item != range(0, len(items)):
print("\nSorry, that is not a valid number.")
item = input("\nWhat item would you like to remove? ").strip()
item_remove = items[int(item) - 1]
items.pop(int(item) - 1)
prices.pop(int(item) - 1)
quantities.pop(int(item) - 1)
print(item_remove + " removed.")
break
I shortened the code so you wouldn't have to read as much, but here is what is happening. When I put in an existing index it displays the print statement "Sorry, that is not a valid number." and then asks for the input "What item would you like to remove?" a second time then after you enter an existing index again it removes the item and goes back to the main menu option that I am using in my code. However, if you enter an index that does not exist, it displays the print statement "Sorry, that is not a valid number." then asks "What item would you like to remove?", but the second time that I enter an index that does not exist the code crashes saying list index out of range. Is there any way that I could get this code to keep asking "What item would you like to remove?" followed by the print statement "Sorry, that is not a valid number." until I enter an existing index? If you need more code let me know, and I greatly appreciate any help or feedback.

Python: How to ask the user for the index of a list

-------Answered, turns out I was doing the right thing, but had a different error that made me think it was the wrong thing to do------------------
Alright, so I know this is super simple but I am really confused as to how to take a user input as a number and use that number to index from a list with that number.
So what I am trying to do is this:
Enter your choice: (User enters a 1)
You choose 1.
Which sentence? (User enters a 0 or whatever number they want within the bounds of how many sentences they enter)
I then just want to use their inputted number and index that from the list.
So if they entered these two sentences for their list:
good
bad
Then when they ask which sentence, and say 1, I want to index sentenceList[1] and print it back to them.
But this needs to be scale-able to any number, so sentenceList[variable],
but I do not know how to properly do this.
Thanks, I know this might be confusing.
#declare variable
TOTAL_SENTENCES = 5
def main():
#print greeting
print ('This program will demonstrate lists')
#establish array sentences
sentenceList = list()
#prompt user for how many sentences to store (assume integer, but if
negative, set to 5)
TOTAL_SENTENCES = int(input('How many sentences? '))
if TOTAL_SENTENCES < 0:
TOTAL_SENTENCES = 5
else:
pass
#store in a list in all lower case letters (assume no period at the end)
while len(sentenceList) < TOTAL_SENTENCES:
userSentence = input('Enter a sentence: ')
sentenceList.append(userSentence.lower())
#print 5 options for the user to choose from (looping this for the total
number of sentences)
for i in range(TOTAL_SENTENCES):
print ('Enter 1 to see a sentence\n' 'Enter 2 to see the whole list\n'
'Enter 3 to change a sentence\n' 'Enter 4 to switch words\n'
'Enter 5 to count letters')
#prompt user for their choice
userChoice = int(input('Enter your choice: '))
#print their choice back to them
print ('You selected choice' ,userChoice)
#prompt for which sentence
#CHOICE-1 (pull from the list and print the sentence)
Now, in the last line of your code, if you want to pull up a sentence from the list sentenceList, you can just write:
print(sentenceList[userChoice-1])
Note that I wrote userChoice-1. This is because people usually are going to number the sentences from 1 to N. But Python's internal list numbering is from 0 to N-1.
I hope this answers your question!

Prompt to enter a name and then output the name that was entered along a score

I am writing a program for my intro CS class but I am a little stuck.
I have a designated list of names that correspond to a list of scores.
I am supposed to prompt the user to enter a name and then the program is supposed to output the name that was entered along with the corresponding score.
As I have it written now the program is printing the first name and score in the set regardless of the input. I have been stuck on this for a while, any help would be greatly appreciated!
Here is what I have right now:
names=['Jim','Sarah','Jason','Lynne','Ginny','Joe','Susan'];
scores=['88','92','95','84','85','92','89'];
input("Please enter student's name:")
for i in range (0,7):
print (input(names[i] + scores[i]));
the program is supposed to output the name that was entered
That'll be hard considering you aren't capturing the input() return value.
Try this (as an example)
name = input("Please enter student's name:")
print(name)
Then, you next task is to check (in your loop) when name == <a name in the list>
Hint: You can use these for your loop rather than range(0,7)
for student in names:
or, even better, see zip lists in python
for (student, score) in zip(names, scores):
Using the zip function, you can combine the two lists together in an easy to use 1-to-1 group of tuples.
names=['Jim','Sarah','Jason','Lynne','Ginny','Joe','Susan']
scores=['88','92','95','84','85','92','89']
data = zip(names, scores) # <- ('Jim', '88'), ('Sarah', '92'), ...
stud = input('Enter the student's name: ')
for (student, score) in data:
if (stud == student):
print('{} -> {}'.format(student, score))
Better to use Python dictionaries for that:
student_scores = {'Jim': 88, 'Sarah': 92, 'Jason': 95}
and so on...
Then you can call for each of them like so;
name = input("Please enter student's name: ")
print(name + 'has a score of ' + student_scores[name])

Making a statistics program

I am trying to write a Python program that computes and prints the following :
the average score from a list of scores
the highest score from a list of scores
the name of the student who got the highest score.
The program starts by asking the user to enter the number of cases. For EACH case, the program should ask the user to enter the number of students. For each student the program asks the user to enter the student's name and marks. For EACH case the program reports the average marks, the highest marks and the name of the student who got the highest marks.
Also
If there are more than one person with the highest score in a CASE, the program should report the first occurrence only.
The average score and the highest score should have exactly 2 decimal places.
The output should be as in the sample program output.
What I have been trying so far is the following:
grade=[]
name_list=[]
cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
print('case',case)
number=int(input('Enter number of students: '))
for number in range (1,number+1):
name=str(input('Enter name of student: '))
name_list.append(name)
mark=float(input('Enter mark of student:'))
grade.append(mark)
highest= max (grade)
average=(sum(grade)/number)
high_name=grade.index(max(grade))
print('average',average)
print('Highest',highest)
print (high_name)
This is what i have deciphered so far. my biggest problem now is getting the name of the individual with the high score. Any thoughts and feedback is much appreciated. As with respect to the answer posted below, i am afraid the only thing i do not understand is the dictionary function but otherwise the rest does make sense to me.
This resembles an assignment, it is too specific on details.
Anyways, the official docs are a great place to get started learning Python.
They are quite legible and there's a whole bunch of helpful information, e.g.
range(start, end): If the start argument is omitted, it defaults to0
The section about lists should give you a head start.
numcases = int(input("How many cases are there? "))
cases = list()
for _ in range(numcases):
# the _ is used to signify we don't care about the number we're on
# and range(3) == [0,1,2] so we'll get the same number of items we put in
case = dict() # instantiate a dict
for _ in range(int(input("How many students in this case? "))):
# same as we did before, but skipping one step
name = input("Student name: ")
score = input("Student score: ")
case[name] = score # tie the score to the name
# at this point in execution, all data for this case should be
# saved as keys in the dictionary `case`, so...
cases.append(case) # we tack that into our list of cases!
# once we get here, we've done that for EVERY case, so now `cases` is
# a list of every case we have.
for case in cases:
max_score = 0
max_score_student = None # we WILL need this later
total_score = 0 # we don't actually need this, but it's easier to explain
num_entries = 0 # we don't actually need this, but it's easier to explain
for student in case:
score = case[student]
if score > max_score:
max_score = score
max_score_student = student
total_score += score
num_entries += 1
# again, we don't need these, but it helps to demonstrate!!
# when we leave this for loop, we'll know the max score and its student
# we'll also have the total saved in `total_score` and the length in `num_entries`
# so now we need to do.....
average = total_score/max_entries
# then to print we use string formatting
print("The highest score was {max_score} recorded by {max_score_student}".format(
max_score=max_score, max_score_student=max_score_student))
print("The average score is: {average}".format(average=average))

Categories

Resources