a = int(input("Enter mark of BIOLOGY: "))
b = int(input("Enter mark of CHEMISTRY: "))
c = int(input("Enter mark of PHYSICS: "))
sum = a + b + c
x = sum
y = 3
avg = x / y
print("Total marks = ", sum)
print("Average marks = ", avg)
I want to limit the user's input so it only accepts integers from 0 to 90.
To limit the user's input to 0 to 90, you will need to repeatedly ask the user to re-input the data until it meets the 0 to 90 criteria. You can do that by implementing a while loop and then break if the criteria is met. Here's the code:
# Data validation for the variable "a"
while True:
a = int(input("Enter mark of BIOLOGY: "))
if 0 <= a <= 90:
break
else:
print("The mark is not between 0 and 90. Please enter a new mark.")
Hope this helped.
If you are wanting to limit the sum variable, at the end of your code you could simply put an if statement checking that the variable is within the boundary..
if sum > 90:
sum = 90
elif sum < 0:
sum = 0
The following code will ensure that the user inputs the number in the specified range:
while True:
a = int(input("enter mark of BIOLOGY = "))
if 0 <= a <= 90:
break
else:
print("Invalid mark. Please try again.")
while True:
b = int(input("enter mark of CHEMISTRY = "))
if 0 <= b <= 90:
break
else:
print("Invalid mark. Please try again.")
while True:
c = int(input("enter mark of PHYSICS = "))
if 0 <= c <= 90:
break
else:
print("Invalid mark. Please try again.")
sum = a + b + c
x = sum
y = 3
avg = x / y
print("total marks = ", sum)
print("average marks = ", avg)
This will ensure the variables a, b, and c are between 0-90.
Related
This question already has answers here:
Armstrong numbers in python
(14 answers)
Closed 7 months ago.
def Counting(number):
count = 0
while(number > 0):
number = number // 10
count = count + 1
return count
number = int(input("Please Enter any number:"))
count = Counting(number)
i'm not sure what to do so i really can't do much
Program to test if a given number is an Armstrong number
def is_armstrong(n):
l = len(str(n))
t = 0
for d in str(n):
t += int(d) ** l
return t == n
print(is_armstrong(int(input('Enter a number: '))))
Output:
Enter a number: 153
True
Enter a number: 200
False
Hope this helps!
n = 153
s = n
b = len(str(n))
summ = 0
while n != 0:
r = n % 10
summ = summ+(r**b)
n = n//10
if s == summ:
print("The given number", s, "is armstrong number")
else:
print("The given number", s, "is not armstrong number")
Hope this helps. Thanks
This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
This is my while loop so far. I ask the user how many assignments they completed, which can only be between 1 and 10 (and graded out of 0 to 5).
However, if they answer anything below 10, I want the to code to automatically enter it as zero, instead of the user having to manually enter 0 for each assignment they have not completed.
Right now my code will ask the user to input a grade 10 times, but I only want to input grades based on the users answer of how many assignments they completed. So if they answered 7, the question would be presented 7 times, and three 0 marks would be automatically factored in to the average.
while True:
result = input("How many assignments did you complete? ")
if result.isdigit() and 0 <= int(result) <= 10:
break;
print ("Try a number between 1 and 10")
total = 0
gradeCount = 0
while gradeCount < 10:
grade = float(input('What was assignment score: '))
if grade < 0 or grade > 5:
print('It should be a number from 0 to 5')
else:
gradeCount += 1
total += grade
aaverage = total / 30 * 100
print('Average: ', aaverage)
while True:
result = input("How many assignments did you complete? ")
if result.isdigit() and 0 <= int(result) <= 10:
break;
print ("Try a number between 1 and 10")
total = 0
gradeCount = 0
while gradeCount < int(result):
grade = float(input('What was assignment score: '))
if grade < 0 or grade > 5:
print('It should be a number from 0 to 5')
else:
gradeCount += 1
total += grade
aaverage = total / 50 * 100
print('Average: ', aaverage)
Just count the number of assignments. Also you have to divide by 50, because of the 10 max assignments, so 50 points
while 1:
result = input("How many assignments did you complete? ")
if result.isdigit() and 0 <= int(result) <= 10:
result = int(result)
break
print ("Try a number between 1 and 10")
total = 0
for i in range(result):
while 1:
grade = float(input('What was assignment score: '))
if 0 <= grade <= 5:
break
else:
print('It should be a number from 0 to 5')
total += grade
aaverage = total / 10
print('Average: ', aaverage)
Basically, I need to take input unless a negative number is entered and then print the sum of scores along with some other statistics and all. Question has now been resolved.
nums=[]
total= 0
count= 0
while x >= 0:
x = int(input("Enter a number (enter -1 to terminate): "))
if x <= 100:
total = total + x
count+=1
nums.append(x)
if x>100:
print("Invalid entry.")
x = int(input("Enter a number (enter -1 to terminate): "))
print(nums)
print("Number of scores: ", len(nums))
It looks like the 2nd input should be at the end of the while loop
while x >= 0:
if x <= 100:
total = total + x
count+=1
nums.append(x)
if x>100:
print("Invalid entry.")
x = int(input("Enter a number (enter -1 to terminate): "))
That gives the first value a chance to get processed, and means that the final -1 won't be appended
I need to create a function that will print the smallest, largest,and average of n amount of numbers inputed by user.
My function, so far, can print the average and largest value of n amount of numbers entered by user but I'm stuck on finding the smallest value.
This is what I have so far:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
l_v=0
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x>l_v:
l_v=x
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
As #Padraic mentioned, the answer that your posted to your question doesn't work for positive values, since your if-statement only checks if the min value is less that 0.
To fix this, you could just assign the first inputted value to all the variables. This way you wouldn't have to use positive and negative inf variables:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=0
f_v = l_v = s_v = total =int (input("enter first value")) #first value
while counter<(n-1):
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<s_v: #find minimum
s_v=x
elif x>l_v: #find maximum
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()
Now your code will run without any issues:
how many?5
enter first value-1
enter next number7
enter next number0
enter next number3
enter next number2
the smallest value is -1
the largest value is 7
('the average is ', 2.2)
You could add the items to a list while the user inputs data.
When the user is done, just use min(), max(), and sum() (and maybe len()) on the list.
Keep track of the lowest number also, set the start value to float(inf) for the min and float(-inf) for the max:
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
You can also use a for loop with range:
n = int(input("how many?"))
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm = 0
for i in range(n):
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
Or using a list comp:
n = int(input("how many?"))
if n > 0:
nums = [int(input("enter next number")) for _ in range(n)]
print ("the largest value is {0}".format(min(nums)))
print("the average is ", sum(nums)/ n)
print("the min value is {}".format(min(nums)))
else:
print("What? it is not possible to find the average, sorry ")
sm += x is augmented assignment which the same as doing sm = sm + x.
When verifying user input and casting you should really use a try/except to catch any exceptions:
def get_num():
while True:
try:
n = int(input("enter next number"))
# user entered valid input, return n
return n
except ValueError:
# could not be cast to int, ask again
print("Not an interger")
while True:
try:
n = int(input("how many?"))
break
except ValueError:
print("Not an interger")
if n > 0:
l_v = float("-inf")
mn_v = float("inf")
sm, counter = 0, 0
while counter < n:
x = int(input("enter next number"))
if x < mn:
mn = x
if x > l_v:
l_v = x
sm += x
counter += 1
print("the largest value is {0}".format(l_v))
print("the average is ", sm / n)
print("the min value is {}".format(mn_v))
This is what I ended up doing... Just kind of worked it out myself through trial and error.
I really appreciate the answers! Gives me a different way of looking at the problem!
Answer:
def main():
n = int(input("how many?"))
if (n>0):
counter=0
total=1
l_v=0
s_v= 0
f_v = int (input("enter first value"))
while counter<n:
x = int(input("enter next number"))
total=total+x
counter=counter+1
if x<f_v:
s_v=x
elif x>l_v:
l_v=x
print ("the smallest value is {0}".format(s_v))
print ("the largest value is {0}".format(l_v))
print("the average is ", total/n)
else:
print("What? it is not possible to find the average, sorry ")
main()