Apologies if the question to this is worded a bit poorly, but I can't seem to find help on this exercise anywhere. I am writing a basic Python script which sums two numbers together, but if both numbers inputted are the same the sum will not be calculated.
while True:
print('Please enter a number ')
num1 = input()
print('Please enter a second number ')
num2 = input()
if num1 == num2:
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
If both numbers are equal I want the script to loop back once more and if the numbers inputted are equal again I want the program to end. With the code I have provided the issue I am having is that when I enter two equal numbers it keeps constantly looping until I enter two different numbers.
You would likely want to have a variable keeping track of the number of times that the numbers were matching. Then do something if that counter (keeping track of the matching) is over a certain threshold. Try something like
matches = 0
while True:
num1 = input('Please enter a number: ')
num2 = input('Please enter a second number: ')
if num1 == num2 and matches < 1:
matches += 1
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
You can add give input code again inside first if statement or use some other dummy variable for loop so that you can break the loop, for e.g. use while j == 0 and increase it j += 1when you are inside the first if statement
continue skips the execution of everything else in the loop. I don't see it much useful in your example. If you want to print the sum then just remove it.
How continue works can be demonstrated by this sample (taken from python docs)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
Result
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
Related
I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()
my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern
if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6
this is the problem
there is logical error in program .Help in resolving it`
this is the complete detail of my program
i have tried it in this way
**********python**********
while(1):
a=int(input("Enter any three digit no"))
if(a<100 or a>999):
print("enter no again")
else:
s = 0
while(a>0):
k = a%10
a = a // 10
s = s + k
print("total",s)
there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123
total=6 but i m getting total=3 then total=5 and in last total=6 one line of output is coming in three lines
If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.
import re
while True:
num = input("Enter number: ")
match = re.match(r"^\d{3}$, num)
if match:
numList = list(num)
sum = 0
for each_number in numList:
sum += int(each_number)
print("Total:", sum)
else:
print("Invalid input!")
Additionally, you can verify via exception handling, and implementing that math you had instead.
while True:
try:
num = int(input("Enter number: "))
if num in range(100, 1000):
firstDigit = num // 10
secondDigit = (num // 10) % 10
thirdDigit = num % 10
sum = firstDigit + secondDigit + thirdDigit
print("Total:", sum)
else:
print("Invalid number!")
except ValueError:
print("Invalid input!")
Method two utilizes a range() function to check, rather than the RegEx.
Indentation problem dude, remove a tab from last line.
Also, a bit of python hint/tip. Try it. :)
a=123
print(sum([int(x) for x in str(a)]))
I am new to coding and I'm trying to figure a simple code. The user will input a number, that must be an integer greater than 0, then asked to enter a second integer, greater than the previous one. once the second value is entered the two inputs should be displayed as well as the even and odd numbers in-between the two inputs. Currently, the code I have doesn't distinguish the value of the second input, allowing it to be lesser than the previous one.
number = input('please enter a number:')
val = int(number)
if val > 0:
integer = raw_input('please pick a second integer:')
if raw_input < val:
print 'please pick an integer greater than the previos input'
if raw_input > val:
print
if val < 0:
print 'please pick a positive integer greater than zero'
You could ask for the inputs before the while loop check and then ask again, but I like the cleaner appearance of only having the input prompt appear once in the code, so we can set up some conditions that will trigger the loop and the prompt.
We can initialize num1 = -1 and then our while loop condition will be triggered and repeat until we receive and int larger is larger than 0.
Then we can do the same with num2 by initializing it as num1 - 1, this will trigger our while loop that will continue to prompt until num2 is greater than num1.
Finally we can print a list of the range from num1 to num2 + 1 since the end is not inclusive we should extend the range by 1
num1 = -1
while num1 <= 0:
num1 = int(input('Enter a number greater than 0: '))
num2 = num1 - 1
while num2 <= num1:
num2 = int(input('Enter a number greater than {}: '.format(num1)))
print(list(range(num1, num2+1)))
Enter a number greater than 0: 1
Enter a number greater than 1: 5
[1, 2, 3, 4, 5]
So i have to make a program in python using a while loop. It goes like this: input an integer until it is 0.the program has to write out how many of inputed numbers has at least 1 odd digit in it.i don't know how to find odd digits in a number for which i don't know how many digits it has.i need this for school :/
As others have commented, the question you have asked is a little unclear. However, perhaps this is something like you are looking for?
odd_count = 0
user_number = None
# Ask for a user input, and check it is not equal to 0
while user_number != 0:
user_number = int(input("Enter and integer (0 to quit): "))
# Check for odd number by dividing by 2 and checking for a remainder
if user_number % 2 != 0:
odd_count += 1 # Add 1 to the odd number counter
print("There were {} odd numbers entered".format(odd_count))
number=int(input())
i=0
odd_number_count=0
while number>0:
for k in str(number):
if int(k)%2==0:
i=0
else:
i=i+1
if i>>0:
odd_number_count=odd_number_count+1
number=int(input())
print(odd_number_count)
this is how i solved it
Objective: * Write a python program that repeatedly prompts for input of a positive number until the sum of the numbers is greater than 179. Use at least three modules/functions in your solution.
* The largest number entered cannot exceed 42.
* When the sum of the numbers exceeds 179, print the sum of the numbers, the largest number entered and smallest number entered.
I just need some guidance, specifically for the "input_numbers" module. There must be an easier way to do this than to make a variable for each number. The code is not complete. I haven't even started on the two other modules yet. Thanks in advance.
def input_numbers():
while True:
num1 = raw_input("Enter a positive integer no greater than 42 ")
if num1 <= 0:
print "That is not a positive integer. Try again "
elif num1 > 42:
print "The number cannot exceed 42. Try again "
num2 = raw_input("Enter another positive integer ")
if num2 <= 0:
print "That is not a positive integer. Try again "
elif num2 > 42:
print "The number cannot exceed 42. Try again "
num3 = raw_input("Enter another positive integer ")
if num3 <= 0:
print "That is not a positive integer. Try again "
elif num3 > 42:
print "The number cannot exceed 42. Try again "
num4 = raw_input("Enter another positive integer ")
if num4 <= 0:
print "That is not a positive integer. Try again "
elif num4 > 42:
print "The number cannot exceed 42. Try again "
num5 = raw_input("Enter another positive integer ")
if num5 <= 0:
print "That is not a positive integer. Try again "
elif num5 > 42:
print "The number cannot exceed 42. Try again "
elif sum(num1, num2, num3, num4, num5) > 179:
print_numbers()
add_numbers()
def add_numbers():
print_numbers()
def print_numbers():
input_numbers()
You can knock out all three function requirements by encapsulating each step of your program. Rather than having your loop inside of a function, we'll let main control the loop, and we'll control the flow by passing data into and out of function calls.
Let's rework your input_numbers() function a bit.
def get_input_number():
num = int(raw_input("Enter a positive integer no greater than 42 "))
if num <= 0 or num > 42:
print "Invalid input. Try again "
get_input_number()
else:
return num
So, instead of having input_numbers control the loop as well as the input handling and validation, we have it do just what its name implies: It asks for input, validates it, and then, if it's good, it returns the value to the caller, but if it's bad, it writes a message, and calls itself again to the user can enter good input.
The next function we'll set up is straight from your list of requirements. From all of the numbers that the user enters, we need to find the biggest one. From the language alone, we can determine that we're looking through a set of numbers, and thus, this is a good place to break out a list. Assuming we store all of the users input in a list, we can then pass that list to a function and perform operations on it, like so.
def get_greatest_number(input_list):
highest = input_list[0]
for i in input_list:
if i > highest:
highest = i
return highest
We set the first element of the list to a variable highest and then check all other elements in the list against that initial value. If we find one that's bigger, we then reassign the highest variable to the element that was bigger. Once we do this for each element in the list, the number inside of highest will now be, just that, the highest number, and so, we'll return it to the main program.
Similarly, we can do the same for finding the smallest.
def get_smallest_number(input_list):
smallest = input_list[0]
for i in input_list:
if i < smallest:
smallest = i
return smallest
Finally, we get to our main loop. Here we declare an empty list, number_list to store all the numbers in. And we use the sum of that as our loop condition.
if __name__ == '__main__':
number_list = []
while sum(number_list) < 179:
number_list.append(get_input_number())
In the body of the loop, we call our get_input_number() and append its result to the list we made. Once the sum of the numbers in the list exceed 179, the while loop will exit and we can finally show the user the results.
print
print '-------------------------'
print 'total of numbers entered: %d' % sum(number_list)
print 'greatest number entered: %d' % get_greatest_number(number_list)
print 'smallest number entered: %d' % get_smallest_number(number_list)
Here we can the get_greatest_number and get_smallest_number we made, and we give them the list of numbers as an argument. They'll loop though the lists, and then return the appropriate values to the print statements.
Yes, of course there's a better way than making a variable for each number. Store them in a list. Storing them in a list also makes finding their sum and the highest and lowest value easy (there are built-in functions for this).
As a further hint, you'll want to use two loops, one inside the other. The outer loop keeps the user entering numbers until their sum exceeds 179. The inner loop keeps the user entering a single number until it's between 1 and 42 inclusive.
def get_int(prompt=''):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def get_values():
values = []
total = 0
while total <= 179:
val = get_int('Enter a positive integer <= 42: ')
if 0 <= val <= 42:
values.append(val)
total += val
return values
def print_info(values):
print 'Sum is {}'.format(sum(values))
print 'Largest value is {}'.format(max(values))
print 'Smallest value is {}'.format(min(values))
def main():
values = get_values()
print_info(values)
if __name__=="__main__":
main()
You can repeatedly poll the number in a loop, and add the inputs into a list, e.g.
def input_numbers():
user_inputs = [] # a list of all user's inputs
while True:
num = raw_input("Enter a positive integer no greater than 42 ")
try:
num = int(num) # convert input string to integer
if num <= 0:
print "That is not a positive integer. Try again "
elif num > 42:
print "The number cannot exceed 42. Try again "
user_inputs.append(num)
except ValueError: # conversion to integer may fail (e.g. int('string') ?)
print 'Not a Number:', num
if some_condition_regarding(user_inputs):
break # eventually break out of infinite while loop
here some well-known tricks:
def min_and_max(your_num_list)
min=your_num_list[0]
max=your_num_list[0]
for num in your_num_list:
if num < min:
min=num
if max > num
max=num
return min,max
When you're writing a standalone Python program, it’s a good practice to use a main function. it allows you to easily add some unit tests, use your functions or classes from other modules (if you import them), etc.
And as others already said, it is a good idea to create a list and append a new element to it each time the user enters a valid number (until the sum of the numbers axceeds 179). If user entered an incorrect value, then just don’t append anything to the list and skip to the next iteration (so the user will be asked to enter a number again).
So basically it could look like this:
def validate_entered_number(num):
"""
Checks if the number is positive and is less or equal to 42.
Returns True if the number matches these conditions,
otherwise it returns False.
"""
if num < 0:
print "That is not a positive integer."
return False
if num > 42:
print "The number cannot exceed 42."
return False
return True
def main():
entered_numbers = []
while True:
try:
num = int(raw_input("Enter a positive integer less or equal to 42: "))
except ValueError:
print "You should enter a number"
continue
if validate_entered_number(num):
entered_numbers.append(num)
if sum(entered_numbers) > 179:
print "The sum of the numbers is %s" % sum(entered_numbers)
print "The smallest number entered is %s" % min(entered_numbers)
print "The largest number entered is %s" % max(entered_numbers)
return
if __name__ == "__main__":
main()
In fact, I can imagine a situation where you would want to just store the sum of the numbers, the smallest number and the largest number in three variables and update these variables in each iteration (add current number to the sum and compare it to the currently known smallest and larger numbers and update the corresponding variables when necessary), but in this case the longest list you can possibly have is only 180 elements (if all numbers are 1 and the user doesn’t enter 0 or you have modified the program to deny entering 0), which is very small amount of elements for a list in Python. But if you had to deal with really big amounts of numbers, I’d recommend to switch to a solution like this.
Thanks to everyone who answered. I've written the following code and it works nearly perfectly except the last module. If you exit the program after the first run (by pressing 0) it will exit, but if you run it a second time pressing 0 won't make it exit. It'll just go back to the beginning of the program. I don't know why.
Note: The assignment has various requirements that I had to incorporate in my code. Hence the unnecessary modules, global variables, and comments.
maxNum = 42 # declares global variable maxNum
target = 179 # declares global variable target
def user_input(): # prompts user to input a number 42 or less until all add up to 179
x = 0
nums = []
while sum(nums) <= target:
nums.append(int(raw_input("Enter a number: ")))
if int(nums[x]) > int(maxNum):
print "Number cannot exceed 42."
user_input()
else:
x += 1
print_nums(nums,x)
def print_nums(nums,x): # prints the sum of the numbers, the smallest, and the largest
print "Sum of all numbers is", sum(nums)
nums.sort()
x -= 1
print "Largest number entered is", nums[x]
print "Smallest number entered is", nums[0]
decide()
def decide(): # allows user to continue the program or exit
exit = raw_input("<9 to enter a new set of number. 0 to exit.> ")
while True:
if int(exit) == 0:
return
elif int(exit) == 9:
user_input()
user_input()