I wanted to know if there was any way to end a conditional early. For example, when I run the code and enter all values in between 0-100 the program does what it's supposed to. However, let's say I put a negative number as input #3. The program keeps on going until the very end, then I get "Invalid input. Enter a number between 0-100". I'm wondering if there is any way I can get that message as soon as I enter a number that's not in between 0-100. I'm a complete beginner, so I really don't know what I'm doing.
def e5():
stdnt1 = float(input("Enter the first grade: "))
stdnt2 = float(input("Enter the second grade: "))
stdnt3 = float(input("Enter the third grade: "))
stdnt4 = float(input("Enter the fourth grade: "))
stdnt5 = float(input("Enter the fifth grade: "))
if(0 <= (stdnt1 and stdnt2 and stdnt3 and stdnt4 and stdnt5) <= 100):
avrg = (stdnt1 + stdnt2 + stdnt3 + stdnt4 + stdnt5) / 5
print("The groups average is", avrg)
grades = [stdnt1, stdnt2, stdnt3, stdnt4, stdnt5]
grades.sort()
print("The lowest grade is", grades[0])
else:
print("Invalid input. Enter number between 0-100")
I would recommend writing a function that takes the input and processes it.
def get_input(prompt):
response = float(input(prompt))
if 0 <= response <= 100:
return response
raise ValueError("Invalid input - enter number between 0-100")
This also has the advantage of simplying the first 5 lines of your function.
def e5():
stdnt1 = get_input("Enter the first grade")
# ...
You could also change the function to continue to ask the user using a while loop for valid input.
Hopefully this is enough to get you started.
Yes. Perform some preliminary checks as soon as you get the input. Example:
stdnt3 = float(input("Enter the third grade: "))
if not (0 <= stdnt3 and stdnt3 <= 100):
raise SystemExit("Error: value is not between 0 and 100.")
stdnt4 = float(input("En...
Edit
Note that your if-condition doesn't work as you expect. This:
if(0 <= (stdnt1 and stdnt2 and stdnt3 and stdnt4 and stdnt5) <= 100):
Will be (logically) turned into:
# Step 1
booleanValue = stdnt1 and stdnt2 and stdnt3 and stdn4 and stdnt5 # a True or False
# Step 2
if 0 <= (booleanValue) <= 100
# Step 3
if (0 <= booleanValue) <= 100
# Step 4
if TrueOrFalse <= 100
TrueOrFalse will be True (casting usually to the number 1) or False (casting usually to the number 0). That means that the if-condition will always evaluate to True and your else will never get called. Instead, check each value individually, either with multiple if statements, or in a single if statement:
if (0 <= stdnt1 and stndt1 <= 100) and (0 <= stndt2 and stndt2 <= 100) and ...
Divide up your problems. You're trying to achieve two separate things here:
Validate your inputs
Calculate an average
Write separate functions for each of these... well.. functions!
def validate_grade(grade):
if grade < 0 or grade > 100:
raise InvalidGrade() # This is a custom exception, I'll explain momentarily
return grade
So this function will check if a given number is between 0 and 100 inclusive, if not it will raise an exception. In this case it's a custom exception, so that we can catch it only if this particular case occurs. In all other circumstances, normal Python exceptions will be raised.
Let's define that exception.
class InvalidGrade(Exception):
pass
It really is just a standard exception with a different name! Easy but very helpful, here's how:
try:
stdnt1 = validate_grade(float(input("Enter the first grade: ")))
stdnt2 = validate_grade(float(input("Enter the second grade: ")))
stdnt3 = validate_grade(float(input("Enter the third grade: ")))
stdnt4 = validate_grade(float(input("Enter the fourth grade: ")))
stdnt5 = validate_grade(float(input("Enter the fifth grade: ")))
except InvalidGrade:
print("Invalid input. Enter number between 0-100")
else:
calculate_grades(stdnt1, stdnt2, stdnt3, stdnt4, stdnt5)
Great! Now it will gather input, raise an exception if any one of those inputs is invalid, otherwise it will execute the yet-to-be-defined calculate_grades function. But before we do that, we have some very repetitive code to clean up.
Lets ask ourselves what we're really repeating with these 5 grades. The only difference between each line is "first", "second", "third", etc.
Aha! We could create a list of grade names, and then python can loop over that list to build a list of grade values.
grade_names = ["first", "second", "third", "fourth", "fifth"]
try:
grade_values = [validate_grade(float(input("Enter the %s grade: " % name)))
for name in grade_names]
except InvalidGrade:
print("Invalid input. Enter number between 0-100")
else:
calculate_grades(*grade_values)
First we simply define a list of grade names by creating a list of strings.
Then inside the try block we use something called a list comprehension. It is simply a statement that gets evaluated for each item in a list, in this case that statement is the function validate_grade which happens to take the results of input then float as its parameters, and returns a value which is what will be saved in our grade values list.
Then, instead of passing each item one by one to calculate_grades, the * tells python to expand the list's elements as parameters for the function. Now if you were to say, add or remove a grade, you only have to change your code in one place.
Now for the final piece, lets define calculate_grades
def calculate_grades(*args):
avrg = sum(args) / len(args)
print("The groups average is", avrg)
print("The lowest grade is", min(args))
The whole solution together
GRADE_NAMES = ["first", "second", "third", "fourth", "fifth"]
class InvalidGrade(Exception):
pass
def validate_grade(grade):
if grade < 0 or grade > 100:
raise InvalidGrade()
return grade
def calculate_grades(*args):
print("The groups average is", sum(args) / len(args))
print("The lowest grade is", min(args))
try:
grade_values = [validate_grade(float(input("Enter the %s grade: " % name)))
for name in GRADE_NAMES]
except InvalidGrade:
print("Invalid input. Enter number between 0-100")
else:
calculate_grades(*grade_values)
Related
I get a syntax error on the last else statement. This is supposed to be a grade calculator. If someone enters anything that isn't between 0 and 100, then the program should send a message, and then loop until a valid number is entered. Also I am new to programming, so if there is something else wrong with my code, please let me know!
number = int(input("Enter the numeric grade: "))
if number > 89:
letter = 'A'
elif number > 79:
letter = 'B'
elif number > 69:
letter = 'C'
else:
letter = 'F'
print("The letter grade is", letter)
number = int(input("Enter the numeric grade: "))
if number > 100:
print("Error: grade must be between 100 and O")
elif number < 0:
print("Error: grade must be between 100 and O")
else:
# The code to compute and print the result goes here
number = int(input("Enter the numeric grade: "))
if number > 100 or number < 0:
print("Error: grade must be between 100 and 0")
else:
# The code to compute and print the result goes here
number = int(input("Enter the numeric grade: "))
if number >= 0 and number <= 100:
else:
print("Error: grade must be between 100 and O")
Your issue is at the bottom, where you've got an empty if statement followed by an else statement, as well as incorrect indenting. From your code, I believe you are trying to use not.
I would suggest doing one of two things:
1.
if not (number >= 0 and number <= 100):
2.
if number < 0 or number > 100:
These two pieces of code will both produce the same result.
Also, it seems as though you are repeating the same code several times to try to ensure that the user inputs a number between 0 and 100. If so, this can be achieved with a while loop. I've put an example of this below:
number = int(input("Enter the numeric grade: "))
while number < 0 or number > 100:
print("Error: grade must be between 100 and O")
number = int(input("Enter the numeric grade: "))
In the last line.
if number >= 0 and number <= 100:
else:
print("Error: grade must be between 100 and O")
you didn't write anything after the if statement.
This code will run
if number >= 0 and number <= 100:
print('Write something here')
else:
print("Error: grade must be between 100 and O")
or you can just remove the last if statement its really of no use like try doing something else because there are a lot of if and else statements which don't look nice.
try this:
n = int(input())
first = 0
last = 100
while n < first or n > last:
print(n,'is not a valid input')
n = int(input())
From what I've understood, you're trying loop indefinitely until the user input is between 0 and 100.
My solution would be this:
Define a function that starts by requesting an input from the user.
Use a while loop that will check if the input is 'correct'. In case the input is not correct, the loop will print the error and call back the function again indefinitely till the user's input is between 0 and 100.
if the input is between that range, it will then evaluate the grade and return it.
def yfunc():
n = int(input('Enter the numeric grade: '))
while n < 0 or n > 100:
print("Error: grade must be between 100 and O")
return yfunc()
if n > 89:
letter = 'A'
elif n > 79:
letter = 'B'
elif n > 69:
letter = 'C'
else:
letter = 'F'
return letter
yfunc()
If you have any questions, feel free to ask.
so i'm writing a program that's supposed to take 2 inputs of data as int's for a user's debt. the variables are debt1 and debt2. it's supposed to add these two values together and then depending on the user's input, it's supposed to give out a specific response using the "if/else" loop i've created. the problem is that the program only prints out the response from the first "if" statement no matter what the input is, it always prints out "your debt is dangerously high". how do i correct this?
** Here is my code **
Name = input("Please enter your name: ")
debt1 = int(input("Please enter your first debt amount: "))
debt2 = int(input("Please enter your second debt amount: "))
totalDebt = debt1+debt2
print("Your total debt is ", totalDebt)
if (totalDebt > 900,000):
print("Your debt is dangerously high ", Name)
elif((totalDebt >= 450,000 and totalDebt < 900,000)):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
Don't use commas in numbers:
if totalDebt > 900000:
print("Your debt is dangerously high ", Name)
elif (totalDebt >= 450000 and totalDebt < 900000):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
As #rdas said, you can use _ for long numbers, in place of ,
I am learning Python this semester and this is my homework.
Can anyone tell me why my code is wrong?
QUESTION:
You want to know your grade in Computer Science, so write a program that continuously takes grades between 0 and 100 to standard input until you input "stop", at which point it should print your average to standard output.
MY CODE:
total=0
count=0
while True:
grade=input("Enter Your Grades between 0 and 100 [put 'stop' when done]:")
if grade<0 or grade>100:
print("Invalid Input")
continue
elif grade=="stop":
break
else:
count+=1
total+=grade
print "Your Average Grade is:"+format(total/count,'.2f')
When I run the code, the Python keeps giving me this messages:
Change input to raw_input
grade = raw_input("Enter Your Grades between 0 and 100 [put 'stop' when done]:")
You are using Python 2.7, so use raw_input instead of input. The latter evaluates the input, so 5 + 2 will return 7 instead of the string '5 + 2'. Entering stop tries to evaluate stop as a variable, which doesn't exist.
Another note, total and count are both integers, so total/count performs integer division in Python 2 (Python 3 gives a float result). If you want a floating point average, use float(total)/count. One of the variables must be float to get a float answer.
You'll also find that grade is a string, so test for 'stop' first, then convert it to an int to test the grade grade = int(grade). You might want to think about handling errors. What if the user types 10a?
You can evaluate first the string stop, try capture the input with raw_input:
total = 0
count = 0
while True:
grade = raw_input("Enter Your Grades between 0 and 100 [put 'stop' when done]:")
if grade == "stop":
break
if grade.isdigit():
grade = int(grade)
if grade < 0 or grade > 100:
print("Invalid Input")
continue
else:
count += 1
total += grade
if count == 0:
print "Empty values"
else:
print "Your Average Grade is: %.2f" % (float(total)/count)
I added different conditions for correct execution, check the lines, for example if grade.isdigit(): for verify that the input value is a numeric value, when this evaluation we can work normally with any math calculation.
count == 0: for the error division by zero if the user write stop in first iteration.
In the last line you can use two different ways to print the values:
print "Your Average Grade is: %.2f" % (float(total)/count)
or
print "Your Average Grade is: {:.2f}".format(float(total)/count)
You're running this program in Python 2 where input evaluates the user input. So if you enter "stop", Python tries to find the variable stop which doesn't exist and raises the NameError.
There are more problems and you need to restructure the code. The first thing you should do is to change input to raw_input which just returns the user input as a string. Then you need to check if the user entered "stop" and break, otherwise convert the input string to an int and then increment the count and total.
total = 0
count = 0
while True:
grade = raw_input("Enter Your Grades between 0 and 100 [put 'stop' when done]:")
if grade == "stop":
break
# Skip if the string can't be converted to an int.
if not grade.isdigit():
print("Invalid Input")
continue
# Now convert the grade to an int.
grade = int(grade)
if grade < 0 or grade > 100:
print("Invalid Input")
continue
else:
count += 1
total += grade
# Convert total to a float for true division.
print "Your Average Grade is: {:.2f}".format(float(total)/count)
Objective: * Write a python program that repeatedly prompts for input of a positive number until the sum of the numbers is greater than 179. Use at least three modules/functions in your solution.
* The largest number entered cannot exceed 42.
* When the sum of the numbers exceeds 179, print the sum of the numbers, the largest number entered and smallest number entered.
I just need some guidance, specifically for the "input_numbers" module. There must be an easier way to do this than to make a variable for each number. The code is not complete. I haven't even started on the two other modules yet. Thanks in advance.
def input_numbers():
while True:
num1 = raw_input("Enter a positive integer no greater than 42 ")
if num1 <= 0:
print "That is not a positive integer. Try again "
elif num1 > 42:
print "The number cannot exceed 42. Try again "
num2 = raw_input("Enter another positive integer ")
if num2 <= 0:
print "That is not a positive integer. Try again "
elif num2 > 42:
print "The number cannot exceed 42. Try again "
num3 = raw_input("Enter another positive integer ")
if num3 <= 0:
print "That is not a positive integer. Try again "
elif num3 > 42:
print "The number cannot exceed 42. Try again "
num4 = raw_input("Enter another positive integer ")
if num4 <= 0:
print "That is not a positive integer. Try again "
elif num4 > 42:
print "The number cannot exceed 42. Try again "
num5 = raw_input("Enter another positive integer ")
if num5 <= 0:
print "That is not a positive integer. Try again "
elif num5 > 42:
print "The number cannot exceed 42. Try again "
elif sum(num1, num2, num3, num4, num5) > 179:
print_numbers()
add_numbers()
def add_numbers():
print_numbers()
def print_numbers():
input_numbers()
You can knock out all three function requirements by encapsulating each step of your program. Rather than having your loop inside of a function, we'll let main control the loop, and we'll control the flow by passing data into and out of function calls.
Let's rework your input_numbers() function a bit.
def get_input_number():
num = int(raw_input("Enter a positive integer no greater than 42 "))
if num <= 0 or num > 42:
print "Invalid input. Try again "
get_input_number()
else:
return num
So, instead of having input_numbers control the loop as well as the input handling and validation, we have it do just what its name implies: It asks for input, validates it, and then, if it's good, it returns the value to the caller, but if it's bad, it writes a message, and calls itself again to the user can enter good input.
The next function we'll set up is straight from your list of requirements. From all of the numbers that the user enters, we need to find the biggest one. From the language alone, we can determine that we're looking through a set of numbers, and thus, this is a good place to break out a list. Assuming we store all of the users input in a list, we can then pass that list to a function and perform operations on it, like so.
def get_greatest_number(input_list):
highest = input_list[0]
for i in input_list:
if i > highest:
highest = i
return highest
We set the first element of the list to a variable highest and then check all other elements in the list against that initial value. If we find one that's bigger, we then reassign the highest variable to the element that was bigger. Once we do this for each element in the list, the number inside of highest will now be, just that, the highest number, and so, we'll return it to the main program.
Similarly, we can do the same for finding the smallest.
def get_smallest_number(input_list):
smallest = input_list[0]
for i in input_list:
if i < smallest:
smallest = i
return smallest
Finally, we get to our main loop. Here we declare an empty list, number_list to store all the numbers in. And we use the sum of that as our loop condition.
if __name__ == '__main__':
number_list = []
while sum(number_list) < 179:
number_list.append(get_input_number())
In the body of the loop, we call our get_input_number() and append its result to the list we made. Once the sum of the numbers in the list exceed 179, the while loop will exit and we can finally show the user the results.
print
print '-------------------------'
print 'total of numbers entered: %d' % sum(number_list)
print 'greatest number entered: %d' % get_greatest_number(number_list)
print 'smallest number entered: %d' % get_smallest_number(number_list)
Here we can the get_greatest_number and get_smallest_number we made, and we give them the list of numbers as an argument. They'll loop though the lists, and then return the appropriate values to the print statements.
Yes, of course there's a better way than making a variable for each number. Store them in a list. Storing them in a list also makes finding their sum and the highest and lowest value easy (there are built-in functions for this).
As a further hint, you'll want to use two loops, one inside the other. The outer loop keeps the user entering numbers until their sum exceeds 179. The inner loop keeps the user entering a single number until it's between 1 and 42 inclusive.
def get_int(prompt=''):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def get_values():
values = []
total = 0
while total <= 179:
val = get_int('Enter a positive integer <= 42: ')
if 0 <= val <= 42:
values.append(val)
total += val
return values
def print_info(values):
print 'Sum is {}'.format(sum(values))
print 'Largest value is {}'.format(max(values))
print 'Smallest value is {}'.format(min(values))
def main():
values = get_values()
print_info(values)
if __name__=="__main__":
main()
You can repeatedly poll the number in a loop, and add the inputs into a list, e.g.
def input_numbers():
user_inputs = [] # a list of all user's inputs
while True:
num = raw_input("Enter a positive integer no greater than 42 ")
try:
num = int(num) # convert input string to integer
if num <= 0:
print "That is not a positive integer. Try again "
elif num > 42:
print "The number cannot exceed 42. Try again "
user_inputs.append(num)
except ValueError: # conversion to integer may fail (e.g. int('string') ?)
print 'Not a Number:', num
if some_condition_regarding(user_inputs):
break # eventually break out of infinite while loop
here some well-known tricks:
def min_and_max(your_num_list)
min=your_num_list[0]
max=your_num_list[0]
for num in your_num_list:
if num < min:
min=num
if max > num
max=num
return min,max
When you're writing a standalone Python program, it’s a good practice to use a main function. it allows you to easily add some unit tests, use your functions or classes from other modules (if you import them), etc.
And as others already said, it is a good idea to create a list and append a new element to it each time the user enters a valid number (until the sum of the numbers axceeds 179). If user entered an incorrect value, then just don’t append anything to the list and skip to the next iteration (so the user will be asked to enter a number again).
So basically it could look like this:
def validate_entered_number(num):
"""
Checks if the number is positive and is less or equal to 42.
Returns True if the number matches these conditions,
otherwise it returns False.
"""
if num < 0:
print "That is not a positive integer."
return False
if num > 42:
print "The number cannot exceed 42."
return False
return True
def main():
entered_numbers = []
while True:
try:
num = int(raw_input("Enter a positive integer less or equal to 42: "))
except ValueError:
print "You should enter a number"
continue
if validate_entered_number(num):
entered_numbers.append(num)
if sum(entered_numbers) > 179:
print "The sum of the numbers is %s" % sum(entered_numbers)
print "The smallest number entered is %s" % min(entered_numbers)
print "The largest number entered is %s" % max(entered_numbers)
return
if __name__ == "__main__":
main()
In fact, I can imagine a situation where you would want to just store the sum of the numbers, the smallest number and the largest number in three variables and update these variables in each iteration (add current number to the sum and compare it to the currently known smallest and larger numbers and update the corresponding variables when necessary), but in this case the longest list you can possibly have is only 180 elements (if all numbers are 1 and the user doesn’t enter 0 or you have modified the program to deny entering 0), which is very small amount of elements for a list in Python. But if you had to deal with really big amounts of numbers, I’d recommend to switch to a solution like this.
Thanks to everyone who answered. I've written the following code and it works nearly perfectly except the last module. If you exit the program after the first run (by pressing 0) it will exit, but if you run it a second time pressing 0 won't make it exit. It'll just go back to the beginning of the program. I don't know why.
Note: The assignment has various requirements that I had to incorporate in my code. Hence the unnecessary modules, global variables, and comments.
maxNum = 42 # declares global variable maxNum
target = 179 # declares global variable target
def user_input(): # prompts user to input a number 42 or less until all add up to 179
x = 0
nums = []
while sum(nums) <= target:
nums.append(int(raw_input("Enter a number: ")))
if int(nums[x]) > int(maxNum):
print "Number cannot exceed 42."
user_input()
else:
x += 1
print_nums(nums,x)
def print_nums(nums,x): # prints the sum of the numbers, the smallest, and the largest
print "Sum of all numbers is", sum(nums)
nums.sort()
x -= 1
print "Largest number entered is", nums[x]
print "Smallest number entered is", nums[0]
decide()
def decide(): # allows user to continue the program or exit
exit = raw_input("<9 to enter a new set of number. 0 to exit.> ")
while True:
if int(exit) == 0:
return
elif int(exit) == 9:
user_input()
user_input()
This is kind of a double-barreled question, but it's got me puzzled. I currently have the following code:
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
Now, I'd like to have some kind of loop (I'm guessing it's a for loop, but I'm not entirely sure) so that after a function has been completed, it'll return to the top, so the user can enter a new function number and do a different equation. How would I do this? I've been trying to think of ways for the past half hour, but nothing's come up.
Try to ignore any messiness in the code... It needs some cleaning up.
It's better to use a while-loop to control the repetition, rather than a for-loop. This way the users aren't limited to a fixed number of repeats, they can continue as long as they want. In order to quit, users enter a value <= 0.
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
while function > 0:
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer = b/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
print 'Enter a value <= 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
You can tweak this (e.g., the termination condition) as needed. For instance you could specify that 0 be the only termination value etc.
An alternative is a loop that runs "forever", and break if a specific function number is provided (in this example 0). Here's a skeleton/sketch of this approach:
function = int(raw_input("Type function no.: "))
while True:
if function == 1:
...
elif function == 2:
...
elif function == 0:
break # terminate the loop.
print 'Enter 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
Note: A for-loop is most appropriate if you are iterating a known/fixed number of times, for instance over a sequence (like a list), or if you want to limit the repeats in some way. In order to give your users more flexibility a while-loop is a better approach here.
You simply need to wrap your entire script inside a loop, for example:
from __future__ import division
import math
for _ in range(10):
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
This will run your if statement 10 times in a row.
I'd try this:
while True:
function = ...
if function == 0:
break
elif ...