I've kind of run into a brick wall with one of my latest assignments where I have to calculate the class average from a text file that is created after a certain amount of inputs from a user.
Code:
f=open('class.txt','w')
title=['name','english','math','science']
f.write(str(title)+""+"\n")
name=input("enter student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
s=int(input("enter science score:"))
o=input("do you wish to continue?: y/n:")
f.write(name + " " +str(m)+ " "+str(e)+" "+str(s)+" "+"\n")
name =[]
while o !='n':
name=input("enter a student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
s=int(input("enter science score:"))
o=input("do you wish to continue?: y/n:")
f.write(name + " " +str(m)+ " "+str(e)+" "+str(s)+" "+"\n")
f.close()
Basically, the text file needs a header, hence the line with "title" in it, and after the user hits 'n' the text file gets saved.
Now I'm having trouble figuring out how to write the code that reads the text file, calculates the total score of each, calculates the average score of each student and then prints it all into three columns. If I could get any pointers as to how I should go about doing this it would be much appreciated! Thanks!
(I am not a phython programmer so the syntax may not be exactly right)
I am assuming that you are to write the code that produces the text file and calculates the average at the same time. If so then no need write file then re-read it, just keep running total and calculate average when you're done.
numberOfStudents = 0
int totalMathScore = 0
# Only showing math score add lines to do same with english / science
# see below about how loop should be structured
while continue != 'n':
numberOfStudents += 1
m=int(input("enter math score:"))
totalMathScore += m
# Now calculate average math score
averageMathScore = totalMathScore / numberOfStudents
Look for bits of repeated code and refactor. e.g. where you're getting the scores both outside and inside the loop. Thats poor style and should be either
a) Put that in a function
b) Or more likely for this simple example change loop to something like
continue = 'y'
while (continue != 'n'):
name=input("enter a student name:")
m=int(input("enter math score:"))
e=int(input("enter english score:"))
...
Other bonuses
Use descriptive variable names - e.g. mathScore rather than m
Error handling - what happens if someone types in "BANANA" for a score?
Related
Just started programming in python 3 and I am trying to pull from an input() where I have placed the input() command in the first line and then further down use the output() to retrieve the input().
Here is an example:
rent = eval(input("How much does rent cost per year? $"))
Now I want to get the input I put in (10,000) and retrieve it from the input automatically using output() or another command.
print output("The family rent is", _______ , "per year."
What code would go in the ________ so I can retrieve what I put in for the input?
Thanks - newbie
the code as is :
# get user input
user_input = input("How much does rent cost per year? $")
# cast to int or whaterver you're expecting
try :
cost = int(user_input)
except :
print ("expecting a number")
# stop here maybe return
# print output
print ("The family rent is", cost , "per year.")
Use string formatting:
print('The family rent is {} per year'.format(rent))
See here for documentation of string formatting:
https://docs.python.org/3/library/string.html#format-string-syntax
I have to make a fill in the blank quiz for my online class but I seem to be stuck, and am having trouble finding out why I'm stuck. Any advice would be great, thanks! this is my code so far... When I run the code it gets to the point of asking the first question and is looking for an answer but when I put it in it gives me the "not quite, please try again" prompt so am I not calling the answers right?
print ('Welcome to my computer programming Quiz, in this quiz you will be
asked to select from three difficulty levels, easy, medium, and hard. Each
the level contains 4 - 5 fill in the blank questions')
print ('')
print ('Your score at the end will be based on how many correct answers you
get compared to the number of guesses you take')
print ('')
# opening introduction to the Quiz
level=None
while level not in ['easy', 'medium', 'hard']:
level = input ('Please select a difficulty (easy, medium, or hard):').lower()
# This is where the difficulty is chosen, this is also is the reason I couldn't get my
# code to open until I did some searching around the internet and found that
# raw_input had to be replaced with input in newer versions of python. Also, I found
# that adding .lower() makes the user's input lower case so that it fits with the
# potential answers.
guesses, score = 0, 0
# this is where the number of guesses and the number of right answers will be collected
# and then shown to the user at the end
easy_questions = ['When you give a computer an instruction, its called
giving a computer a _____.',
'The _____ of a computer language is the set of rules that
defines the combination of symbols that are considered to be a correctly
structured document or fragment in that language.',
'A _____ is a value, one that can change based on conditions.',
'One piece of a larger group is called a _____ in computer
programming.',
'_____ are made up of elements, and are enclosed in square brackets.']
medium_questions = ['A _____ starts with the keyword def followed by the its name.',
'A _____ is a character that represents an action, such as x representing multiplication.',
'A _____ is a set of coded instructions that tell a computer how to run a program or calculation.',
'A _____ is traditionally a sequence of characters either as a literal constant or as some kind of variables.',
'An expression inside brackets is called the _____ and must be an integer value.']
hard_questions = ['A sequence of instructions that is continually repeated until a certain condition is reached, is called a _____ function.',
'A control flow statement that allows code to be executed repeatedly based on a true/false statement is called a _____ loop.',
'This is a common thing in programming when a variable is defined and then redefined the variable has gone through a _____.',
'_____ refers to the situation where the same memory location can be accessed using different names']
# The first thing I tried was having all the questions and then all of the answers
# together in two big lists bc of some code I saw online while researching how to
# do this project but couldn't figure out how to make that code work so I started
# over and tried this way with longer code but code I thought I could make work.
easy_answers = ['command', 'syntax', 'variable', 'element', 'lists']
medium_answers = ['function', 'operator', 'procedure', 'string', 'index']
hard_answers = ['loop', 'while', 'mutation', 'aliasing']
if level == 'easy':
questions = easy_questions
answers = easy_answers
elif level == 'medium':
questions = medium_questions
answers = medium_answers
elif level == 'hard':
questions = hard_questions
answers = hard_answers
# this is how I bet thought to get the the right questions and answers to be called up.
number_of_questions = 5
question_number = 0
def check_answer(user_answer, questions, answers):
if user_answer == answers:
print ('')
print ('Correct!')
score = + 1
guesses = + 1
question_number = + 1
# this will increase the score and guesses by one and move the quiz on to
# the next question.
else:
print ('')
print ('Not quite, please try again')
guesses = + 1
# this will only increase the guesses by one, and give the user another
# chance to answer the same question again.
while question_number < number_of_questions:
questions = questions[question_number]
user_answer = answers[question_number]
print('')
user_answer = input (questions + ': ').lower()
# Prompts the user to answer the fill in the blank question.
print (check_answer(user_answer, questions, answers))
# this is where im also having a lot of trouble, ive done some research online and this
# is what i was told to use but it doesn't seem to be working.
print ('')
print ('Congratulations, you have completed the ' + str(level) + ' level, with a score of ' + str(score) + ' out of ' + str(guesses) + ' guesses')
Well the problem seems to be very trivial. When you check if the answer is correct or not in the check_answer with the code line below:
if user_answer == answers:
you're answers is an array containing all the answers while the user_answer is the string that the user has typed. Hence, when you type the first answer as "command" is tries to match the string "command" to an array containing a few strings. which is definitely not gonna match.
use the below code line to solve it:
if user_answer in answers:
I am having trouble with making a simple calculator work. There are some requirements I need to meet with it:
Need to be able to calculate the average of however many grades the user wants
Be able to calculate within the same program separate grade averages
for multiple 'users'
Give the option to exclude the lowest value entered for each person
from their individual average calculation.
I have some code, it is pretty much a mess:
def main():
Numberofstudents=eval(input("How many students will enter grades today? "))
Name=input("What is your frist and last name? ")
numberofgrades=eval(input("How many grades do you want to enter? "))
gradecount=0
studentcount=1
lowestgradelisty=[]
while studentcount<=Numberofstudents:
gradetotal=0
while gradecount<numberofgrades:
gradeforlisty=eval(input("Enter grade please: "))
gradetotal=gradetotal+gradeforlisty
gradecount=gradecount+1
Numberofstudents=Numberofstudents-1
studentcount=studentcount+1
lowestgradelisty.extend(gradeforlisty)
min(lowestgradelisty.extend(gradeforlisty))
Drop=(min(lowestgradelisty.extend(gradeforlisty))), "is your lowest grade. do you want to drop it? Enter as yes or no: "
if (Drop=="yes"):
print(Name, "The new total of your grades is", gradetotal-min(lowestgradelisty.append(gradeforlisty)/gradecount))
elif (Drop=="no"):
print("the averages of the grades enetered is", gradetotal/gradecount)
gradecount=0
studentcount=1
main()
Here's a function that does what it sounds like you wanted to ask about. It removes the smallest grade and returns the new average.
def avgExceptLowest(listofgrades):
# find minimum value
mingrade = min(listofgrades)
# remove first value matching the minimum
newgradelist = listofgrades.remove(mingrade)
# return the average of of the new list
return sum(newgradelist) / len(newgradelist)
A number of notes on your code:
The indentation of the code in your question is wrong. Fixing it may solve some of your problems if that's how it appears in your python file.
In Python the convention is to never capitalize a variable, and that's making your highlighting come out wrong.
If you code this correctly, you won't need any tracking variables like studentcount or gradecount. Check out Python's list of built-in functions and use things like len(lowestgradelisty) and loops like for i in range(0, numberofstudents): instead to keep your place as you execute.
Okay so I'm very new to the programming world and have written a few really basic programs, hence why my code is a bit messy. So the problem i have been given is a teacher needs help with asigning tasks to her students. She randomly gives the students their numbers. Students then enter their number into the program and then the program tells them if they have drawn the short straw or not. The program must be able to be run depending on how many students are in the class and this is where i am stuck, I can't find a way to run the program depending on how many students are in the class. Here is my code
import random
print("Welcome to the Short Straw Game")
print("This first part is for teachers only")
print("")
numstudents = int(input("How many students are in your class: "))
task = input("What is the task: ")
num1 = random.randint(0, numstudents)
count = numstudents
print("The part is for students") #Trying to get this part to run again depending on number of students in the class
studentname = input("What is your name:")
studentnumber = int(input("What is the number your teacher gave to you: "))
if studentnumber == num1:
print("Sorry", studentname, "but you drew the short straw and you have to", task,)
else:
print("Congratulations", studentname, "You didn't draw the short straw")
count -= 1
print("There is {0} starws left to go, good luck next student".format(count))
Read up on for loops.
Simply put, wrap the rest of your code in one:
# ...
print("The part is for students")
for i in range(numstudents):
studentname = input("What is your name:")
#...
Also, welcome to the world of programming! :) Good luck and have fun!
Can you tell me a best script / program that will pull a winner at random.
These are all entrants to a competition and one winner needs to be chosen randomly.
The data in Excel sheet. I want to run the script against excel.
The following assumes your list of entrants is in a range named "Entrants". Naturally, the usual caveats about system-generated random numbers not exactly being random apply - should be fine for local/small scale fun competition, probably not the solution for a national lottery.
Sub PickWinner()
Dim winner As String
winner = Range("Entrants").Cells(Int(Rnd() * (Range("Entrants").Count) + 1), 1)
Debug.Print winner
End Sub
save as CSV then
in python:
import random
fd = open(csv_file)
lines = fd.readlines()
line_num = random.randrange(0,len(lines)-1)
print 'winner: ', lines[line_num]