I am making a program that calculates the sum of all even and odd numbers between two number which are user inputted. I'm new to Python and am not sure how to use the range in a loop to make my program work. Here is my code. I know its sloppy and not well put together and not finished but any help works thanks.
n = int(input(" please enter a number"))
m= int(input(" please enter another number"))
count =0
sum =0
for x in range(n,m+1,2):
if x%2==0:
count=count+x
sum = count
print(" the total sum of odd numbers are",sum)
It's important to know if n is greater than m and invert situation if so. Other than that, you need to know if the smallest number is odd or even and begin the two ranges accordingly:
n = int(input("Please enter a number: "))
m = int(input("Please enter another number: "))
# n will always be the smaller one
if n > m:
n, m = m, n
n_is_odd = n % 2 # Gives 1 if n is odd
n_even = n + n_is_odd # Sum 1 if n is odd
n_odd = n + (not n_is_odd) # Sum 1 if n is even
print("the total sum of even numbers is %d" % sum(range(n_even, m+1, 2)) )
print("the total sum of odd numbers is %d" % sum(range(n_odd, m+1, 2)) )
Input validation is a big part of good coding. A good overview can be found here:
Asking the user for input until they give a valid response
To make the validation it reusable I put the validation in a function that only accept integers and (if a minval is provided, makes sure that the input is bigger that the minval.
def while_invalid_ask_input_return_integer(text, minval = None):
"""Aks for input until a number is given that is > minval if minval not None
returns an integer."""
while True:
c = input (text)
try:
c = int(c)
if minval is not None and c < minval:
raise ValueError # its too small, raise an erros so we jump to except:
return c
except ValueError:
if minval is not None:
print("must be a number and greater ", minval)
else:
print("not a number")
I use it to get the first number, and the second number gets the first one as "constraint" so it will be bigger. For summation I just use the range starting once with n once with n+1 till m and a range step of 2. I check what even/oddness n has and print text accordingly:
n = while_invalid_ask_input_return_integer("please enter a number ")
m = while_invalid_ask_input_return_integer("enter number bigger then {}".format(n),n)
print( "Odd sum:" if n % 2 == 1 else "Even sum:", sum(range(n,m+1,2)) )
print( "Even sum:" if n % 2 == 1 else "Odd sum:", sum(range(n+1,m+1,2)) )
Output:
please enter a number k
not a number
please enter a number 55
enter number bigger then 55 2
must be a number and greater 55
enter number bigger then 55 150
Odd sum: 4896
Even sum: 4944
Doku:
sum(iterable)
try: except: error handling
python ternary operator (thats the thing # "Odd sum:" if n % 2 == 1 else "Even sum:" in the print statement)
Here's a function I think fits into the description of what you asked above. It returns None if the user doesn't enter the type of query he or she wants.
So query can either be odd or even and depending on this, it calculates the sum that you want. The function makes use of list comprehension which is super cool too.
def calculate_odd_or_even_sum(query):
start = int(input(" please enter a number"))
end = int(input(" please enter another number"))
count = 0
if query == 'even':
return sum([x for x in range(start, end) if x % 2 == 0])
elif query == 'odd':
return sum([x for x in range(start, end) if x % 2 != 0])
else:
return 0
Related
I want to calculate the sum of the natural numbers from 1 up to an input number. I wrote this code:
number=int(input("enter a natural number"))
if number<0:
print("The number is not positive")
else:
n=0
for i in range (1,number+1):
n+=i
print(n)
But it prints multiple numbers instead. For example, if the user puts five, the program should print 15, but I get this:
1
3
6
10
15
How can I fix the code so that only 15 appears?
You have all the steps because your print statement is in your for loop.
Change it like this:
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
result = 0
for i in range(1, number + 1):
result += i
print(result) # We print after the calculations
There's also a mathematical alternative (see here):
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
print(number * (number + 1) / 2)
As I've pointed out and suggested earlier in comments, you could move the print statement out of for-loop to print the final sum.
Or you could try to use generator expression to get all number's total (sum), because we don't care the intermediate sums.
This simple sum of all up to the number in one shot.
number=int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
# exit or try again <---------
else:
print(sum(range(1, number + 1))) # given 5 -> print 15
Something like this?
number = int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
else:
n = 0
for i in range (1,number + 1):
n += i
print(n)
The answer to your question is that you are printing the n every time you change it. You are looking for the last answer when you run the code. This code should solve it.
number = int(input("enter a natural number"))
if number < 0:
print("The num < 0")
else:
n = 0
l = []
for i in range (0, number+1):
n+=i
l.append(n)
print(l[len(l)-1])
I'm trying to make a program that basically works like this:
I ask for a number, and from that number I must form a number N by concatenating all the numbers between 1 and N. For example, if I enter a 12, the number N will be 123456789101112, or if I enter a 6, the number would be 123456. Once N has been formed, I must return "YES" on the screen in the case that N is divisible by 3 and “NO” in the case that it is not.
This is what I have:
n = int(input("Enter a number:"))
for x in range (n + 1):
if(n%3==0):
print("YES")
else:
print("NO")
I just started using Python and I don't know what I'm doing wrong, if someone can give me a hand I would be very grateful!
The answer will be :
if n%3 != 1:
print("YES")
else:
print("NO")
Reason
Every number is one of the three types (3*k+1), (3*k+2) or (3*k). A number is divisible by 3 if the sum of its digits is divisible by 3 a.k.a. it is a (3*k) type of number.
If input is 1. Then N will be 1 which is a (3*k+1) type of number so it is not divisible by 3.
When input is 2. Then N will be 12 which is divisible by 3.
When input is 3. Then N will be 123 which is divisible by 3.
Similarly, when input is 4. Then N will be 1234 which is not divisible by 3.
If you go one you realise that N will be divisible by 3 whenever the input is not a (3*k+1) type of number.
If you want to do it using the algorithm you describe, then a simple (but not very fast) way of doing it would be so:
n = int(input("Enter a number:")) # get the number
stringNumber = ""
for x in range(1, n+1):
stringNumber += str(x) # join the string version of numbers 1...n into a string
intNumber = int(stringNumber) # convert the string concatenation into an int
if (intNumber % 3 == 0): # check if the int is divisible by 3
print("YES")
else:
print("NO")
You can speed-up the string concatenation by using join() if you wish:
stringNumber = "".join([str(digit) for digit in range(1,n+1)])
the result is the same
However, you might also notice that a number is divisible by 3 if the sum of its digits is divisible by 3, so you can use an algorithm like this:
n = int(input("Enter a number:")) # get the number
sumOfDigits = sum([digit for digit in range(1,n+1)]) # sum numbers 1...n
if (sumOfDigits % 3 == 0): # check if the int is divisible by 3
print("YES")
else:
print("NO")
Here is one possible solution. It shows how you can test n the input and val the concatenated value
n = int(input("enter a number: "))
# This line creates a list of numbers and
# then concatenates them as a new number in string format
val = "".join(str(x) for x in range(1, n + 1))
print(f"Is {n} divisible by 3? ")
print("no" if int(n) % 3 else "yes")
print(f"Is {val} divisible by 3? ")
print("no" if int(val) % 3 else "yes")
You can write a one-line tertiary operation with a list comprehension to do this as well.
def check():
n = int(input("Enter a number:"))
return 'Yes' if int(''.join([str(i) for i in range(1,n+1)]))%3==0 else 'No'
check()
Enter a number:12
'Yes'
Use a range to produce numbers from 1 to N, convert them to strings and concatenate them:
x = 12
N = int("".join(map(str,range(1,x+1))))
div3 = N%3 == 0
print("Is",N,"divisible by 3?",["NO","YES"][div3])
# Is 123456789101112 divisible by 3? YES
enter image description hereEven Numbers!
Take input N from the user and print EVEN for every even number and ODD for every odd number between 1 and N.
Sample Input 1:
4
Sample Output 1:
ODD
EVEN
ODD
EVEN
You need to use the modulus opperator which is % in python to check if the number is odd or even.
N = int(input("Enter a number: "))
i = 1
while(i <= N):
if (i % 2) == 0:
print('EVEN')
else:
print('ODD')
i += 1
N = int(input())
for i in range(1,N+1):
if i%2 == 0:
print("EVEN".format(i))
else:
print("ODD".format(i))
n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)
This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Closed 4 years ago.
Here's my code:
total = int(input("How many students are there "))
print("Please enter their scores, between 1 - 100")
myList = []
for i in range (total):
n = int(input("Enter a test score >> "))
myList.append(n)
Basically I'm writing a program to calculate test scores but first the user has to enter the scores which are between 0 - 100.
If the user enters a test score out of that range, I want the program to tell the user to rewrite that number. I don't want the program to just end with a error. How can I do that?
while True:
n = int(input("enter a number between 0 and 100: "))
if 0 <= n <= 100:
break
print('try again')
Just like the code in your question, this will work both in Python 2.x and 3.x.
First, you have to know how to check whether a value is in a range. That's easy:
if n in range(0, 101):
Almost a direct translation from English. (This is only a good solution for Python 3.0 or later, but you're clearly using Python 3.)
Next, if you want to make them keep trying until they enter something valid, just do it in a loop:
for i in range(total):
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
break
myList.append(n)
Again, almost a direct translation from English.
But it might be much clearer if you break this out into a separate function:
def getTestScore():
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
return n
for i in range(total):
n = getTestScore()
myList.append(n)
As f p points out, the program will still "just end with a error" if they type something that isn't an integer, such as "A+". Handling that is a bit trickier. The int function will raise a ValueError if you give it a string that isn't a valid representation of an integer. So:
def getTestScore():
while True:
try:
n = int(input("Enter a test score >> "))
except ValueError:
pass
else:
if n in range(0, 101):
return n
You can use a helper function like:
def input_number(min, max):
while True:
n = input("Please enter a number between {} and {}:".format(min, max))
n = int(n)
if (min <= n <= max):
return n
else:
print("Bzzt! Wrong.")