Hello I am fairly new to python and would like to know where my program is failing and why.. thanks, the basic coding is as follows,
grade = 0
total = 0
scorecount = 0
while grade >=0:
grade = raw_input("enter grade ->")
grade = int(grade)
total = total + grade
total = int(total)
scorecount = scorecount + 1
scorecount= int(scorecount)
average = total/scorecount
print average
You accept the grade, then add it to the average even if it is -1, since you don't check for -1 until the loop starts again.
To quit a loop halfway through, use break. Then, you can write
while True: # loop 'forever' until break
grade = raw_input("enter grade ->")
grade = int(grade)
if grade == -1:
break # we're done
# rest of processing...
Your checking for -1 AFTER you change it, so you should check that the raw grade is that and break from the loop before processing.
It'd be smarter to use a list to manage something like this.
grades = []
while True:
grade = int(raw_input('Enter a grade: '))
if grade < 0:
break
grades.append(grade)
print '\nAverage:', float(sum(grades)) / len(grades)
There are better ways to have the user break the loop than entering a negative grade, but there you go.
Related
I've just started to learn Python (my first dabble in coding) and this is my first time posting... I hope I'm not abusing the forum by asking this question (I'm essentially asking an expert to help me learn). Please let me know if this is frowned upon in the community.
For this assignment from a Michigan open course, I've been instructed to ask a user for input until the user enters "done", at which point the code should calculate the largest, smallest, sum, and average. In all my test-runs, it's worked fine. But I feel like there's probably a much simpler way to write this code. Can anyone offer suggestions for improvement?
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count = count + 1
sum = sum + num
avg = sum/count
if largest is None:
largest = num
if smallest is None:
smallest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
continue
except: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", avg
Well there are a few things here:
you can drop the continue statement since it is the end of the loop anyway;
you can compress the if statements into if largest is None or num > largest: this will shortcircuit and make the loop smaller;
you can use x += y instead of x = x + y; and
you do not have to calculate the average inside the loop; calculating it once when the loop finishes, is enough.
So:
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count += 1
sum += num
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count
But in terms of big oh, you cannot improve much: calculating the sum, etc. simply require O(n) and it also costs O(n) to read the input anyway.
Furthermore some software engineering advice: don't use the blanket exception, always specify the exception you expect so:
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count += 1
sum += num
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except ValueError: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count
An alternative approach to accomplish this is to store all of the inputs in a list, and then use the built-ins min(),max(),len() and sum() to find values:
num=raw_input("Enter a number: ")
nums=[]
while num!="done": #check if user has finished entering inputs
try:
nums.append(int(num)) #append the input as an integer to a list
num=raw_input("Enter a number: ") #get another input
except ValueError:
print "Invalid input"
print "Maximum is",max(nums)
print "Minimum is",min(nums)
print "Count:",len(nums)
print "Sum: ",sum(nums)
print "Average: ",sum(nums)/len(nums)
Output:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: done
Maximum is 6
Minimum is 1
Count: 6
Sum: 21
Average: 3.5
I am a beginner in Python and I was trying to write a small program that asks the user to enter an integer that is greater than 0. The function should keep on asking the user for the number until it is valid.
I tried something like below, however I am getting the wrong results. Can you please help me understand my error?
num = input('please enter a number: ' )
n = int(num)
while n < 0:
num = input('please enter a number: ' )
if n >= 0:
print('Valid number')
else:
print('Invalid number')
Is it possible to start the code without an input function? (like to start with num = int())
Thank You for Your Time
There's an error with the logic behind your code.
You firstly ask the user for a number and if he inputs a number which is greater than or equal to 0, the while-loop will never start (in your script: while n < 0:), which, I assume is fine, because the goal of your program is, as you said, to make "the user to enter an integer that is greater than 0".
If the user inputs a number that is smaller than or equal to 0, the while-loop will start, but will never break because inside of it, the value of variable n never changes, only does the value of num.
This is an appropriate script considering that you want to make the user input a number greater than 0, and that you want to give feedback regarding their input.
n = None
while n <= 0:
n = int(input('please enter a number: '))
if n <= 0:
print('Invalid number')
else:
pass # the loop will break at this point
# because n <= 0 is False
print('Valid number')
The code has the user stuck in a loop until they write a number that's greater than 0.
Another solution would be to, inside the loop, check whether int(num) is greater than 0 and if it is, print 'Valid number' and do break to stop the loop; if it's not, print 'Invalid number' (though then the loop doesn't need to be defined by while n < 0:; rather by while True:.
Also, what do you mean by this:
Is it possible to start the code without an input function? (like to start with num = int())
Please clarify this part.
If your problem is the code not terminating, writing Invalid number all the time it's because you are not updating the value of n. You assigned it just once. The solution to your problem is as follows:
n = -1
while n < 0:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
By the way you get rid of starting the code without an input function.
Edit:
As you just said - you want to keep the input reading despite passing an negative integer into the command line. This should help you accomplish this:
while True:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
This loop will go forever until you exit the program lets say with ctrl + C. while True: is as you see an forever ongoing loop, because the True argument will never be false.
minimunpaymonth = 0
balance = 4773
annualInterestRate = 0.2
def function(minimunpaymonth):
global balance
month = 1
while month <= 12:
balance = balance - minimunpaymonth
anninterest = annualInterestRate/12 * balance
balance = balance + anninterest
month += 1
return balance
while function(minimunpaymonth) >= 0:
minimunpaymonth += 10
print "Lowest Payment: " + str(minimunpaymonth)
the second while loop is infinite and i dont know why. the first is ok because i have ran it
when the loop increases minimunpaymonth, value of balance goes down, so there will be a moment when balance is negative
def function(minimunpaymonth, balance, annualInterestRate):
month = 1
while month <= 12:
balance = balance - minimunpaymonth
anninterest = annualInterestRate/12 * balance
balance = balance + anninterest
month += 1
return balance
while function(minimunpaymonth, balance, annualInterestRate) >= 0:
minimunpaymonth += 10
print "Lowest Payment: " + str(minimunpaymonth)
ok i just solved it. i change the function to give 3 arguments instead of 1
your second loop is checking to see if minimunpaymonth is >= 0, if it is then it performs the loop again.
Your minimunpaymonth will always be >=0 because it starts at 0 & is only ever added to. There is no subtraction from this value.
the second loop keeps adding to minimum payment, it will always be >= 0 till it reaches the numeric limit of the variable; however as the comment pointed out, the "function" could get less, but perhaps the interest rate always keeps the balance above zero and the minimum payments don't get it there -- plausible enough in real life!
I tried to make a guess the number game in python but whenever I guess it repeats 4 times 'your guess is too low'
import random
number = random.randint(1, 20)
guessestaken = 0
print('I am thinking of a number between 1 and 20 ')
guess = raw_input('Take a guess and hit enter')
while guessestaken < 4:
guessestaken = guessestaken + 1
if guess > number:
print('your number is too low')
if guess < number:
print('your number is too high ')
if guess == number:
break
print('well done the number was ' + number + ' and you got it in ' + guessestaken + '')
You are asking for the user input before the while loop.
guess = int(raw_input('Take a guess and hit enter'))
This statement should come within the while block.
The function raw_input returns a string, you should convert it to an integer. You can read more about it in the Documentation.
You need to ask the user for input inside your loop, otherwise you are just comparing his first guess multiple times. Also, you should convert the input value to an integer, because raw_input returns a string.
>>> guess = raw_input('guess the number> ')
>>> type(guess)
<type 'str'>
>>> type(int(guess))
<type 'int'>
You are asking for the input from the user only once, right before you enter your loop. You will need to ask the user for a new input after every iteration of the loop, otherwise the guess will never change!
Additionally, when you read in some input from the user with raw_input it will be a string. You will need to cast it to an int.
Next, if you have a break in your loop, the statements after it will not get called. This means that you need to move the break statement to after the output when the user gets the right answer, or nothing will be printed.
Lastly, your logic in the if statements is backwards, if the guess is less than your generated number then the guess was too low, not too high! Altogether you get:
import random
number = random.randint(1, 20)
guessestaken = 0
print('I am thinking of a number between 1 and 20 ')
while guessestaken < 4:
guess = int(raw_input('Take a guess and hit enter'))
guessestaken = guessestaken + 1
if guess < number:
print('your number is too low')
if guess > number:
print('your number is too high ')
if guess == number:
print('well done the number was ' + number + ' and you got it in ' + guessestaken + '')
break
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
You just tried to make a loop in >4 so it is a normal error just to use while True: and change the raw_input to int(raw_input)
import random
number = random.randint(1, 20)
guessestaken = 0
print('I am thinking of a number between 1 and 20 ')
guess = int(raw_input('Take a guess and hit enter'))#make your input a int
while True:#change <4 for True
guessestaken = guessestaken + 1
if guess > number:
print('your number is too low')
if guess < number:
print('your number is too high ')
if guess == number:
break
print('well done the number was ' + number + ' and you got it in ' + guessestaken + '')
I am trying to write a program that converts a percentage received in a class into a GPA format then eventually find the overall GPA. I want it to first prompt the user to input the amount of classes, then input the percentages. I am running into some trouble getting the program to convert the percentage into the GPA format (90 or greater equals 4, 80 to 89 equals 3, ect...). This is what I have so far
class_number = int(raw_input("How many classes do you have? "))
total_grade = list((raw_input("Enter Percentage: ")) for i in range(class_number))
a = total_grade
def alter(x):
if x >= 90:
return 4
elif x >= 80:
return 3
a = map(alter,a)
print a
The problem is that this only seems to output 4s no matter the original percentage.
Any help would be greatly appreciated! Thanks!
That's because x is actually a string. I think a string will always be greater than a number. You need to convert each item in total_grade to an int:
total_grade = list(int(raw_input("Enter Percentage: ")) for i in range(class_number))
Also, you can just use a list comprehension:
total_grade = [int(raw_input("Enter Percentage: ")) for i in range(class_number)]