It wont print out the code at the bottom on the program - python

For some reason the print command at the bottom is not printing out it is just looping no matter how I put indentation as well.
result_list = []
print("Welcome to Speed Cameras")
while 1:
result_list.append(input("New Reading: "))
if result_list == "END":
break
try:
max_speed = max(result_list)
min_speed = min(result_list)
avg_speed = len(result_list) / len(result_list)
print("Max is:", max, " MPH:")
print("Min is:", min, " MPH")
print("Avg is", avg_speed, "MPH")
finally:
print("Thanks For Submitting")

You have 2 issues and both are here
if result_list == "END":
break
result_list is a list so it will never be equal to a string, instead you could check if the last item is END like this result_list[-1] == "END"
the second problem you have is indentation, your break is not in the if statement but in the while loop, but this doesn't seem to be the case with your error, so i think you copied your code into the question with an error

Here is the code would work:
result_list = []
print("Welcome to Speed Cameras")
while 1:
# you need test the input first before append it to the list and not test the list
inp = input("New Reading: ")
if inp == "END":
break
else:
result_list.append(float(inp)) # turn your input into a number before appending
try:
max_speed = max(result_list)
min_speed = min(result_list)
# len(result_list) / len(result_list) make no sense, use sum()
avg_speed = sum(result_list) / len(result_list)
print("Max is:", max_speed, " MPH:") # your variable name was wrong here
print("Min is:", min_speed, " MPH") # your variable name was wrong here
print("Avg is", avg_speed, "MPH")
# since you try, you should do something when you don't pass the try
# 1 there is no input at all
# 2 the input need to be numbers
except:
print('at least one speed input is needed, or please make sure your input to be a number')
finally:
print("Thanks For Submitting")
A few mistakes:
Test the input instead of the list, and then append it to the list
Need to turn input into number
Average speed formula need to be fixed
Don't forget except in try-except-finally
Wrong variable names inside print()
Please reading your own code a few time before post it for help. Some mistakes like variable names and avg-speed formula, are easy to identify.
Anyway hope this would help.

Related

I want to make an calculator for average but i'm facing some issues

I want to make an calculator for average but i'm facing some issues. I want the numbers entered by the users come as a print statement but it is just throwing the last entered value.Here is my code.
numlist = list()
while True:
inp = input(f"Enter a number, (Enter done to begin calculation): ")
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f"The Entered numbers are: ", inp)
print(f"average is = ", average)
Solution
we can print the list
numlist = list()
while True:
inp = input(f"Enter a number, (Enter done to begin calculation): ")
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f"The Entered numbers are: {numlist}")
print(f"average is = ", average)
As I understand, you want to print all the user inputs, however, as I see in your code, you are printing just a value but not the storing list, try to change your code to print(f"The Entered numbers are: ", numlist)
You are telling the user that their entered numbers are the last thing they typed in input, which will always be "done" because that is what breaks out of the loop. If you want to print the entered numbers; print numlist instead of inp.

My code freezes and stops, what's wrong with it?

I'm new to python so don't be surprised it if is something really basic, but i've been trying to write this code that asks math questions and then saves the scores in order to show them again at the start of the loop, but it doesn't save the scores. what should i change?
this is the code
scores = []
names = []
while True:
f = open("highscore.txt", "r")
for line in f:
line = line.strip("\n")
line = line.split(" ")
names.append(line[0])
scores.append(int(line[1]))
print(f.read())
for pos in range(len(names)) :
print(pos + 1, names[pos], scores[pos])
f.close()
score = 0
print("hello, welcome to maths game")
print("\nQuestion 1: what is 2 x 2 x 2?")
answer = int(input("your answer >"))
if answer == 8:
print("correct")
score = score + 1
print("your score is ", score)
else:
print("incorrect")
print("the score is ", score)
print("\nQuestion 2: what is 34 x 2?")
answer = int(input("your answer >"))
if answer == 68:
print("correct")
score = score + 1
print("your score is", score)
else:
print("incorrect")
print("the score is", score)
name = input("what is your name?")
position = 0
for compare_score in scores :
if score < compare_score:
position = position + 1
scores.insert(position, score)
names.insert(position, name)
scores = scores[:5]
names = names[:5]
f = open("highscore.txt", "w")
for pos in range (len(names)):
f.write(names[pos] + " " + scores[pos])
it doesn't give any kind of error message, just loops back and doesn't save the names, neither the scores
You have a for-loop on scores that adds a new item to the scores list at each iteration. The for-loop will never reach the end of the list because there is always 'one more'.
Alain T.'s answer has already stated the root cause that you experienced. The loop never stops which appears to you as "freezing" since there are no outputs or indicators that you (as a user/developer) see that the loop still runs. So actually nothing freezes here .. it just runs forever.
For that reason I wanted to add a short note how to drill down the problem your own the next times..
Keyword here is clearly: debugging.
Debugging means: "finding out what your code does while being executed"
A very simple but (at least for small programs) quite effective approach is using one or more print() statements. These can be used to display the value of variables, the property of an object or just some statement like print("I am before the loop") to know where execution runs/stops..
A possible would be: (look at the print statements)
while True:
print("in while") #<-- this one
...
print("before loop") #<-- this one
for compare_score in scores :
print("in loop") #<-- this one repeats....
if score < compare_score:
position = position + 1
scores.insert(position, score)
names.insert(position, name)
scores = scores[:5]
names = names[:5]
print("After loop") #<-- never see this one
f = open("highscore.txt", "w")
for pos in range (len(names)):
f.write(names[pos] + " " + scores[pos])
Running your program again should print out:
in while
before loop
in loop
in loop
in loop
in loop
in loop
in loop
in loop
...
and so on... So what you know now is:
Everything before the loop at least executed
The loop runs forever .
So now it would be time to dig a little deeper inside the loop.
Most interesting would be to examine the variable on which the loop exit
depends.
In your case that is the length of the scores list:
for compare_score in scores:
So the loop runs until there are no more scores to compare left in the scores list.
So it might be a good idea to print() the length of the list to check if and how it decreases until there are no more scores to compare.
So add something like this:
Check the two print() statements containing len(scores)
for compare_score in scores:
print("in loop")
if score < compare_score:
position = position + 1
scores.insert(position, score)
names.insert(position, name)
scores = scores[:5]
names = names[:5]
print(len(scores)) #<--- this one
# or a bit nicer as f-string:
print(f"len score: {len(scores)}") #<--- this one
print("After loop")
Both are displaying the length of the scores list.
The former one just does it a little nicer.
There is a lot more to debugging. Many tools like VSCode, Pycharm, etc. support a lot more sophisticated methodologies to step through code, set breakpoints, inspect objects and variables ..
But for small ans simple projects and when the focus is on learning, instant feedback and repeating. At least to my mind. Print() debugging gives you a lot of insight in a very easy and simple manner.
Oh, and if you read until here:
"Welcome to the community" Just jokin', welcome !! ;)"

changing data from printing line by line to a list (in a text file)

I'm using python, idle version 3.4.2
My code when it prints, print 3 scores per name but they print like this:
Maya: 3
Maya:2
Maya: 4
I was wondering if there was any way to get it to print like this in a list/dictionary so i can call upon the scores later for sorting
Maya = [3,2,4]
Here is my code.
students_names = []
import random #import module
print("What is your name?") #prints writing in brackets
name = input().title() #Capitalizes the first letter of the word inputted
students_names.append(name)
print("What class are you in? (Enter 1, 2 or 3)") #asks the user to input a number
while True:
try:
class_number = int(input()) #asks for an integer input from user
except ValueError:
print("Sorry, I didn't understand that, please try again") #print statement
continue
if class_number > 3: #if input is more than 3
print("SORRY but that class isn't recognised, try again") #print statement
continue
else:
print ("Hello,", name, "from class", class_number, "welcome to my quiz") #prints writing in brackets and anything saved in the variable "name" and "class_number"
break #break out of loop
score = 0 #sets the variable "score" to zero
question = 0 # sets the variable "question" to zero
print(class_number)
while question < 3:#If questions (intitally set to 0) is smaller than 10, carry out this function
question +=1 # add one to the value of "question"
maths = random.randint(1,3) #randomly generate a number from 1-3 and store as "maths"
num1 = random.randint(1,10)#randomly generate an integer from 1-10 and store as "num1"
num2 = random.randint(1,10)#randomly generate a second integer from 1-10 and store as "num2"
if maths == 1: #if the number generated is 1
print(num1, "+", num2) #prints num1 + num2
ans = num1 + num2 #sets "ans" to equal the value of num1 added to num2
elif maths == 2: #if the number generated is 1
print(num1, "*", num2) #print num1 multiplied by num2
ans = num1 * num2 #sets "ans" to equal the value of num1 multiplied by num2
else: #else run this part of code
print(num1, "-", num2) #print num1 subtracted by num2
ans = num1 - num2 #sets "ans" to equal the value of num1 subtracted by num2
while True:
try:
user_ans = int(input()) #user inputs answer to question
except ValueError: #runs when the user input is no an integer
print ("SORRY but that answer isn't recognised, try again")
else:
break
if user_ans == ans:
score+=1
print("Well done, you are CORRECT")
else:
print("SORRY, you are INCORRECT") #print writing in brackets
print("The correct answer was", ans)
if score == 10: #run this part of code if "score" equals 10
print("fantastic", name, "you got full marks!")#print statement and name
elif score >= 6: #run this part of code if "score" is larger than or equal to 6
print("well done, there's some improvement to be done here though", name, "you got", score, "/10")# then print statement and score
elif score <=5: #run this part of code if "score" is smaller than or equal to 5
print("hmm, maybe some more practise would be beneficial", name, "you got", score, "/10") #then print statement and score
class_number = str(class_number) + ".txt" #this adds '.txt' to the end of the file (therefore creating a text file) so it can be used to create a file under the name of the class
file = open(class_number, 'a') #opens the file in 'append' mode so you don't delete all the information
file.write(str(students_names))
file.write(str(name + " : ")) #writes the name and ":" to file
file.write(str(score)) #writes the score to file
file.write('\n')#writes the score to the file
file.close()#safely closes the file to save the information
Sure simply add the score values foreach person to a new dictionary.
name_dict = {}
if name in name_dict:
name_dict[name].append(new_score)
else:
name_dict[name] = [new_score]
It is a little bit hard to follow up on your code. Therefore I was not completely able to integrate it.
Ok, I think I get what you're looking for. But to simplify my answer to that, we first need to simplify your example. A good way to do so, is to cut your code into functions:
How to store your results?
First we'll look at where you need help on, which is the last bit of your code, which fits in a function we'll call store_results():
def store_results(...):
class_number = str(class_number) + ".txt" # this adds '.txt' to the end of the file (therefore creating a text file) so it can be used to create a file under the name of the class
file = open(class_number, 'a') # opens the file in 'append' mode so you don't delete all the information
file.write(str(students_names))
file.write(str(name + " : ")) # writes the name and ":" to file
file.write(str(score)) # writes the score to file
file.write('\n') # writes the score to the file
file.close() # safely closes the file to save the information
I used here ... for the arguments of the function, which is not python, to have a thought about it. What arguments does that function needs to work as is?
class_number: the class the student answering the QA is in
name: the score the student had on the QA
student_names
What you're doing here, is that when you run that code, you're appending name
into student_names, which will always contain one, and only one name. So when
you write file.write(str(students_names)), for a user whose name is John, you'll
end up writing:
...
['John']
John : 5
...
Which is not something I believe you're expecting. You actually do not need that list at all.
So as a first update, you should do:
def store_results(class_number, name, score):
class_file = "{}.txt".format(class_number) # this adds '.txt' to the end of the file (therefore creating a text file) so it can be used to create a file under the name of the class
with open(class_file, 'a') as f: # opens the file in 'append' mode so you don't delete all the information
f.write("{}: {}\n".format(name, score) # outputs the user's score to the file
Other changes in that snippet are:
- you shall not use file as a variable as it already exists as a global type, and using it in
your code is considered bad practice called "shadowing" which can lead to hard to find bugs
(not in this case, but if you don't take the good habits now, it's bite you in a future code).
- you shall use with open() as f: construct instead of opening and closing the file manually,
because in your existing code, if there's an exception thrown between open and close your
file won't be properly closed, ending up in possible lost writes.
- you shall use format strings instead of direct string concatenation, which makes the code
easier to read and to modify.
Now, that being said, you'll still have your issue having the result of each test taken
by an user being shown as:
John: 2
John: 4
John: 5
The right way to solve this is to not use "blinded" appending to the file, but instead
use the file as some sort of very basic database. The most simple option would be to
write your scores within a JSON file, which is syntactically compatible with python
(pretty useful for manual testing):
import os
import json
def store_results(class_number, name, score):
# this adds '.json' to the end of the file (therefore creating a json file)
class_file = "{}.json".format(class_number)
# first step: load the existing data
# first test if the file exists, and if not, use an empty score dictionary
if not os.path.exists(class_file):
scores = {}
# otherwise populate the dictionary
else:
# open as read only, because we just want the data out of it
with open(class_file, 'r') as f:
# load contents of the json file "f" as object "scores"
scores = json.load(f)
# second step: update the data
scores.setdefault(name, []).append(score)
# third step: update the file
# use 'w' when opening the file to overwrite all data within it
with open(class_file, 'w') as f:
# dump object "scores" within file "f"
json.dump(scores, f)
Within this code, I used a trick to do insertion of the score in one line:
scores.setdefault(name, []).append(score)
which is equivalent to:
# if the user's "name" is not already in the dictionary
if name not in scores.keys():
# add it as a new key containing an empty list
scores[name] = []
# append the "score" to the list indexed by the user's "name"
scores[name].append(score)
Then the results within a file would look like:
{"John":[3,5,10],"Jane":[2],"Bob":[1,0,2]}
To make the output file more readable you can change the json.dump line into:
json.dump(scores, f, sort_keys=True, indent=4, separators=(',', ': '))
which will output:
{
"Bob": [
1,
0,
2
],
"Jane": [
2
],
"John": [
3,
5,
10
]
}
How to run the QA?
Finally you want to create another function that handles the QA process, within which
you call the function we just defined
# add the following import at the start of your script if you're running python2 and not python3
from __future__ import print_function
def run_qa():
print("What is your name?") # prints writing in brackets
name = input().title() # Capitalizes the first letter of the word inputted
print("What class are you in? (Enter 1, 2 or 3)") # asks the user to input a number
while True:
try:
class_number = int(input()) # asks for an integer input from user
except ValueError:
print("Sorry, I didn't understand that, please try again") # print statement
continue
if class_number > 3: # if input is more than 3
print("SORRY but that class isn't recognised, try again") # print statement
continue
else:
break # break out of loop
# prints writing in brackets and anything saved in the variables "name" and "class_number"
print ("Hello, {} from class {} welcome to my quiz".format(name, class_number))
score = 0 # sets the variable "score" to zero
question = 0 # sets the variable "question" to zero
while question < 3: # If questions (initially set to 0) is smaller than 10, carry out this function
question += 1 # add one to the value of "question"
maths = random.randint(1,3) # randomly generate a number from 1-3 and store as "maths"
num1 = random.randint(1,10) # randomly generate an integer from 1-10 and store as "num1"
num2 = random.randint(1,10) # randomly generate a second integer from 1-10 and store as "num2"
if maths == 1: # if the number generated is 1
print("{} + {} = ?".format(num1, num2)) # prints num1 + num2
ans = num1 + num2 # sets "ans" to equal the value of num1 added to num2
elif maths == 2: # if the number generated is 1
print("{} * {} = ?".format(num1, num2)) # print num1 multiplied by num2
ans = num1 * num2 # sets "ans" to equal the value of num1 multiplied by num2
else: # else run this part of code
print("{} - {} = ?".format(num1, num2)) # print num1 subtracted by num2
ans = num1 - num2 # sets "ans" to equal the value of num1 subtracted by num2
while True:
try:
# print a nice little prompt for the user to enter his answer
print("> ", end="")
user_ans = int(input()) # user inputs answer to question
# if an exception is raised by "int()" the break is not being called
# here you achieve the same as a single line, as you're doing in two
# lines with your try/except/else clause, making your code more readable.
break
except ValueError: # runs when the user input is no an integer
print ("SORRY but that answer isn't recognised, try again")
if user_ans == ans:
score += 1
print("Well done, you are CORRECT")
else:
print("SORRY, you are INCORRECT") # print writing in brackets
print("The correct answer was {}".format(ans))
if score == 10: # run this part of code if "score" equals 10
print("Fantastic {}, you got full marks!".format(name))# print statement and name
elif score >= 6: # run this part of code if "score" is larger than or equal to 6
print("Well done, there's some improvement to be done here, though {} you got {}/10".format(name, score))# then print statement and score
elif score <=5: # run this part of code if "score" is smaller than or equal to 5
print("hmm, maybe some more practice would be beneficial, {}, you got {}/10".format(name, score)) # then print statement and score
# return the results
return class_number, name, score
Finally, to call your code, you just need to add the following at the end of your script:
if __name__ == "__main__":
class_number, name, score = run_qa()
store_results(class_number, name, score):
the reason for the if statement is to make it possible to later include your code as
a module in another module without running it, which is considered good practice!
as another improvement I'd avoid repeating the same code several times to check input
from the user, but use a function instead:
def get_integer_input(maxval=None):
while True:
try:
# print a nice prompt
print("> ", eol="")
i = int(input()) # asks for an integer input from user
if maxval:
if i >= maxval:
continue
print("Sorry, input shall be inferior than {}, try again".format(maxval))
break
except ValueError:
print("Sorry, I didn't understand that, please try again") # print statement
return i
Then in your code you use it that way:
...
class_number = get_integer_input(maxval=3)
...
BTW, as an improvement, I'd actually split the run_qa in two functions: one that
generates the questions, and the other that does the interactive process.
so that you would do:
if __name__ == "__main__":
questions = generate_qa()
class_number, name, score = run_qa(questions)
store_results(class_number, name, score)
with generate_qa() being something like:
def generate_qa():
questions = []
while len(questions) < 3: # add a question until we have three generated
op = random.randint(0,2) # randomly generate a number from 1-3 and store as "maths"
num1 = random.randint(1,10) # randomly generate an integer from 1-10 and store as "num1"
num2 = random.randint(1,10) # randomly generate a second integer from 1-10 and store as "num2"
questions.append( (op, num1, num2) )
return questions
and then:
def run_qa(questions):
print("What is your name?") # prints writing in brackets
name = input().title() # Capitalizes the first letter of the word inputted
print("What class are you in? (Enter 1, 2 or 3)") # asks the user to input a number
class_number = get_integer_input(maxval=3)
# prints writing in brackets and anything saved in the variables "name" and "class_number"
print ("Hello, {} from class {} welcome to my quiz".format(name, class_number))
score = 0 # sets the variable "score" to zero
for op, left, right in questions:
if op == 0: # if the number generated is 0
op("{} + {} = ?".format(left, right)) # prints 'left' + 'right'
ans = left + right # sets "ans" to equal the value of num1 added to 'right'
elif op == 1: # if the number generated is 1
print("{} * {} = ?".format(left, right)) # print 'left' multiplied by 'right'
ans = left * right # sets "ans" to equal the value of num1 multiplied by 'right'
else: # the only possible value is: op == 2
print("{} - {} = ?".format(left, right)) # print 'left' subtracted by 'right'
ans = left - right # sets "ans" to equal the value of num1 subtracted by 'right'
user_ans = get_integer_input()
if user_ans == ans:
score += 1
print("Well done, you are CORRECT")
else:
print("SORRY, you are INCORRECT") # print writing in brackets
print("The correct answer was {}".format(ans))
if score == 10: # run this part of code if "score" equals 10
print("Fantastic {}, you got full marks!".format(name))# print statement and name
elif score >= 6: # run this part of code if "score" is larger than or equal to 6
print("Well done, there's some improvement to be done here, though {} you got {}/10".format(name, score))# then print statement and score
elif score <=5: # run this part of code if "score" is smaller than or equal to 5
print("hmm, maybe some more practise would be beneficial, {}, you got {}/10".format(name, score)) # then print statement and score
return class_number, name, score
Finally, a last improvement that could be done to your code is to use a dict containing the operators:
import operator
operations = {
'+': operator.add,
'*': operator.mul,
'-': operator.sub
}
and then you'd simplify run_qa as follows:
def run_qa(questions):
print("What is your name?") # prints writing in brackets
name = input().title() # Capitalizes the first letter of the word inputted
print("What class are you in? (Enter 1, 2 or 3)") # asks the user to input a number
class_number = get_integer_input(maxval=3)
# prints writing in brackets and anything saved in the variables "name" and "class_number"
print ("Hello, {} from class {} welcome to my quiz".format(name, class_number))
score = 0 # sets the variable "score" to zero
for op, left, right in questions:
# convert from index value into symbol (the "list()" is a needed trick for python3
op = list(operations.keys())[op]
print("{} {} {} = ?".format(left, op, right))
# calculate the operation with operator 'op' using 'left' and 'right'
ans = operations[op](left, right)
user_ans = get_integer_input()
if user_ans == ans:
score += 1
print("Well done, you are CORRECT")
else:
print("SORRY, you are INCORRECT") # print writing in brackets
print("The correct answer was {}".format(ans))
if score == 10: # run this part of code if "score" equals 10
print("Fantastic {}, you got full marks!".format(name))# print statement and name
elif score >= 6: # run this part of code if "score" is larger than or equal to 6
print("Well done, there's some improvement to be done here, though {} you got {}/10".format(name, score))# then print statement and score
elif score <=5: # run this part of code if "score" is smaller than or equal to 5
print("hmm, maybe some more practice would be beneficial, {}, you got {}/10".format(name, score)) # then print statement and score
return class_number, name, score
Nota Bene: I have not tested my code locally, it's been live coding within the answer box
of stackoverflow, so there might be syntax errors and maybe minor bugs. The goal of
my answer is to emphasize what you're doing wrong and show you how to do better. So,
please do not take it "as is" to copy/paste, but read it through, understand what I'm
showing to you, and update your code with what I given you as an improvement.
Here's a full example I just tested:
# make the script both py2 and py3 compatible
from __future__ import print_function
import sys
if sys.version_info.major == 2:
input = raw_input
import operator
import random
import json
import os
def store_results(class_number, name, score):
# this adds '.json' to the end of the file (therefore creating a json file)
class_file = "{}.json".format(class_number)
# first step: load the existing data
# first test if the file exists, and if not, use an empty score dictionary
if not os.path.exists(class_file):
scores = {}
# otherwise populate the dictionary
else:
# open as read only, because we just want the data out of it
with open(class_file, 'r') as f:
# load contents of the json file "f" as object "scores"
scores = json.load(f)
# second step: update the data
scores.setdefault(name, []).append(score)
# third step: update the file
# use 'w' when opening the file to overwrite all data within it
with open(class_file, 'w') as f:
# dump object "scores" within file "f"
json.dump(scores, f, sort_keys=True, indent=4, separators=(',', ': '))
def get_integer_input(maxval=None):
while True:
try:
# print a nice prompt
print("> ", end="")
i = int(input()) # asks for an integer input from user
if maxval:
if i >= maxval:
continue
print("Sorry, input shall be inferior than {}, try again".format(maxval))
break
except ValueError:
print("Sorry, I didn't understand that, please try again") # print statement
return i
operations = {
'+': operator.add,
'*': operator.mul,
'-': operator.sub
}
def generate_qa():
questions = []
while len(questions) < 3: # add a question until we have three generated
op = random.randint(0,2) # randomly generate a number from 1-3 and store as "maths"
num1 = random.randint(1,10) # randomly generate an integer from 1-10 and store as "num1"
num2 = random.randint(1,10) # randomly generate a second integer from 1-10 and store as "num2"
questions.append( (op, num1, num2) )
return questions
def run_qa(questions):
print("What is your name?") # prints writing in brackets
name = input().title() # Capitalizes the first letter of the word inputted
print("What class are you in? (Enter 1, 2 or 3)") # asks the user to input a number
class_number = get_integer_input(maxval=3)
# prints writing in brackets and anything saved in the variables "name" and "class_number"
print ("Hello, {} from class {} welcome to my quiz".format(name, class_number))
score = 0 # sets the variable "score" to zero
for op, left, right in questions:
# convert from index value into symbol (the "list()" is a needed trick for python3
op = list(operations.keys())[op]
print("{} {} {} = ?".format(left, op, right))
# calculate the operation with operator 'op' using 'left' and 'right'
ans = operations[op](left, right)
user_ans = get_integer_input()
if user_ans == ans:
score += 1
print("Well done, you are CORRECT")
else:
print("SORRY, you are INCORRECT") # print writing in brackets
print("The correct answer was {}".format(ans))
if score == 10: # run this part of code if "score" equals 10
print("Fantastic {}, you got full marks!".format(name))# print statement and name
elif score >= 6: # run this part of code if "score" is larger than or equal to 6
print("Well done, there's some improvement to be done here, though {} you got {}/10".format(name, score))# then print statement and score
elif score <=5: # run this part of code if "score" is smaller than or equal to 5
print("hmm, maybe some more practise would be beneficial, {}, you got {}/10".format(name, score)) # then print statement and score
return class_number, name, score
if __name__ == "__main__":
questions = generate_qa()
class_number, name, score = run_qa(questions)
store_results(class_number, name, score)
HTH

Printing min and max function from input of a list

Every time I run the code I get "TypeError: 'int' object is not iterable".
So my question is: How do I print/use the min and max function at the end? So if someone let's say types 5,7,10, and -1. How do I let the user know that the highest score is 10 and the lowest score would be 5? (And then I guess organizing it from highest numbers to lowest.)
def fillList():
myList = []
return myList
studentNumber = 0
myList = []
testScore = int(input ("Please enter a test score "))
while testScore > -1:
# myList = fillList()
myList.append (testScore)
studentNumber += 1
testScore = int(input ("Please enter a test score "))
print ("")
print ("{:s} {:<5d}".format("Number of students", studentNumber))
print ("")
print ("{:s} ".format("Highest Score"))
print ("")
high = max(testScore)
print ("Lowest score")
print ("")
print ("Average score")
print ("")
print ("Scores, from highest to lowest")
print ("")
Your problem is that testScore is an integer. What else could it be? Each time through the list, you reassign it to the next integer.
If you want to, say, append them to a list, you have to actually do that:
testScores = []
while testScore > -1:
testScores.append(testScore)
# rest of your code
And now it's easy:
high = max(testScores)
And, in fact, you are doing that in the edited version of your code: myList has all of the testScore values in it. So, just use it:
high = max(myList)
But really, if you think about it, it's just as easy to keep a "running max" as you go along:
high = testScore
while testScore > -1:
if testScore > high:
high = testScore
# rest of your code
You will get different behavior in the case where the user never enters any test scores (the first one will raise a TypeError about asking for the max of an empty list, the second will give you -1), but either of those is easy to change once you decide what you actually want to happen.
If all your scores are in a array.
print("The max was: ",max(array))
print("The min was: ",min(array))

python variable NameError

I am having trouble with assigning values to vars and then accessing the values. For example:
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = raw_input()
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = 100Mb # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is " + tSize + "."
Traceback returns:
Traceback (most recent call last):
File "./ranSongList.py", line 87, in <module>
print "\nYou want to create a random song list that is " + tSize + "."
NameError: name 'tSize' is not defined
I have read up on python variables and they do not need to be declared so I am thinking they can be created and used on the fly, no? If so I am not quite sure what the traceback is trying to tell me.
By the way, it appears as though python does not offer 'case' capabilities, so if anyone has any suggestions how to better offer users lists from which to choose options and assign var values I would appreciate reading them. Eventually when time allows I will learn Tkinter and port to GUI.
Your if statements are checking for int values. raw_input returns a string. Change the following line:
tSizeAns = raw_input()
to
tSizeAns = int(raw_input())
This should do it:
#!/usr/local/cpython-2.7/bin/python
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = int(raw_input())
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is {}.".format(tSize)
BTW, in case you're open to moving to Python 3.x, the differences are slight:
#!/usr/local/cpython-3.3/bin/python
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print("\nHow much space should the random song list occupy?\n")
print("1. 100Mb")
print("2. 250Mb\n")
tSizeAns = int(input())
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print("\nYou want to create a random song list that is {}.".format(tSize))
HTH
In addition to the missing quotes around 100Mb in the last else, you also want to quote the constants in your if-statements if tSizeAns == "1":, because raw_input returns a string, which in comparison with an integer will always return false.
However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. Please check your posted code. I cannot reproduce the error message.
Also if ... elif ... else in the way you use it is basically equivalent to a case or switch in other languages and is neither less readable nor much longer. It is fine to use here. One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup:
tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns]
This however does only work as long as tSizeAns is guaranteed to be in the range of tSize. Otherwise you would have to either catch the KeyError exception or use a defaultdict:
lookup = {"1": "100Mb", "2": "200Mb"}
try:
tSize = lookup[tSizeAns]
except KeyError:
tSize = "100Mb"
or
from collections import defaultdict
[...]
lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"})
tSize = lookup[tSizeAns]
In your case I think these methods are not justified for two values. However you could use the dictionary to construct the initial output at the same time.
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
I would approach it like this:
sizes = [100, 250]
print "How much space should the random song list occupy?"
print '\n'.join("{0}. {1}Mb".format(n, s)
for n, s in enumerate(sizes, 1)) # present choices
choice = int(raw_input("Enter choice:")) # throws error if not int
size = sizes[0] # safe starting choice
if choice in range(2, len(sizes) + 1):
size = sizes[choice - 1] # note index offset from choice
print "You want to create a random song list that is {0}Mb.".format(size)
You could also loop until you get an acceptable answer and cover yourself in case of error:
choice = 0
while choice not in range(1, len(sizes) + 1): # loop
try: # guard against error
choice = int(raw_input(...))
except ValueError: # couldn't make an int
print "Please enter a number"
choice = 0
size = sizes[choice - 1] # now definitely valid
You forgot a few quotations:
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = raw_input()
if tSizeAns == "1":
tSize = "100Mb"
elif tSizeAns == "2":
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is " + tSize + "."

Categories

Resources