I've set up the following for loop to accept 5 test scores. I want the loop to prompt the user to enter 5 different scores. Now I could do this by writing the input "Please enter your next test score", but I'd rather have each inputted score prompt for its associated number.
So, for the first input, I'd like it to display "Please enter your score for test 1", and then for the second score, display "Please enter your score for test 2". When I try to run this loop, I get the following error:
Traceback (most recent call last):
File "C:/Python32/Assignment 7.2", line 35, in <module>
main()
File "C:/Python32/Assignment 7.2", line 30, in main
scores = input_scores()
File "C:/Python32/Assignment 7.2", line 5, in input_scores
score = int(input('Please enter your score for test', y,' : '))
TypeError: input expected at most 1 arguments, got 3
Here's the code
def input_scores():
scores = []
y = 1
for num in range(5):
score = int(input('Please enter your score for test', y, ': '))
while score < 0 or score > 100:
print('Error --- all test scores must be between 0 and 100 points')
score = int(input('Please try again: '))
scores.append(score)
y += 1
return scores
A simple (and correct!) way to write what you want:
score = int(input('Please enter your score for test ' + str(y) + ': '))
Because input does only want one argument and you are providing three, expecting it to magically join them together :-)
What you need to do is build your three-part string into that one argument, such as with:
input("Please enter your score for test %d: " % y)
This is how Python does sprintf-type string construction. By way of example,
"%d / %d = %d" % (42, 7, 42/7)
is a way to take those three expressions and turn them into the one string "42 / 7 = 6".
See here for a description of how this works. You can also use the more flexible method shown here, which could be used as follows:
input("Please enter your score for test {0}: ".format(y))
Related
I am trying to get the first while True loop to ask a question. If answered with a 'y' for yes, it continues to the second while test_score != 999: loop. If anything other than a y is entered, it should stop.
Once the second while loop runs, the user enters their test scores and enters 'end' when they are finished and the code executes, the first "while True" loop should ask if the user would like to enter another set of test scores. If 'y' is entered, then it completes the process all over again. I know the second one is a nested while loop. However, I have indented it, in PyCharm, per python indentation rules and it still tells me I have indentation errors and would not run the program. That is the reason they are both lined up underneath each other, below. With that said, when I run it as it is listed below, it gives the following answer:
Enter test scores
Enter end to end the input
==========================
Get entries for another set of scores? y
Enter your information below
Get entries for another set of scores? n
((When I type in 'n' for no, it shows the following:))
Thank you for using the Test Scores application. Goodbye!
Enter test score: 80 (I entered this as the input)
Enter test score: 80 (I entered this as the input)
Enter test score: end (I entered this to stop the program)
==========================
Total score: 160
Average score: 80
When I answered 'y', it started a continual loop. When I answered 'n', it did give the print statement. However, it also allowed me to enter in my test scores, input end and execute the program. But, it also did not ask the user if they wanted to enter a new set of test scores. Any suggestions on where I am going wrong?
print("The Test Scores application")
print()
print("Enter test scores")
print("Enter end to end input")
print("======================")
# initialize variables
counter = 0
score_total = 0
test_score = 0
while True:
get_entries = input("Get entries for another set of scores? ")
if get_entries == 'n':
print("Thank you for using the Test Scores application. Goodbye!")
break
else:
print("Enter your information below")
continue
counter = 0
score_total = 0
test_score = 0
while test_score != 999:
test_score = input("Enter test score: ")
if test_score == 'end':
break
elif (int(test_score) >= 0) and (int(test_score) <= 100):
score_total += int(test_score)
counter += 1
elif test_score == 999:
break
else:
print("Test score must be from 0 through 100. Score discarded. Try again.")
# calculate average score
average_score = round(score_total / counter)
# format and display the result
print("======================")
print("Total Score:", score_total,
"\nAverage Score:", average_score)
The while loops should be nested to have recurring entries
print("The Test Scores application")
print()
print("Enter test scores")
print("Enter end to end input")
print("======================")
# initialize variables
counter = 0
score_total = 0
test_score = 0
while True:
get_entries = input("Get entries for another set of scores? ")
if get_entries == 'n':
print("Thank you for using the Test Scores application. Goodbye!")
break
else:
print("Enter your information below")
counter = 0
score_total = 0
test_score = 0
while test_score != 999:
test_score = input("Enter test a score: ")
if test_score == 'end':
break
elif (int(test_score) >= 0) and (int(test_score) <= 100):
score_total += int(test_score)
counter += 1
elif test_score == 999:
break
else:
print("Test score must be from 0 through 100. Score discarded. Try again.")
# calculate average score
average_score = round(score_total / counter)
# format and display the result
print("======================")
print("Total Score:", score_total,
"\nAverage Score:", average_score)
Output:
The Test Scores application
Enter test scores
Enter end to end input
======================
Get entries for another set of scores? y
Enter your information below
Enter test a score: 60
Enter test a score: 80
Enter test a score: 90
Enter test a score: 70
Enter test a score: end
======================
Total Score: 300
Average Score: 75
Get entries for another set of scores? y
Enter your information below
Enter test a score: 80
Enter test a score: 80
Enter test a score: end
======================
Total Score: 160
Average Score: 80
Get entries for another set of scores? n
Thank you for using the Test Scores application. Goodbye!
This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 3 years ago.
I'm starting out with Python after taking a class that taught us pseudocode. How could I make a validation loop to continue the function if a user inputted a decimal rather than a whole number? At its current state, I've gotten it to recognize when a user enters a number outside of the acceptable range, but if the user enters a decimal number, it crashes. Is there another validation loop that can recognize a decimal?
def main():
again = 'Y'
while again == 'y' or again == 'Y':
strength_score = int(input('Please enter a strength score between 1 and 30: '))
# validation loop
while strength_score < 1 or strength_score > 30 :
print ()
print ('Error, invalid selection!')
strength_score = int(input('Please enter a whole (non-decmial) number between 1 and 30: '))
# calculations
capacity = (strength_score * 15)
push = (capacity * 2)
encumbered = (strength_score * 5)
encumbered_heavily = (strength_score * 10)
# show results
print ()
print ('Your carrying capacity is' , capacity, 'pounds.')
print ('Your push/drag/lift limit is' , push, 'pounds.')
print ('You are encumbered when holding' , encumbered, 'pounds.')
print ('You are heavyily encumbered when holding' , encumbered_heavily, 'pounds.')
print ()
# technically, any response other than Y or y would result in an exit.
again = input('Would you like to try another number? Y or N: ')
print ()
else:
exit()
main()
Depending on what you want the behavior to be:
If you want to accept non-integer numbers, just use float(input()). If you want to accept them but turn them into integers, use int(float(input())) to truncate or round(float(input())) to round to the nearest integer.
If you want to print an error message and prompt for a new number, use a try-catch block:
try:
strength_score = int(input('Please enter a strength score between 1 and 30: '))
except ValueError:
again = input("Invalid input, try again? Y / N")
continue # skip the rest of the loop
That is because you have strength_score as an int, and not a float.
Try changing
strength_score = int(input('Please enter a strength score between 1 and 30: '))
to
strength_score = float(input('Please enter a strength score between 1 and 30: '))
Tested with 0.1 and 0.0001 and both are working properly.
desired outcome:
Enter a test score (-99 to exit): 55
Enter a test score (-99 to exit): 77
Enter a test score (-99 to exit): 88
Enter a test score (-99 to exit): 24
Enter a test score (-99 to exit): 45
Enter a test score (-99 to exit): -99
55 77 88 24 45
P P P F F
Process finished with exit code 0
The code so far: (works except for Pass fail assignment)
Python Program to ask user to input scores that are added to a list called scores. Then prints under that score P for Pass F for fail.
scores = [] #list is initialized
while True:
score = int(input("Enter a test score (-99 to exit): "))
if score == -99:
break
scores.append(score)
def print_scores(): #accepts the list and prints each score separated by a space
for item in scores:
print(item, end = " ") # or 'print item,'
print_scores() # print output
def set_grades(): #function determines whether pass or fail
for grade in scores:
if score >= 50:
print("P")
else:
print("F")
print(set_grades)
You're thinking along the right lines, but you need to run through your program from the top and make sure that you're getting your reasoning right.
Firstly, you've written the program to print out all the scores before you get to checking if they're passes, so you'll get a list of numbers and then a list of P/F. These need to happen together to display properly.
Also, make sure that you keep track of what variable is what; in your last function, you attempt to use 'score', which doesn't exist anymore.
Finally, I'm not sure what exactly you're asking with %d or %s, but you may be looking for named arguments with format(), which are shown below.
scores = [] #list is initialized
while True:
score = int(input("Enter a test score (-99 to exit): "))
if score == -99:
break
scores.append(score)
for item in scores:
if item >= 50:
mark = 'P'
else:
mark = 'F'
print('{0} {1}'.format(item, mark))
I believe this is what you're looking for.
my code is supposed to make sure (for this section) that each inputted number is an integer and is only one digit long, however I am not sure how to make sure that each number is only one digit while it is in an array.
amount = 0
code = [0,0,0,0,0,0,0]
code[amount] = int(input("enter the first number"))
amount = amount + 1
while amount < 7 and amount != 0:
code[amount] = int(input("please enter the next number"))
amount = amount + 1
amount = 0
if len(code[amount])>1:
print("you have entered a number that is more than one digit")
elif len(code[amount])==1:
print("")
else:
print("invalid input")
my expected result would be an error when you enter any number that is longer than one digit, however this error is returned instead.
Traceback (most recent call last):
File "C:\Users\User\Desktop\task 1 full code.py", line 9, in <module>
if len(code[amount])>1:
TypeError: object of type 'int' has no len()
You can check at input time (and loop to repeat the input until the value is okay):
while amount < 7 and amount != 0:
while True: # until a valid digit is given
code[amount] = int(raw_input("please enter the next number"))
if 0 <= code[amount] <= 9:
break
print "Please enter only single digits!"
amount = amount + 1
Or you can check later:
if not all(0 <= c <= 9 for c in code):
print "Not all values are only digits!"
the program i have writen is meant to take the users input which is a integer then times it with the range of 1-10 so userinput x 1-10. however when i run my program an error occurs saying 'bool' is not iterable..
im new to coding so please go easy <3
Heres my code:
And heres the error:
Traceback (most recent call last):
File "", line 1, in
loop()
File "C:/Users/chemg/AppData/Local/Programs/Python/Python35-32/loop1.py", line 6, in loop
for numbers in number in range(1,10):
TypeError: 'bool' object is not iterable
this error occurs after the user enters a value
Let's break this line up
for numbers in number in range(1,10):
range(1,10) => 1..10
number in range(1,10) => True/False, but what is 'number'? 0? So, 'False'
numbers in number in range(1,10) => Error!!! There are no 'numbers' in 'False'
Maybe you meant to do this?
for number in range(1,10):
# do something
You also have an error later where you are trying to print 4 things, but only specified 3 in the format().
print("Here it is {0}:\n {1} x {2} = {3}".format(number,add,name))
And you put name as {2}, so that would have printed something like
Here it is 1: 7 x James = ??
So, you can fix that by
add=int(input("Enter number and i will display the times table: "))
for number in range(1,10):
print("{0} x {1} = {2}".format(add, number, add*number))
You also probably don't want to store the result of the multiplication into 'add' because for each iteration of the loop, 'add' will be the value from the previous iteration rather than what the user entered which doesn't produce a multiplication table. In fact all your results will be 0 for the below:
for number in range(10):
print('{0} * {1}'.format(add, number))
add = add*number
print("Result:{0}".format(add))
Test in your cli with range(1,10) as you had in your code originally so it starts with 1 instead of 0 and you will see the results aren't a multiplication table:
for number in range(1,10):
print('{0} * {1}'.format(add, number))
add = add * number
print(add)
Here is a complete version with all the changes:
def loop():
name=input("Enter name: ").capitalize()
print("Hey {0}".format(name))
add=int(input("Enter number and i will display the times table: "))
for number in range(1,10):
product = add * number
print("Here it is {0}:\n {1} x {2} = {3}".format(name,add,number,product))
In your for loop number is a single variable ,not a iterable ,and it is an invalid syntax , so replace ur code with the below and
No need to write number=0,
def loop():
name=input("Enter name: ").capitalize()
print("Hey {0}".format(name))
add=int(input("Enter number and i will display the times table: "))
for number in range(1,11): # last value is not included so to iterate up to 10 write 11
product= add*number
print(" {1} x {2} = {3} \n ".format(number,add,product))
Ok i seemed to have done it. its probably what the answers put, but this is what i came up with
def loop():
numbers=int(input("Enter a number: "))
add=numbers
for number in range(1,900000000000):
numbers= add*number
print("{0} x {2} = {1}".format(add,numbers,number))
number in range(1,10) is being evaluated to False (because 0 isn't in range(1,10), so for numbers in False is causing problems.
You probably just want for number in range(1,10):.