Split a number into 3 parts - python

If there is number I want to split that number into 3 parts.
for example: num = 4563289
these have to split into 45 63 289
I just count the numbers.
count = 0
num = int(raw_input("enter the number :"))
while (num > 0):
num = num//10
count = count + 1
print ("Total number of digits:", count)
if count % 2 == 0:
print('even')
else:
print('Odd')
Using this code to identify whether it is odd or even.
Based on that i want to split the numbers into 3 parts.

Make the integer string and find its length. Something like this:
num = 4563289
num_str = (str(num))
a = int(len(num_str) / 3)
print('{} {} {}'.format(num_str[:a], num_str[a:2*a], num_str[2*a:]))
(result is 45 63 289)

Assuming your indentation is supposed to look like this:
count = 0
num = int(raw_input("enter the number :"))
while (num > 0):
num = num//10
count = count + 1
print ("Total number of digits:", count)
if count % 2 == 0:
print('even')
else:
print('Odd')
By the end, you cant split the number anymore, because it has been modified in the while-loop until it is 0. If you run it and let the program print the num variable at the end it always comes out as 0 because that is what you are telling the program to do. In my opinion its never a good idea to modify the original variable especially as its not easily retrievable.
Anyway, theres an easer way to tell whether the number of digits is odd or even, using the len() function:
num = int(raw_input("enter the number :"))
num_str = str(num)
print ("Total number of digits: " + str(len(num_str)))
if len(num_str) % 2 == 0:
print ("Number of digits is even")
else:
print ("Number of digits is odd")
Converting the input to a string makes sense, because it makes its length easy to determine and helps us with slicing the number up later. Now for the splicing, probably not the most elegant solution, but it works:
if len(num_str) >= 3:
newnum = str(num_str[0:2] + " " + num_str[2:4] + " " + num_str[4:])
print (newnum)

num = int(input('enter the Number you want check: ')
if num > 0 :
for i in range(0,num):
if ( num % 2) == 0:
print('its a even number')
break
else:
print('Its a odd number')
else:
print('its even number')

Related

How to print only the last result of an array of sum in python

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])

checking prime number in python

i wrote this program to check weather the no. is prime or not but it shows the number is prime multiple times. how can i solve it
To check weather the number is prime or not.
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
break
else:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
Here is my code to check whether a number is prime or not, hope it helps
# Program to Check whether given number is prime
def isPrime(number):
limit = int(number/2) # limit indicates how many times we need to run the loop
flag=0 # to keep track whether the number is prime or not
if number==0 or number==1:
print(f"The Given Number {number} is Not Prime")
return
for i in range(2,limit+1):
if number%i==0:
flag=1
break
if flag==0:
print(f"The Given Number {number} is Prime")
else:
print(f"The Given Number {number} is Not Prime")
isPrime(1)
Your problem is that the else part of your for-loop is wrong. You print "the number is prime" every time a division check fails, not just at the end.
I added an isPrime boolean that tracks if a single check failed. Only if none of them fail, you can print that the number is prime.
num = int(input("please enter the number you want to check\n"))
if num > 1:
isPrime = True
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
isPrime = False
break
if isPrime:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
You can simplify that even more, with a construct of python called for-else (credits to #TheGamer007):
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print("the number is not prime")
print(str(i) + " times " + str(num//i) + " is "+ str(num))
break
else:
print("the number is prime")
elif(num == 1):
print("the number is not prime")
else:
print('enter a positive value')
It works because Python's for-loops can have an else: following, which only triggers if you don't break out of the loop.
This might be exactly what you were trying to do. In that case, all you did wrong was your indentation.
Also, from an algorithmical point of view, there are much better ways to check. A first simple improvement is that you don't need to check range(2,num), but only range(2, int(math.sqrt(num))+1)
All you need in order to determine whether a number is prime or not, is to find 1 number that is greater or equal to 2 that divides the number.
In your loop, you print out a message that says "the number is prime" for each number that does not divide the given number.
For example, if you want to check whether the number 9 is prime or not, you will loop all numbers from 2 to 8 and check if they can divide 9. So in your for loop, the number 5 for instance -> 9%5 != 0 -> "the number is prime" message will pop up, which is wrong.
The code below shows how you can use a boolean to rise up a flag when the number is NOT prime.
num = int(input("please enter the number you want to check\n"))
isPrime = True
while num < 1:
int(input("enter a positive value\n"))
if num == 1:
print("the number is not prime")
return
for i in range(2, num):
if (num % i) == 0:
isPrime = False
break
print(str(num) + " is prime? " + str(isPrime))
Use a variable, for example flag and initialize it to 0. If the number is not prime,i.e i%2==0 set flag to 1 and break, else flag = 0 .
After that come out of the for block, and with the help of if condition display the number is prime or not. That is if flag==0 the number is prime else not.
I would suggest the following implementation
We only need to check/loop up to a square root of the number and not the number itself and is thus faster.
The for-else structure gets you rid of the isPrime flag that you otherwise need. The way this works is that if the loop finishes normally without breaking (meaning you haven't found what you are looking for) it goes into the else
import math
num = int(input("please enter the number you want to check\n"))
if num > 1:
for i in range(2, int(math.sqrt(num))+1):
if (num % i) == 0:
print("the number is not prime")
print(i, "times", num//i, "is", num)
break
else:
print("the number is prime")
else:
print("the number is not prime")
One way to do it:
def is_prime(n):
count = 0
if x > 1:
for i in range(1, n + 1):
if x % i == 0:
count += 1
return count == 2
number = int(input("Insert a number: "))
if is_prime(number):
print(str(number) + " is a prime number")
else:
print(str(number) + " is not a prime number!")
is_prime(7) # >> Returns True
How does it work:
A prime number (n) must fullfill the following rules:
n > 1;
n divisible only to 1 and itself(
n % 1 == 0,
n % n == 0)
Perform the modulus operation from 1 to n iteratively. Increment the variable count
every time the result is 0. If the input satisfies the 2nd condition from above then count should be equal 2. If count equals 2 then the number is prime.
Ex:
is_prime(7): 7 % 1 = 0 (count += 1), 7 % 2 = 1, 7 % 3 = 1, 7 % 4 = 3, 7 % 5 = 2, 7 % 6 = 1, 7 % 7 = 0 (count += 1); >> 7 is prime

Python Program to check if a number is armstrong or not is not working, what am I doing wrong?

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)

Python program prompts user to enter number until they enter 0, then program adds even and odd integers [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last month.
I'm taking a class in Python and our prof wants us to write a program that prompts the user to enter an integer repeatedly until they enter 0. Then, have the program ignore all negative numbers, if any, and display the number of even integers, the number of odd integers, the sum of the even integers, the sum of the odd numbers, and the number of positive integers.
I've been trying and trying to do this program in small parts. However, I always end up getting stuck. I've started over about 5 times now and I would really appreciate if someone were to point me in the right direction.
So far, I have this:
num_str = input("Input an integer (0 terminates):")
num_int=int(num_str)
even_count=0
odd_count=0
even_sum=0
odd_sum=0
while num_int !=0:
num_str = input("Input an integer (0 terminates):")
num_int=int(num_str)
for num_int in num_str:
if num_int%2 == 0:
even_count += 1
else:
odd_count +=1
print("")
print("Sum of odds:", odd_sum)
print("Sum of evens:", even_sum)
print("Even count:", even_count)
print("Odd count:", odd_count)
print("Total positive int count:")
I know it's not much and I'm missing a whole lot, but I just wrote what I know needs to be included so far. I keep getting stuck because the program keeps giving me errors. Any sort of help is very appreciated because I have really no idea where to start!
Your code has a few problems, but they're small:
1) You're asking for numbers before your main loop, so the first integer entered wouldn't be summed (lines 1 and 2)
2) It doesn't make sense for you to have a for loop like the one in your main loop. What you were doing is trying to check for each character in the string. Just not what you'd want.
3) To ignore negative numbers, just check if they're less than 0 and continue (break the loop) if they are.
4) You were using indentation with 3 spaces. It's probably your text editor's fault, so try to configure it to use 4 spaces instead, which is the standard in Python.
5) Convention says there should be a space around operators.
6) Positive integer count is just another simple counter.
All that revised, this is what your code should look like:
num_int = None
even_count = 0
odd_count = 0
even_sum = 0
odd_sum = 0
while num_int != 0:
num_str = input("Input an integer (0 terminates):")
num_int = int(num_str)
if num_int < 0:
continue # Continue the loop and go back to asking input
# If the loop reaches this point we know it's a positive number, so just add one
positive_count += 1
if num_int % 2 == 0:
even_count += 1
even_sum += num_int
else:
odd_count +=1
odd_sum += num_int
print("")
print("Sum of odds:", odd_sum)
print("Sum of evens:", even_sum)
print("Even count:", even_count)
print("Odd count:", odd_count)
print("Total positive int count:", positive_count)
You should declare a variable
total = 0
to count the number of integers the user has entered.
It's also more readable to have a
while True:
loop that breaks when the input is zero, instead of the loop you have.
Within the loop, you should
break
if the input is equal to 0,
continue
if the input is less than 1, increment even_count and add to even_sum if the input is even,
even_count += 1
even_sum += num
and increment the odd_count and odd_sum otherwise,
odd_count += 1
odd_sum += num
finally, you should increment the total:
total += 1
Also make sure to change the last line of your code to:
print("Total positive int count:", total)
to display the total
Your end result should look like this:
even_count = 0
odd_count = 0
even_sum = 0
odd_sum = 0
total = 0
while True:
num = int(input("Input an integer (0 terminates): "))
if num == 0:
break
if num < 1:
continue
if num % 2 == 0:
even_count += 1
even_sum += num
else:
odd_count += 1
odd_sum += num
total += 1
print("")
print("Sum of odds:", odd_sum)
print("Sum of evens:", even_sum)
print("Even count:", even_count)
print("Odd count:", odd_count)
print("Total positive int count:", total)
try this
userInput = None
oddSum = 0
oddCount = 0
evenSum = 0
evenCount = 0
while(userInput != 0):
userInput = int(input("Enter a number: "))
if(userInput > 0):
if(userInput % 2 == 0):
evenSum += userInput
evenCount += 1
elif(userInput % 2 != 0):
oddSum += userInput
oddCount += 1
print("even numbers: {} sum: {}".format(evenCount, evenSum))
print("odd numbers: {} sum: {}".format(oddCount, oddSum))
to ignore negative numbers, you could have them put it in agian, with an if loop like this
if (num_str>0):
num_str = input("That was not an even number, input an integer (0 terminates)")
Then to add them you would have to add the integer version of num_str to it like this
odd_sum += int(num_str)
here's some code for you to try
num_str = input("Input an integer (0 terminates):")
num_int=int(num_str)
even_count=0
odd_count=0
even_sum=0
odd_sum=0
total = even_count + odd_count
while num_int !=0:
num_str = input("Input an integer (0 terminates):")
num_int=int(num_str)
if num_int < 0:
num_str = input("Input an integer greater than 0.")
for num_int in num_str:
num_int = int(num_str)
if num_int % 2 == 0 and not num_int == 3 and not num_int == 0:
even_count += 1
even_sum = even_sum + num_int
elif not num_int == 0:
odd_count +=1
odd_sum = odd_sum + num_int
total = even_count + odd_count
print("")
print("Sum of odds:", odd_sum)
print("Sum of evens:", even_sum)
print("Even count:", even_count)
print("Odd count:", odd_count)
print("Total positive int count:", total)
val = []
inpt = None
evensm, oddsm = 0, 0
while inpt != 0:
inpt = int(input("Enter a number: "))
val.append(inpt)
for i in val:
if i % 2 == 0:
evensm += i
else:
oddsm += i
print("Sum of even integers is", evensm)
print("Sum of odd integers is", oddsm)
Or if you don't prefer using lists:
oddsm = 0
evensm = 0
while 1:
inpt = int(input("Enter a number: "))
if inpt == 0:
break
elif inpt % 2 == 0:
evensm += inpt
else:
oddsm += inpt
print("Sum of odd integers is", oddsm)
print("Sum of even integers is", evensm)
Write a Python program to take input of positive numbers, with an appropriate prompt, from the user until the user enters a zero. Find total number of odd & even numbers entered and sum of odd and even numbers. Display total count of odd & even numbers and sum of odd & even numbers with appropriate titles.
sumOdd =0
sumEven = 0
cntOdd =0
cntEven = 0
while True :
no = int(input("enter a number (0 for exit)"))
if no < 0 :
print("enter positive no......")
elif no == 0 :
break
elif no % 2 == 0 :
cntEven = cntEven+1
sumEven = sumEven + no
else :
cntOdd = cntOdd+1
sumOdd = sumOdd + no
print ("count odd == ",cntOdd)
print ("sum odd == ",sumOdd)
print ("count even == ",cntEven)
print ("sum even == ",sumEven)
Write a Python program to take input of a positive number, say N, with an appropriate prompt, from the user. The user should be prompted again to enter the number until the user enters a positive number. Find the sum of first N odd numbers and first N even numbers. Display both the sums with appropriate titles.
n = int(input("enter n no.... : "))
sumOdd =0
sumEven = 0
for i in range (n) :
no = int(input("enter a positive number : "))
if no > 0 :
if no % 2 == 0 :
sumEven = sumEven + no
else :
sumOdd = sumOdd + no
else :
print("exit.....")
break
print ("sum odd == ",sumOdd)
print ("sum even == ",sumEven)

how to make a python program using "while" to print at 0?

My assignment is to make a program that prompts the user to input numbers to be categorized as even or odd. It will then add them together and count the amount of inputs of evens or odds. So far, I have that down, but I can't figure out how to get my program to run through the outputs when 0 is typed in.
Here's my code:
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
sum = float(count_odd) + float(count_even)
while number >= 0:
if number%2 == 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number == zero:
print("Sum of odds: " +odd_sum)
print("Sum of evens: " + even_sum)
print("Odd count: " +count_odd)
print("Even count: " +count_even)
print("Total positive int count:" +sum)
else:
number = int(input("Input an integer (0 terminates the program): "))
I'm not even sure the ending is right at all. Especially not my attempt at creating a "zero."
Your current program does not work because 0 % 2 is also 0 , so it will go into the if block and it will never reach the elif number == zero: block.
You should move your elif to the top to become an if and move the if to elif , for your logic to work. and also, if you want to loop to break at 0 , you should add break statement in the number == zero block. Example -
while number >= 0:
if number == 0:
print("Sum of odds: ", odd_sum)
print("Sum of evens: ", even_sum)
print("Odd count: ", count_odd)
print("Even count: ", count_even)
print("Total positive int count:", even_sum + odd_sum)
break
elif number%2 == 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
Other issues that I noticed in your program -
"Sum of odds: " +odd_sum would not work because you cannot add int and string like that, instead pass them as separate arguments to the print .
You do not need the else: part, as it would never reach there.
When you input "0", this condition is true as well:
if number%2 == 0:
So your program counts the "0" as a valid input (an even number).
Try comparing with zero first, then the rest of the ifs.
Also, you should use a "break" to end the program when "0" is inputted.
Try this version:
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
sum = float(count_odd) + float(count_even)
while number >= 0:
if number == zero:
print("Sum of odds: ", odd_sum)
print("Sum of evens: ", even_sum)
print("Odd count: ", count_odd)
print("Even count: ", count_even)
print("Total positive int count:", sum)
break
elif number%2 == 0:
print "a"
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
else:
number = int(input("Input an integer (0 terminates the program): "))
I made some changes and addressed them with comments, the main problem was that you should have been checking for zero with the first conditional statement in your while loop.
# Setup your variables
# I removed the input line from here, since we only need to get input in the while loop
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
# Use a simple boolean flag to tell the while loop to keep going
keep_going = True
while keep_going == True:
# Grab the number from the user
number = int(input("Input an integer (0 terminates the program): "))
# IMPORTANT - Check for zero first
# If it is zero, set out flag to false, so we will exit the while loop
if number == 0:
keep_going = False
elif number % 2 == 0:
count_even += 1
even_sum += number
elif number % 2 != 0:
count_odd += 1
odd_sum += number
# Here we have exited the while loop
sum = float(count_odd) + float(count_even)
# Print everything here
To fully make your script function you'll need this:
import sys # allows the script to end after 0 properly
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
summation = float(count_odd) + float(count_even) # don't use sum because it's already taken by python, and you can also remove it, see below why
while number >= 0:
if number%2 == 0 and number != 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number == 0: # pay attention to the concatenation of strings, not string and integer
print("Sum of odds: " + str(odd_sum))
print("Sum of evens: " + str(even_sum))
print("Odd count: " + str(count_odd))
print("Even count: " + str(count_even))
summation = float(count_odd) + float(count_even)
print("Total positive int count:" + str(summation)) # add everything up after it's been done NOT before
sys.exit() # to stop your infinite loop
else:
number = int(input("Input an integer (0 terminates the program): "))

Categories

Resources