How do I limit inputs to only be Specific multiples in Python? - python

Currently doing a college assignment where we need to input and add 3 different scores.
The Scores must be not be less than 0 or greater than 10, and they can only be in multiples of 0.5. It's the latter part I'm having trouble with.
How do I tell the program to give an error if the input isn't a multiple of 0.5?
score1 = float(input("Please input the first score: ")
if score1 <0 or score1 >10:
score1 = float(input("Error! Scores can only be between 0 and 10.\n Please input Score 1 again: "))
elif score1

One way to do this is to use a while loop:
score1 = float(input("Please input the first score: ")
# while loop will keep asking for correct input if the input does not satisfy the requirements
while score1 <0 or score1 >10 or not (score1%0.5)== 0.0:
score1 = float(input("Error! Scores can only be between 0 and 10 and in multiples of 0.5.\n Please input Score 1 again: ")
print(score1, "passes all the tests")
or alternatively, you could raise an error statement if you'd like:
score1 = float(input("score: "))
if score1<0 or score1>10 or not (score1%0.5)==0.0:
raise BaseException("Error! the input score1 must be between 1 and 10 and a multiple of 0.5")
print(score1, "passes all the tests")

Nested if statement comes into play here. First it will check the condn is score>0 and score<10 then the next if statement of checking multiple statement comes to play. Use loop for taking input back to back until condn not met.
score = float(input("Enter score"))
if score>0 and score<10:
if (score*10)%5 == 0:
print(" Score is a Multiple of 0.5")
else:
print("Score is Not multiple of 0.5")
else:
print("Error! Scores can only be between 0 and 10")
`

Related

Limiting user from 0-100 in input function

How to create a program that limiting user in input function from 0-100 only. We need to ask user to for their grade in 4 tests after that if the user does not have taken any of those test it shows INC.
while True:
score = float(input('Enter your score: '))
if not 0 <= score <= 100:
continue
else:
break
while True:
score = input('Enter your score: ')
if not (0 <= score <= 100):
continue
else:
break

Checking for an exception and other values in an if statement

Let's say I want to check the avarage of 2 test scores. I don't want the user to input any letters or a value less than 0.
What comes to my mind is this code:
while True:
try:
score1 = float(input('Enter the your 1st score: '))
score2 = float(input('Enter the your 2nd score: '))
except:
print('Invalid value, try again...')
continue
if (score1 < 0 or score2 < 0):
print('Invalid value, try again...')
continue
print(f'Your average is {(score1 + score2) / 2}')
break
Is there a way to check for an exception and if a score is less than 0 in the same if statement?
This is not very efficient; but you can do this after loading score2 in the try:
score2 = float(input('Enter the your 2nd score: '))
assert score1 >= 0 and score2 >= 0
except:
...
and get rid of the if statement.
In Python, the way to check for an exception is by using a try:except: block, not by using an 'if' statement.
So the answer to this question:
"Is there a way of checking for an exception with an 'if' statement?" is "no."
Your question was a little different. You asked whether you could (1) check for an exception and (2) evaluate another expression "in the same 'if' statement." Since you can't even do the first thing in an 'if' statement, you clearly can't do both.

Two while loops that run simultaneously

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!

using %s, %d to assign pass/fail to grade determination based on user input score (python)

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.

How do I sort a list if there is an integer tied to a string by the smallest number?

I am quite new to programming and I am trying to make a leader board for a number guessing game in python 3 where you have the score then the name sorted by the lowest score first:
leaderboard_list = [0,0,0,0,0]
while True:
leaderboard_list.sort()
print("This in the leaderboard",leaderboard_list)
name = ("What is your name?")
while user_num != answer:
user_num = input("Guess a number: ")
if user_num = answer:
print("YAY")
else:
score = score + 1
leaderboard_list.append(score+" "+name)
I have tried many different ways and have figured out that if you get a score of 11, then it will say you are higher in the leader board than someone with a score of 2, which it shouldn't. I have also tried to change the score to an int type however you can't have an int and a string in the same list. How can I get around this?
Dictionary solution
dictionaries are well suited for the task of storing the scores and linking them to the user name. Dictionaries can't be directly sorted. However, there is an easy solution in this other post.
Moreover, in the OP, the name declaration is wrong, as it is not getting any value from the user. With the following code, it works perfectly. A condition for ending the while loop should added as well.
import operator
#Store the names and scores in a dictionary
leaderboard_dict = {}
#Random number
answer = 3
while True:
#Sort the dictionary elements by value
sorted_x = sorted(leaderboard_dict.items(), key=operator.itemgetter(1))
#Rewrite the leaderboard_dict
leaderboard_dict = dict(sorted_x)
print("This in the leaderboard",leaderboard_dict)
name = input("What is your name?")
#initialize score and user_num for avois crashes
user_num = -1
score = 0
while user_num != answer:
user_num = input("Guess a number: ")
if user_num is answer:
print("YAY")
else:
score += 1
leaderboard_dict[name] = score
NumPy array solution
EDIT: In case that you want to store more than one score for each player, I would user NumPy arrays, as they let you do plenty of operations, like ordering indexes by slicing and getting their numeric order, that is the request of the OP. Besides, their syntax is very understandable and Pythonic:
import numpy as np
#Random number
answer = 3
ranking = np.array([])
while True:
name = input("What is your name?")
user_num = -1
score = 1
while user_num != answer:
user_num = input("Guess a number: ")
if user_num is answer:
print("YAY")
else:
score += 1
#The first iteration the array is created
if not len(ranking):
ranking = np.array([name, score])
else:
ranking = np.vstack((ranking, [name,score]))
#Get the index order of the scores
order = np.argsort(ranking[:,1])
#Apply the obtained order to the ranking array
ranking = ranking[order]
And an example of its use:
>> run game.py
What is your name?'Sandra'
Guess a number: 3
YAY
What is your name?'Paul'
Guess a number: 6
Guess a number: 3
YAY
What is your name?'Sarah'
Guess a number: 1
Guess a number: 5
Guess a number: 78
Guess a number: 6
Guess a number: 3
YAY
What is your name?'Sandra'
Guess a number: 2
Guess a number: 4
Guess a number: 3
YAY
What is your name?'Paul'
Guess a number: 1
Guess a number: 3
YAY
Being the output:
print ranking
[['Sandra' '1']
['Paul' '2']
['Paul' '2']
['Sandra' '3']
['Sarah' '5']]
The leaderboard itself should store more structured data; use strings only to display the data.
# Store a list of (name, score) tuples
leaderboard = []
while True:
# Print the leaderboard
print("This in the leaderboard")
for name, score in leaderboard:
print("{} {}".format(score, name))
name = ("What is your name?")
score = 0
while user_num != answer:
user_num = input("Guess a number: ")
if user_num == answer:
print("YAY")
else:
score = score + 1
# Store a new score
leaderboard.append((name, score))
# Sort it
leaderboard = sorted(leaderboard, key=lambda x: x[1], reverse=True)
# Optional: discard all but the top 5 scores
leaderboard = leaderboard[:5]
Note that there are better ways to maintain a sorted list than to resort the entire leaderboard after adding a new score to the end, but that's beyond the scope of this answer.

Categories