This is a problem I am working on for a class (below is my question and the code I wrote):
The program should accept a series of students and their exam scores in response to a
"?" prompt. Enter the two digit exam score (no one ever gets 100 or less than 10), a single
space and the name of the student. Keep entering these until the user enters "Stop" –
your program should be able to handle any form of "Stop" – for example, "stop", "Stop",
"STOP", "sTOP", etc.
You should then display a list of student names ordered by their exam scores (low to
high).
For instance (user input is underlined):
? 23 Warren
? 44 Dona
? 33 Tom
? stop
Warren
Tom
Dona
So I understand everything I've written and I understand that this is not an especially complicated problem. Though, the way my code is written, when I input "stop" to show the program that I am finished with inputs, it runs the input "stop" in the for loop creating a index out of range error. How can I make it run "stop" only in the while loop and not in the for loop?
students = []
nameScore = ""
while (nameScore.lower() != "stop"):
nameScore = input ("? ")
students.append(nameScore)
students.sort()
for student in students:
x = student.split()
print (x[1])
If you "break" before you append, then "stop" will not be included in students.
while True:
nameScore = input ("? ")
if nameScore.lower() == "stop": break
students.append(nameScore)
Moreover, if you write the while-loop this way, you won't need to pre-initialize nameScore.
You can change the flow of the program just a bit and have it "prime" the input string before entering the while loop; that way it'll check before it appends the input:
students = []
nameScore = input("? ")
while nameScore.lower() != "stop":
students.append(nameScore)
nameScore = input ("? ")
students.sort()
for student in students:
x = student.split()
print (x[1])
A bit of code repetition, but it does the job.
Another way to do it is to use a list slice to remove the last element:
students = []
nameScore = ""
while nameScore.lower() != "stop":
students.append(nameScore)
nameScore = input ("? ")
students = students[:-1] # Remove the last element
students.sort()
for student in students:
x = student.split()
print (x[1])
By the way, the parenthesis around the while condition aren't necessary in Python.
Related
I'm new to coding and started with a python course now.
I was trying to work on a word bingo game but can't seem to make it work.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
list = bingo.split()
print
print "Okay, let's go! "
random.shuffle(list)
for choice in random.shuffle(list):
user = raw_input()
if user == "":
print(choice)
raw_input("")
else:
print "That's the end of the game ^.^"
break
#for words in range(len(list)):
#user = raw_input()
#if user == "":
#print(random.sample(list, 1))
#raw_input("")
#else:
#print "That's the end of the game ^.^"
#break
If i use choice in random.shuffle(list) I get a NonType error
before I used a for loop with random.sample (seen in the ## parts at the end)
That worked except in each iteration the words were still repeated.
I tried to search for similar questions but they all either had numbers or more automatic loops.
I want it so the user enters words, then each time they press enter, a new word appears from the list without repetition.
I can't seem to figure out how to get that into a loop - any help?
I tried to use random.choice and random.sample but the words still kept repeating in a for loop.
Tried shuffle and had a nonType error
Two comments:
Don't use list for variable name, it is a keyword in Python for type list
random.shuffle(l) does operation in-place (i.e. after you called it, l will be shuffled). So, you just supply l into the loop. Hope this helps.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
l = bingo.split()
print
print "Okay, let's go! "
random.shuffle(l)
for choice in l:
user = raw_input()
if user == "":
print(choice)
raw_input("")
else:
print "That's the end of the game ^.^"
break
P.S.
Why did you decide to use Python 2? If you are new to Python it can be better to work with Python 3. It is your decision to make. FYI, https://www.python.org/doc/sunset-python-2/#:~:text=We%20have%20decided%20that%20January,as%20soon%20as%20you%20can.
I am working on a teacher grading system in Django. I want functionality in which there is some entry like subject id and student's marks from the frontend. My app on the backend takes these two-parameter and creates a list of dictionaries with subject id and marks and pass it on another function and that function will sum up all the marks and give me a total and next average and percentage etc. But right now, I am stuck with total only so, when I pass this list of dictionaries in a function it gives me an error.
def marks_calculation(marks_entry):
total = sum(item['marks'] for item in marks_entry)
return total
class Student_marks:
def entry(subject_id, marks):
while True:
value = input("Need to enter marks, Press 'y' for Yes, 'n' for No: ").lower()
if value == 'n':
break
try:
subject_id = int(input(f'Enter subject id: '))
marks=int(input(f'Enter marks: '))
except ValueError:
print(f'You can only try integers:')
continue
marks_entry=[]
marks_entry.append({
"subject_id": subject_id,
"marks": marks
})
total_marks = marks_calculation(marks_entry)
return total_marks
marks=0
subject_id= 0
b= Students_marks
b.entry(marks, subject_id)
error is:
It is not giving me a total marks
"c:/Users/Lenovo/Documents/TGS/controller.py"
Enter subject id: 1
Enter marks: 58
PS C:\Users\Lenovo\Documents\TGS>
Based on your new edited question, there are multiple issues with your current code -
The indentation is incorrect at places.
The try/except block should be under the while loop
Since you want to first put all the entries in the marks_entry, you should intialize it first and then append data to it. Currently, its being reset back to [] after every new entry that you get. So it will always have at most 1 element in it, when you are trying to sum it up.
The total should be calculated in the end once you exit out of the while loop
Here's a sample code built on top of yours -
def marks_calculation(marks_entry):
total = sum(item['marks'] for item in marks_entry)
return total
class Student_marks:
def entry(subject_id, marks):
marks_entry=[]
while True:
value = input("Need to enter marks, Press 'y' for Yes, 'n' for No: ").lower()
if value == 'n':
break
try:
subject_id = int(input(f'Enter subject id: '))
marks=int(input(f'Enter marks: '))
except ValueError:
print(f'You can only try integers:')
continue
marks_entry.append({
"subject_id": subject_id,
"marks": marks
})
total_marks = marks_calculation(marks_entry)
return total_marks
marks=0
subject_id= 0
b = Student_marks
total = b.entry(marks, subject_id)
print(f'Your total marks are {total}')
Sample Output:
Need to enter marks, Press 'y' for Yes, 'n' for No: y
Enter subject id: 1
Enter marks: 44
Need to enter marks, Press 'y' for Yes, 'n' for No: y
Enter subject id: 2
Enter marks: 23
Need to enter marks, Press 'y' for Yes, 'n' for No: y
Enter subject id: 3
Enter marks: 12
Need to enter marks, Press 'y' for Yes, 'n' for No: n
Your total marks are 79
There are a few problems with your class. First of all, since you used b.mark_calculation() I assume you tended to define this function within the class, which is not right now! So, calling it on the class would be wrong. you should call it like:
class Marks_entry:
def marks_entry(subject_id, marks):
#...
def marks_calculation(marks_entry):
total = sum(item['marks'] for item in marks_entry)
return total
Second, you called marks_calculation without referring to the class. If you are trying to call a function of class, in most of the cases, you should use self in order to call a function of an object right within itself. Meaning your code should be something like:
class Marks_entry:
def marks_entry(subject_id, marks):
# rest of code
marks_calculation = self.marks_calculation(marks_entry)
return marks_calculation
def marks_calculation(self,marks_entry):
total = sum(item['marks'] for item in marks_entry)
return total
Third, you call the class without () which seems to be wrong. You should use something like:
# Rest of code
b= Marks_entry()
Fourth, I can't understand your intention of using b.marks_calculation(marks, subject_id) since you have defined this function to get just one argument(just marks and notsubject_id ). If you want to pass more variables to your function, you should define them in the function before calling the function.
I'm learning beginner python and there's one question that I'm stuck on.
The question involves asking user input for any amount of mushrooms that they have picked, entering a weight, and then sorting them according to the user input. For this, a list and a while loop is needed to append the inputs into the list.
Currently I am trying to implement a sentinel value that will stop the while loop after all of the user inputs have been entered, but setting the sentinel as "STOP" conflicts with the int() notification.
if __name__ == "__main__":
STOP = "stop"
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
total_list = []
while total_list != STOP:
total_list.append(mushroom)
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
print(total_list)
The program runs well until entering "STOP", where a syntax error appears.
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
ValueError: invalid literal for int() with base 10: 'STOP'
As you can see, the sentinel value STOP conflicts with my input suggestion, resulting in an error.
As for the second part of the problem, I need to sort the value inputs by weight. If everything has been done correctly, I should have a list with all the values.
What kind of code can I use in order to sort the values?
I need to sort each integer value based on small (<100), medium (100-1000), and large (>1000), then print the results in a statement.
Am a little clueless regarding what I need to do here.
Thank you, just kind of stuck in one place.
You can use the error produced by trying to convert a noninteger to an integer to your advantage with try and except in Python. Here is the documentation for that.
Rewriting your code, you might try this:
if __name__ == "__main__":
STOP = "STOP"
total_list = []
while True:
try:
user_input = input("Enter a mushroom weight in grams, or STOP to end. ")
total_list.append(int(user_input))
except ValueError:
if user_input.strip().upper()==STOP:
break
else:
print("Incorrect entry! '{}' is not an integer".format(user_input))
Then if you want to sort that list and put into categories, you might consider using a dictionary:
total_list.sort()
di={'Small':[],'Medium':[],'Large':[]}
for e in total_list:
key='Small' if e<100 else 'Medium' if 100<=e<=1000 else 'Large'
di[key].append(e)
print(total_list, sum(total_list),di)
The first crash is occurring because you are trying to cast "STOP" as an int. For example, if you open a python interpreter and type int("STOP") you will get the same crash. The interpreter does not know how to convert the string "STOP" to an integer. A better way might be to check if the input string can be converted to an integer with isdigit() or a try/except.
For the filtering, the easiest way would be to use a list comprehension on your lists. Something like this should work:
if __name__ == "__main__":
mushroom = None
total_list = []
while mushroom != "STOP":
mushroom = input("Enter a mushroom weight in grams, or STOP to end. ")
if mushroom.isdigit():
total_list.append(int(mushroom))
sorted_total_list = sorted(total_list)
small_values = [mushroom for mushroom in total_list if mushroom < 100]
medium_values = [mushroom for mushroom in total_list if 100 <= mushroom <= 1000]
large_values = [mushroom for mushroom in total_list if mushroom > 1000]
print(sorted_total_list)
print(small_values)
print(medium_values)
print(large_values)
I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.
New to coding...
i am a student and have been tasked with writing a code that asks the user to input a series of values that will i will store in a list and then to ask to input a value (continue this until user types done) and then to check to determine if it is found in the list of valid values.
I'm assuming this could be done with a while true loop to accomplish the input until 'done' is typed and i'm assuming a search using 'if' and 'in' would accomplish the second part.
I am struggling finding a while true using the list of input. i am using an integer input. what am i comparing the condition to if to continue the loop?
Any help is appreciated! The code below is what i wrote i test if i could store input in a list but the while true is where i'm struggling with what to compare.
while True:
if list_of_inputs
list_of_inputs = input("Write numbers: ").split()
list_of_inputs = list(map(int , list_of_inputs))
print (list_of_inputs)
Here's some code that does what you described in the comments.
We use two while loops. The first one gets lines of input, one by one, and adds them to the list_of_inputs. If a line consisting of the string "done" is read we break out of the loop, and we don't add "done" to the list.
The second loop gets lines of input and tests whether or not they are present in list_of_inputs, printing an appropriate message. If the user inputs a line that is present in list_of_inputs we break out of the loop and the program ends.
print('Please enter values for the list, one value per line')
print('Enter "done" (without the quotes) to end the list')
list_of_inputs = []
while True:
s = input('value: ')
if s == 'done':
break
list_of_inputs.append(s)
print('Here is the list:')
print(list_of_inputs)
while True:
s = input('Please enter a test value: ')
if s in list_of_inputs:
print('Yes!', repr(s), 'is in the list')
break
else:
print('No', repr(s), 'is NOT in the list')
test run
Please enter values for the list, one value per line
Enter "done" (without the quotes) to end the list
value: abc def
value: ghi
value: jkl
value: done
Here is the list:
['abc def', 'ghi', 'jkl']
Please enter a test value: def
No 'def' is NOT in the list
Please enter a test value: ghij
No 'ghij' is NOT in the list
Please enter a test value: jkl
Yes! 'jkl' is in the list
Python 3.x
list_of_inputs = list()
while True:
var = input("Enter Number or type 'done' to exit :")
if var.lower() == 'done':
print(" Your inputs are: ",list_of_inputs)
exit()
else:
list_of_inputs.append(int(var))
Make sure indentation is proper in python codes.