Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Let's say x is an integer number. How can I print every even digit of this number?
For example, if the input is 34567910, then I want the output to be 4 6 9 0.
I know how to print every single digit using the following code, but I can't figure out how to print even digits only:
for i in str(x):
print(i)
Here is the solution to your problem. Note that I have to check if i is odd, due to Python indexes starting from 0. For example, in Python, an index of 1 is the second position.
num = input("Enter a number: ")
return_num = ""
# Iterates through input
for i in range(len(num)):
# Checks if digit is at even position
if i % 2 == 1:
# If so, adds it to return_num
return_num += num[i] # + " " if you want spaces between numbers
print(return_num) # Prints 4690 with your input
Alternatively, you could achieve this using one for-loop. (Credit to OneCricketeer.)
num = input("Enter a number: ")
return_num = ""
# Iterates through specified indexes of input
for i in range(1, len(num), 2):
return_num += num[i] # + " " if you want spaces between numbers
print(return_num) # Prints 4690 with your input
Or, if you want to have the shortest program humanly possible to solve your problem (Credit to Tomerikoo):
num = input("Enter a number: ")
print(num[1::2]) # Prints 4690 with your input
This is one way how you can do it
# iterate over string
x = 34567910
string = str(x)
for index in range(len(string)):
# check if index is divisible by 2
if index % 2 != 0:
# print character at index
print(string[index], end = '')
x = str(input())
Try using slicing and map method:
list(map(int, list(x)[1::2]))
[4, 6, 9, 0]
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
#WAP to check given number is Armstrong or not, (done)
#if it is Armstrong then print reverse of that number, (done)
#if it is not Armstrong then check it is Palindrome or not. (problem)
no=int(input("Enter your number:"))
temp=no
arm=0
rev=0
while(no>0):
rem=no%10
cube=rem*rem*rem
arm=arm+cube
no=no//10
if(temp==arm):
while (temp> 0):
rem = temp % 10
rev = (rev * 10) + rem
temp = temp // 10
print("Reverse is:", rev)
elif(temp!=arm):
while (temp > 0):
rem = temp % 10
rev = rev * 10 + rem
temp = temp // 10
if(rev==temp):
print("It's a palindrome.")
else:
print("It's not a palindrome.")
I can't find out the problem with the "check if it is a palindrome" part.
In your code to check for palindrome, you are repeatedly dividing your temp value by 10, but your condition is for temp>0 which will never be reached, as repeated division by 10 will never result in a negative number. So, you should change your condition to while(temp>=1).
Also, you should compare the final value of rev to no instead of with temp.
So if you change your final condition to if(rev==no): it should work. This is because your temp keeps getting modified in your loop to check for palindrome, whereas you want to compare your final rev with the original number.
Try this to check if number is palindrome or not
if str(temp)==str(temp)[::-1]:
print("Number is palindrome")
else:
print("Not palindrome")
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want a program that sums the even numbers of a bigger number using while function.
Exemple :
Number is : 12345
Print : 6 (2+4)
This is what i wrote so far:
num = int(input("Introduce a non negative number: "))
if num % 2 == 0:
sum += num
print("sum")
I can't stress this enough
When doing school assignments, the whole idea with assignments is to teach you concepts, not solutions. There's a reason why you were given this assignment, asking others to solve it for you - is not the way to go.
Go back to your teacher, and ask for help if something is unclear. But because others start posting solutions I might as well just keep mine here.
Skipping the conversion to an early integer, will allow you to iterate over it as a string, and grab one number a a time.
num = input("Introduce a non negative number: ")
total = 0
for i in num:
if int(i) % 2 == 0:
total += int(i)
print("sum:", total)
You can then use your original logic, with some minor modifications.
Since for whatever reason, you're only allowed to use while and not for, you'd have to just adapt a bit.
num = input("Introduce a non negative number: ")
total = 0
i = 0
while i < len(num):
if int(num[i]) % 2 == 0:
total += int(num[i])
i += 1
print("sum:", total)
While I'm at it, after reading my code again. I am quite sure that a while loop here is the least pretty solution to this problem. But from a teaching standpoint there might be some benefit here. But I'd recommend going with the for loop if at all possible.
Try this one:
# split the number to list of digits
digits_list = list(input("Introduce a non negative number: "))
total = 0
# loop over the digits list and pick a digit till the list is empty
while digits_list:
digit = digits_list.pop()
if int(digit) % 2 == 0:
total += int(digit)
print(total)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am requesting someone to tell me a program that asks a user to input only 9 digits. Number 0 not at start but having 9 digits.
How can I limit the number of digits?
For example:
Num=int(input('please Enter a Number'))
if num?!
Please help me soon.
If i got this right this should work:
a=input()
if len(a)==9 and a[0] != '0' and a.isdigit():
#if you want it to be integer
a=int(a)
do something
Hope it helps.
Well if I understood correctly you need a program that asks the user to enter exactly 9 digits. In that case it's pretty simple.
i = input("Enter a nine digit number: ")
if len(i) != 9:
print("You must enter 9 digits!")
quit()
if not i.isdigit():
print("Your input must be a number!")
quit()
# num is a 9 digit integer
# i is a 9 digit string
num = int(i)
You can do this.
num = input('Please enter a number')
if not num[0] == "0" and len(num) == 9 and num.isdigit():
# You can print a message or cast the num into an integer here
# like this: input_number = int(num)
print(True)
else:
print(False)
So what's happening here is that the program will accept the user input and evaluate if the first digit is NOT 0 AND that the length is exactly 9 characters.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have been going through an introduction to python booklet and have been stuck on the following question. the question is outlined below and my attempt follows after the question.
Take this program:
m = 0
finished = False
while not finished:
print('Enter another whole number (0 to finish): ', end = '')
s = input()
num = int(s)
if num != 0:
if num > m:
m = num
else:
finished = True
print(str(m))
If you have worked out what the above program does, can you see that,
for certain series
of numbers, it will not produce the correct output? In what
circumstances will it not
work correctly, and how could you change
the program to make it work properly?
My understanding is that the series of numbers, where the above program will fail, are decimal numbers (non-whole number), therefore my attempt is as follows:
m='0'
finished = False
while not finished:
print('enter number, 0 to finish: ', end = '')
num = input()
if num != '0':
if num > m:
m = num
else:
finished = True
print(m)
However this fails at understanding that 77 is larger than 8 since it is reading it as a string.
This program calculates the maximum value from the inputted sequence. It stores the maximal value in m, and if a num is inputted that's larger than it, it keeps it as the new maximum.
However, note that m is initialized with 0, making the implicit assumption that at least one number you'll input is positive. If you input only negative numbers, you'll get 0 as the largest number, which is clearly wrong, as you never inputted it.
A quick fix could be to initialize m with None and explicitly check for it:
m = None
finished = False
while not finished:
print('Enter another whole number (0 to finish): ', end = '')
s = input()
num = int(s)
if num != 0:
if not m or num > m:
m = num
else:
finished = True
print(str(m))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have the following code to print the (distinct numbers), but I'm trying to check the inputs before the process, should be ten digits numbers only with only one space.
I tried while and try but still can't figure out:
def main():
list1 = input("Enter ten numbers: ").split()
set1 = set(list1)
print(set1)
list2 = list(set1)
string = string.join(list2)
print("The distinct numbers are: " + str(string))
main()
A simpler version using the isnumeric() method built in strings. Also, I put a loop around the input so as the user can easily retry in case of wrong data:
def main():
while(True):
numbers = input("Enter ten space-separated numbers: ").split()
if len(numbers) != 10 or not all(n.isnumeric() for n in numbers):
print("Wrong input, please retry")
continue
numbers = ' '.join(set(numbers))
print("The distinct numbers are:", numbers)
break # or return numbers if you need the data
main()
Do you mean check if there are ten numbers inputted?
import re
def check_input(input_string):
compare_to = '\s'.join(10*['\d+'])
if re.match(compare_to[:-1], input_string):
return True
return False
This is a regular expression, it checks if the input string is equal to a specified input format. This one specifically checks whether 10 sets of at least 1 number [\d+] are added with a space inbetween \s.