A453 Task 3 Programming [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am currently studying computer science as a GCSE student. Me and my teacher are struggling with task 3. The requirements of the task are:
It then needs to ask the user what class they would like to view
After this it will need to ask if they would like to view the file sorted alphabetically, the high scores of the particular class or if they would like to view the average of each student in the selected class
import csv
print("1 for Class A\n2 for Class B\n3 for Class C")
choosen=int(input())
class_a = open('class_a.csv')
class_b = open('class_b.txt')
class_c = open('class_c.txt')
if choosen == 1:
print("1 for for alphabetical orderwith each students highest score\n2 for highest score, highest to lowest\n3 for average score, highest to lowest")
cho_two=int(input())
csv_a = csv.reader(class_a)
a_list = []
for row in csv_a:
row[1] = int(row[1])
row[2] = int(row[2])
row[3] = int(row[4])
minimum = min(row[1:2])
row.append(minimum)
maximum = max(row[1:2])
row.append(maximum)
average = sum(row[1:2])//3
row.append(average)
a_list.append(row[0:9])
if cho_two == 1:
alphabetical = [[x[0],x[6]] for x in a_list]
print("\nCLASS A\nEach students highest by alphabetical order \n")
for alpha_order in sorted(alphabetical):
print(alpha_order)
class_a.close()
elif cho_two == 2:
print("\nCLASS A\nThe highest score to the lowest \n")
for high_scr in sorted(highest_score,reverse = True):
print(high_scr)
class_a.close()
elif cho_two == 3:
average_score = [[x[8],x[0]] for x in a_list]
print("\nCLASS A\nThe average score from highest to lowest \n")
for ave_scr in sorted(average_score,reverse = True):
print(ave_scr)
class_a.close()
My code when run in python tells me there is a problem on line 13 with "index out of range"
My text file contains:
Roo,2,3,
Roo,4,4,
Alfie,5,8,
Alfie,2,8,
Bob,2,8,
Connor,3,5,
Connor,5,3,
Ellis,5,6,
George,5,4,
Ellis,4,9,
Nathan,5,6,
George,5,5,
Alfie,9,4,
George,4,7,
Celis,4,5,
Leo,3,2,
Celis,6,1,
Leo,5,2,
When I run the program the code, row1 = into(row1) tells me it's out of range? Any solutions?

Python - like most programming languages - uses zero-based indexing, which means the first element of a sequence is at index 0 and the last one at index len(sequence) - 1.
In your code you have rows with three elements each, and you are trying to access row[3], which would be the index of an (inexistant) fourth element, hence your error.
Also if your teacher is "struggling" with such a basic problem, you should probably find a competent teacher instead.

Related

Having trouble with def functions [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I have been taking this class for a bit with python for a bit and I have stumbled into a problem where any time I try to "def" a function, it says that it is not defined, I have no idea what I am doing wrong and this has become so frustrating.
# Define main
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
Every time I try to test run this, I get
"builtins.NameError" name 'LIST SIZE' is not defined.
I cant take out the main function! It's required for the assignment, and even if I take it out I still run into errors.
Your MIN, MAX, and LIST_SIZE variables are all being defined locally within def main():
By the looks of it, you want the code below those lines to be part of main, so fix the indentation to properly declare it as part of main.
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
import random
# Define main
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
main()
Output:
[79]
NOTE: You will get another error message:
NameError: name 'findHighest' is not defined
Which I think findHighest should be a function in some part of your code.

How could I print the highest score and name of student grades using python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Using python I'm creating a code that receives a list of lists as parameter. This list of lists contains names and grades of students. The function also must print the name of the student with the best grade and its best grade. When I created the code and try to run it nothing occurs is there a way to improve my code? My desired output would be "The best student is: Caroline with a 9.6"
students=[["steve", 9.0], ["ben", 9.5], ["Caroline",9.6],["Tim", 9.1]]
highest_grade=[]
lowest_grade=[]
def best():
i = 1
max = min = students[0]
# first, calculate the max and min.
while i < len(students): # (possible improvement: replace this with a for loop)
if students[i] > max:
max = students[i] # replace max with the new max
if students[i] < min:
min = students[i] # replace min with the new min
i += 1
highest_grade.append(max)
lowest_grade.append(min)
print("The best student is:",best())
There are a few things you could do to improve it. You find the min score but don't use it, so I'm not sure if you need it. If you do need it, you could add it to your return statement. Here's a suggested way to do it that should be easy to follow:
students = [["steve", 9.0], ["ben", 9.5], ["Caroline", 9.6], ["Tim", 9.1]]
def best(students):
highest_grade_name = None
lowest_grade_name = None
my_max_score = -float("inf")
my_min_score = float("inf")
for name, score in students:
if score > my_max_score:
my_max_score = score
highest_grade_name = name
if score < my_min_score:
my_min_score = score
lowest_grade_name = name
return my_max_score, highest_grade_name
best_name, best_score = best(students)
print(f"The best student is {best_name} with a score of {best_score}")
max(students,key=lambda x:x[1])
I think would work
There could be quite a few improvements to this piece of code. Firstly, it would be far better if the students array was a dict, but it's understandable if it absolutely has to be an array of arrays.
Secondly, you're right, you should do this with a for loop:
def best_student_grade():
highest_grade = 0 # "max" is a terrible name for a variable
for student, grade in student:
if grade > highest_grade:
grade = highest_grade
best_student = student
return highest_grade, best_student
bstudent, bgrade = best_student_grade()
print(f"The best student is: {bstudent} with a {bgrade}")
You could even do this with a list comprehension, but I will leave that as an exercise to the reader.
In all honesty, I think it would benefit you in a lot of ways to read some introductory python or programming books.

Find the "1"s in a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to find a book's page count. The pages have 689 1's in it. So it goes 1,2,3,..11,12,.. in order to find the page count, I need to count the 1's. I thought:
book = []
page = 0
while True:
page += 1
book.append(page)
if book.count(1) == 689:
print("The book is {} pages".format(page))
break
but .count(1) does not include 11,21,111 etc. What can I use instead of .count()?
In order to count the number of pages, you could try to just keep track of a counter variable accumlatively instead of using count on the whole book array.
# book = []
page = 0
count = 0
while True:
page += 1
# book.append(page)
count += str(page).count('1')
if count == 689:
print("The book is {} pages".format(page))
break
book = []
page = 0
sum_of_ones = 0
while True:
page += 1
book.append(page)
sum_of_ones += str(book[-1]).count("1")
if sum_of_ones == 689:
print(f"this book has {page} pages.")
break
#output
1234 pages
I believe this is an efficient way.
It keeps counting the newly added page to the book and increases the sum if possible then rechecks if it is ==689 . It breaks when the number is met.
Only issue is that it will keep iterating if 689 is not met

python quiz with subject options [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
print("plese choose a topic of your liking")
History = ('History')
Music = ('Music')
Computer_science = ('Computer science')
print (History, Music, Computer_science)
History = print("when did the Reichstag fires begin?")
one = ("1) 1937")
two = ("2) 1933")
three = ("3) 1935")
print (one, two, three)
guess = int(input())
if guess == 2: #this makes it so any option appart from 2 is outputed as 'wrong'
print ("well done")
else:
print("wrong")
I have created the first part of my python quiz, It took me a while to figure out, I have also created a list that contains 3 different subjects, Do any of you know how to assign a button to each element within my subject list? If this does not make any sense, please let me know (I'm new to this site)
to get this sort of behaviour you can make an input before everything else which determines what subject you choose based on user input. so something REAL simple like:
subject = int(input("Please choose what subject you would like
(number):\n[1]History\n[2]Maths\n[3]Geography\n"))
if subject == 1:
print("You have chosen History")
elif subject == 2:
print("You have chosen Maths")
elif subject == 3:
print("You have chosen Geography")
else:
print("that is not an available option")
This is probably the simplest it can get with menus... If you type 1 and press enter you get history and so on. i dont know how your program works but do what fits in.
There are probably better ways too this is just what I remember doing back in the day. Very simple stuff

Python: How to print my simple poem [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to know how I could print out sentences using my triplet poem program.
My program randomly picks a list of nouns to use.
My program:
import random
def nouns():
nounPersons = ["cow","crowd","hound","clown"];
nounPlace = ["town","pound","battleground","playground"];
rhymes = ["crowned","round","gowned","found","drowned"];
nounPersons2 = ["dog","frog","hog"];
nounPlace2 = ["fog","Prague","smog"];
rhymes2 = ["log","eggnog","hotdog"];
nounList1 = [nounPersons,nounPlace,rhymes]
nounList2 = [nounPersons2,nounPlace2,rhymes2]
nounsList = [nounList1, nounList2]
randomPick = random.choice(nounsList)
return(randomPick)
verbs = ["walked","ran","rolled","biked","crawled"];
nouns()
For example, I could have "The cow walked to the town. But then it was drowned." And just replace the nouns/rhyme(cow, town,drowned) and verb(walked) with my randomizer.
Would I use random.randint in some way?
I just basically need a general print statement like the example I showed using my randomizer to randomly pick between the nouns/rhymes.
As usual (for me), there may be a more Pythonic approach, but to get what you have working, I did three things:
assigned your call to the nouns() function to 'chosen_list' variable. That way the returned 'randomPick' gets used.
built in a selection step to get individual words from the lists in 'chosen_list' and your verb list
added a final print statement with formatting to assemble the words in to a sentence
the code:
import random
def nouns():
nounPersons = ["cow","crowd","hound","clown"];
nounPlace = ["town","pound","battleground","playground"];
rhymes = ["crowned","round","gowned","found","drowned"];
nounPersons2 = ["dog","frog","hog"];
nounPlace2 = ["fog","Prague","smog"];
rhymes2 = ["log","eggnog","hotdog"];
nounList1 = [nounPersons,nounPlace,rhymes]
nounList2 = [nounPersons2,nounPlace2,rhymes2]
nounsList = [nounList1, nounList2]
randomPick = random.choice(nounsList)
return randomPick
verbs = ["walked","ran","rolled","biked","crawled"]
# this is change 1.
chosen_list = nouns()
# select single words from lists - this is change 2.
noun_subj = random.choice(chosen_list[0])
noun_obj = random.choice(chosen_list[1])
rhyme_word = random.choice(chosen_list[2])
verb_word = random.choice(verbs)
# insert words in to text line - this is change 3.
print ("The {} {} to the {}. But then it was {}.".format(noun_subj, verb_word, noun_obj, rhyme_word))

Categories

Resources