intro to python - series of numbers [closed] - python

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

Related

Determining if a number is a palindrome [closed]

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

How can I print digits at even indexes of a number? [closed]

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]

Program that prompts the user for a non-negative integer n, and then writes a sum of the even digits of n [closed]

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)

Receiving integers from the user until they enter 0 [closed]

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 3 years ago.
Improve this question
It's my 2nd week in programming in Python and have never programmed anything before. appreciate step by step.
I don't know where to start.
try:
count = 0
while True:
user = int(input('Insert Number: '))
count += user
if user == 0:
break
print(count)
except ValueError:
print('Please Insert Numbers Only!')
Here a start, use a while loop for the input. I'll leave the summation part for you unless you need further help:
cc = int(input("Enter an integer to sum. Press 0 to to end and start the summation:"))
while cc != 0:
cc = int(input("Enter an integer to sum. Press 0 to to end and start the summation:"))
def is_int(num):
try:
return int(num)
except:
return False
total = 0
while True:
in_user = is_int(input("input integer: "))
if in_user is not False:
total += in_user
if in_user is 0:
break
print(total)

While Loop Concatenation Exercise [closed]

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 5 years ago.
Improve this question
I'm just starting to learn Python and have a question regarding an exercise that came up in the textbook I'm reading.
I found a solution that does function, but I'm wondering if there is a simpler/recommended solution?
Problem:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ' '
#concatenate X to print numXs times print(toPrint)
My solution:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ''
while (toPrint == ''):
if numXs == 0:
numXs = int(input('Enter an integer != 0 '))
else:
toPrint = abs(numXs) * 'X'
print(toPrint)
I'd suggest you get all your data checking and correction handled up front, so your actual algorithm can be much simpler:
numXs = 0
while numXs <= 0:
numXs = int(input('How many times should I print the letter X? '))
if numXs <= 0:
print('Enter an integer > 0')
print('X' * numXs)
A simple solution would be
try:
print("x" * int(input("how many times?")))
except:
print("you entered an invalid number")
If you want a zero or negative check
try:
num = int(input("how many times?"))
if num > 0:
print("x" * num)
else:
print("need a positive integer")
except:
print("not a number")
If you want this to happen forever, just wrap it in a while loop
while True:
#code above
You are not handling wrong conversions (input of "Eight") - so you could shorten it to:
print(abs(int(input("How many?")))*"X") #loosing the ability to "requery" on 0
Same functionality:
numXs = abs(int(input('How many times should I print the letter X? ')))
while not numXs: # 0 is considered FALSE
numXs = abs(int(input('Enter an integer != 0 ')))
print(numXs * 'X')
Safer:
def getInt(msg, errorMsg):
'''Function asks with _msg_ for an input, if convertible to int returs
the number as int. Else keeps repeating to ask with _errorMsg_ until
an int can be returned'''
i = input(msg)
while not i.isdigit():
i = input(errorMsg)
return int(i)
I am using isdigit() to decide if the input is a number we can use. You could also do try: and except: around the int(yourInput) so you can catch inputs that are not conversible to integers:
def getIntWithTryExcept(msg, errorMsg):
'''Function asks with _msg_ for an input, if convertible to int returs
the number as int. Else keeps repeating to ask with _errorMsg_ until
an int can be returned'''
i = input(msg) # use 1st input message
num = 0
try:
num = int(i) # try convert, if not possible except: will happen
except:
while not num: # repeat with 2nd message till ok
i = input(errorMsg)
try:
num = int(i)
except: # do nothing, while is still True so it repeats
pass
return int(i) # return the number

Categories