Python: Display and count divisors of two integers - python

Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.
This is what I have written so far, but I am stuck here I dont know how to incorporate both numbers. Essentially I do not know where to go from here or if 'here' is even correct???
Please help...[This is my first time with python]
integer1 = input("Enter an integer: ")
integer2 = input("Enter an integer: ")
print integer1, ": " ,
i = 1
while i <= integer1 and integer2 :
if integer1 or integer2 < 1 :
print input("Enter an integer: ")
if integer1%i == 0 and integer2%i == 0 :
print i ,
i = i + 1

Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:
Get first number
Get second number
Calculate
This you can break down futher
Get first number:
Get Number from User
Loop while Number is not ok
...
This way you can see that the validation should not be inside the while loop.
Another tip: test each step separately. This way you will find that if integer1 or integer2 < 1 or while i <= integer1 and integer2 will not work the way you think they do.

This is not how logical operators work in Python or programming in general.
while i <= integer1 and integer2 :
In Python integer2 is a separate logical statement that is always true.
Try instead:
while i <= integer1 and i <= integer2

You'll want to move the code that
validates your input outside of the
loop.
Your print i doesn't need a
comma.
The syntax in your flow
control needs a bit of work, for
example if integer1 or integer2 <
1: should be if ((integer1 < 1) or
(integer2 < 1)):.

First we should do a simple way to get both integers; noting there could be multiple errors. (Even better would be raw_input and checking the number resolves to an int).
integer1 = -1
integer2 = -1
while(integer1 < 1):
integer1 = input("Enter integer 1: ")
while(integer2 < 1):
integer2 = input("Enter integer 2: ")
factor_list1 = [] # store factor list of first number
double_factor_count = 0
# generate the factor list of the first number
for i in range(1, integer1+1): # range(1,5+1) is the list [1,2,3,4,5]
if integer1 % i == 0:
factor_list1.append(i)
for j in range(1, integer2+1):
if integer2 % j == 0 and j in factor_list1:
print j,
double_factor_count += 1
print "\n double count:", double_factor_count
Possibly you want to change it to range(2, integer1) if you want to skip 1 and the integer typed in as numbers.
Note your original code wasn't indented (so didn't appear as code in the forums, and that and and or combine expressions (e.g., things that are True or False). So you meant if integer1 < 1 or integer2 < 1:.

Your code is actually very close, but you have a few problems:
You're not validating integer1 and integer2 correctly (though I suspect you know that, since you're just printing the replacement value).
Your loop test is broken. What you've written means "i is less than integer1, and also integer2 isn't zero".
You can also improve your code in a couple of ways:
Ensuring that your input is not only >= 1, but also an integer.
Using a for loop instead of a while loop, using Python's excellent iterables support.
Here's how to make sure that what the user typed was an integer:
integer1 = 0
while not integer1:
try:
# raw_input() ensures the user can't type arbitrary code
# int() throws a ValueError if what they typed wasn't an integer
integer1 = int(raw_input("Enter the first integer: "))
if integer1 < 1:
print "You must enter an integer greater than 0!"
integer1 = 0 # so that our while statement loops again
except ValueError:
# the user typed something other than an integer
print "You must enter an integer!"
The while, try, and if statements here ensure that the user will be forced to enter a valid integer before your code continues. Here's an example of what the user sees:
Enter the first integer: 6.6
You must enter an integer!
Enter the first integer: -5
You must enter an integer greater than 0!
Enter the first integer: sys.exit(0)
You must enter an integer!
Enter the first integer: 12
Enter the second integer:
And this is how I'd recommend setting up your loop:
# min() returns the smallest of its arguments
# xrange() iterates over a sequence of integers (here, starting with 1 and
# stopping at min(integer1, integer2))
for i in xrange(1, min(integer1, integer2) + 1):
# magic goes here!
Documentation links:
int()
min()
raw_input() and input()
xrange()

Your problem is with your if statements.
Rather than saying: while i <= integer1 and integer2, you need to say while i <= integer1 and i <= integer2
The same applies for your other if statement. if integer1 or integer2 < 1 : should be if integer1 < 1 or integer2 < 1 :

Related

Python if statement not computing value

First baby steps into Python and I'm stuck. I want to print the absolute value of an integer that is input by the user. If the integer that is input is a negative value, I want it to return a positive value. I'm converting the string to an integer fine, I'm storing the input 'number' fine, but if I input a negative number it's not doing the eval of the if statement and converting to a positive number by * -1 as you see below. I'm at a loss, should I be defining another variable somewhere here?
number = int(input('Please enter a number: '))
if number <= 0:
number = number * -1
I performed the tests on my machine and the operation went correctly. Is it returning an error for you?
As a suggestion, you can also use the abs() function instead of multiplying by -1 to return the absolute value of a number.
Example :
abs(-5) ---> 5
abs(5) ---> 5
try this:
num = int(input("Please enter a number:"))
if num <= 0:
num = abs(num)
Python has a lot of built-in functions that help do simple tasks like this.
The abs() function returns the absolute value of any float/int/etc. you put into it.
You can also do this all in one line if you wish, you would use the same abs() function. This time around it can be in a try-except block which will handle any bad input like "18asdfnsjkdf" for example.
try:
num = abs(int(input("Enter a number:")))
except ValueError:
pass
Your code works, add a print statement and be careful of indentation issues:
number = int(input('Please enter a number: '))
if number <= 0:
number = number * -1
print(number)
Output is:
Please enter a number: -5
5

How do I sum numbers from user input in python?(only if they are even numbers)

I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")

Finding the next entity in a list python

I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!
You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary

How do I omit strings and other characters within conditionals in Python 3?

I'm trying to create a small code that asks a user to enter a number between 1 and 100. However my Else statement will not output when entering a string. I want my Else statement to print a message if the user enters an input other than an integer or float. Here is my code.
def between():
print ("Please enter a number between 1 and 100.")
number = eval(input())
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
elif number > 100 or number < 1:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
else:
print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
between()
between()
The easiest method would be to use try and except
num = input()
try:
number = float(num)
# code to do if num is a number
except ValueError:
print("Not a number!")
# code to do if num isn't a number
If num isn't a number, then converting it to a float would raise ValueError going on to the except.
If num is a number, the coversion of it to a float would run fine, and continue on in the try.
Side note: I highly suggest not using eval(input()) but rather just input(), see this for why you shouldn't use eval. Also eval(input()) won't work with my example above.
Try this:
print "Please enter a number between 1 and 100"
in = input()
try:
num = int(in)
if 1 <= num <= 100:
print("Valid")
else:
print("Out of bounds")
except:
print("Invalid")
Try:
def between():
print ("Please enter a number between 1 and 100.")
number=0
try:
number = int(input())
except:
print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
exit(1)
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
else:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
between()
Note: why you use eval and input together? I don't think that's right, correct me if I'm wrong
There are a few logical issues with your code. First before using eval() you must be aware of the security risk associated with it. Consider going through this post for some insight. If you entered some arbitrary input in eval, it will most likely be a run time error.
Now, assuming that the variable actually has a value. To check if it is an integer or a float and is in the desired range or something else (possibly a string), you can not directly apply comparison operators with it because if the variable is not a number it will most likely give a TypeError during comparison with other integers.
Hence a correct approach would be to first check if the variable is of desired type by checking if type(r) is int or type(r) is float only then you should apply test for range. If the above type checking is false then you should print your "else" error message.
Try is too slow and should be avoided when not necessary
num = input("Please enter a number between 1 and 100: ")
if num.replace('.','').isdigit():
num = float(num)
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
else:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
else:
print('thats not a number!')

Adding up the sum of digits

I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]

Categories

Resources