If I give negative numbers this code does not function any more and I don't know how to stop it if I put for example a string or something that doesn't have sense. Help me please!!
def computeHCF(x,y):
if x>y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
while True:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
continue;
else:
print("You write something that doesn't have any sense!")
You have to make python first check for strings in the input.
Then check for negative numbers,
If none of these two errors are present it goes ahead to run your code
But if they are let it exit before giving an error
Like so:
def computeHCF(x,y):
if type(x) is str or type(y) is str:
print("You wrote something that doesn't have any sense!")
exit()
elif x < 0 or y < 0 :
print("You wrote something that doesn't have any sense!")
exit()
elif x>y:
smaller = y
elif y<x:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
while True:
num1 = (input("Enter the first number: "))
num2 = (input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
continue;
We can simulate what happens in your code when the result is not what we expect.
We noticed that if we insert a negative number, the program stops.
so let's assume num1 = -4 and num2 = 2
def computeHCF(x,y): # x = -4, y = 2
if x>y: # we don't meet this condition
smaller = y
else: # we meet this condition
smaller = x # smaller value is -4
for i in range(1, smaller+1): # there is nothing in range(1, -3)!!
# we do not enter here
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf # hcf value has never been retrived, so an error will be raised here
you can solve this problem in many ways, two of them are:
set hfc with a base value, so if the conditions in the for loop are not met, the base value will be returned:
def computeHCF(x,y):
hcf = None
this code will return:
('The H.C.F. of', -4, 'and', 2, 'is', None)
or by having the absolute value of x and y:
def computeHCF(x,y):
x = abs(x)
y = abs(y)
this code will return:
('The H.C.F. of', -4, 'and', 2, 'is', 2)
We also see that if we insert a string or something that can't be interpreted as an int, another error is raised.
This time, the error happens when you read the input:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
in this two lines, you convert anything that the user input to an int, but strings like "Hello World!" can't be converted into an int.
One of the many way to solve this problem, is to use try/except: you try to read the input as an int, but if an error occurs, you do something else.
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
continue
except:
print("You write something that doesn't have any sense!")
continue
with this code, the result of the inputs "Hello" and "World!" will be:
"You write something that doesn't have any sense!"
you catch also the error generated by the function computeHCF(x,y) when x = 0 or y = 0.
At last, you can erase your last two lines, with the "else" statement. That else will be executed only when the condition of the while loop is False, but True is always True!
in the end, your code could be like:
def computeHCF(x,y):
x = abs(x)
y = abs(y)
# or hcf = None
if any([type(x)!=int,type(y)!=int]):
return hcf
if x>y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
while True:
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
except:
print("You write something that doesn't have any sense!")
continue
Related
Divisible challenge
Write a program that asks the user for two numbers. The program should output whether the two numbers are exactly divisible by each other. If not, it should return the remainder. If the user enters a 0 the program should give an error message.
so far I've done this:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
answer1 = num1/num2
answer2 = num2/num1
if num1/num2 == answer1(int) or num2/num1 == answer2(int):
print("Exactly divisible")
elif num1 == 0 or num2 == 0:
print("Error: you cannot divide by 0")
elif num1/num2 != answer1(int) or num2/num1 != answer2(int):
print("Not Exactly divisible")
please help...
I would approach this way
first check the zero case, in that case the code terminates faster
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
# answer1 = num1/num2
# answer2 = num2/num1
def divisible_by_each_other(num1, num2):
if (num1 == 0) or (num2==0):
print("Error do not enter 0")
#check divisibility
elif (num1%num2 == 0 ) or (num2%num1 == 0 ):
print("Exactly divisible")
else:
print("Not Exactly divisible")
high,low= max(num1,num2),min(num1,num2)
print("The remainder is ", high%low)
divisible_by_each_other(num1, num2)
answer1(int) is not the correct way to convert to an integer, it's int(answer1).
Since you already divided the numbers, you could use
if answer1 == int(answer1) or answer2 == int(answer2):
But you're making this much more complicated than it needs to be. Modulus is a simpler way to test divisibility.
if num1 % num2 == 0 or num2 % num1 == 0
You also should check if either of the numbers is zero before you try to use division or modulus. Otherwise, you'll get an error due to trying to divide by 0, which is what you're trying to prevent with this check.
If they're not divisible by each other, get the remainder of the larger divided by the smaller:
else:
return max(num1, num2) % min(num1, num2)
Here's the full, simplified code:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
higher = max(num1, num2)
lower = min(num1, num2)
if num1 == 0 or num2 == 0:
print("Error: you cannot divide by 0")
elif higher % lower == 0
print("Exactly divisible")
else:
print(higher % lower)
I am looking to see if any 2 indices add up to the inputed target number, and print the combination and index location of the respective pair. I honestly am not too sure how to approach this, my first reaction was using a for loop but due to inexperience i couldn't quite figure it out.
def length():
global lst_length
break_loop = False
while break_loop == False:
lst_length = int(input("Enter the length: "))
if lst_length >= 10 or lst_length <= 2:
print("Invalid list")
elif lst_length >= 2 and lst_length <= 10:
print('This list contains', lst_length, 'entries')
break_loop == True
break
def entries():
i = 0
x = 0
global lst
lst = []
while i < lst_length:
number = float(input("Enter the entry at index {0}:".format(x)))
if i < 0:
print('Invalid entry')
else:
lst = []
lst.append(number)
i += 1
x += 1
def target():
target_num = int(input("Enter the target number: "))
length()
entries()
target()
If I understand your question correctly, you want the user to insert numbers, and when finally two numbers match the wanted result, print them?
well, my code is pretty basic, and it gets the job done, please let me know if you meant something else.
for indices, I suppose you can fill in the gaps.
def check(wanted):
numbers_saved = []
checking = True
while checking:
x = float(input("enter a number: "))
if x < 0:
print("only numbers bigger than 0")
else:
for num in numbers_saved:
if num + x == wanted:
print(num, x)
checking = False
return
numbers_saved.append(x)
im relatively new to python and im not really sure how does the indentation for if else works.
Write a Python program that calculates the sum of all the numbers from x to y, where x and y are numbers entered by the user.
print("This program prints the sum of range from x to y. ")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers from 10 to 50. ")
x = int(input("Please enter the value of x: "))
y = int(input("Please enter the value of y: "))
if type(x) == int and type(y) == int:
if x > 0 and y > 0:
if y > x:
sum_of_numbers = []
for counter in range(x , y):
sum_of_numbers.append(x)
x += 1
print("The sum of numbers from {} to {} is {}".format(x,y,sum(sum_of_numbers)))
else:
print("You did not enter a value of y greater than x")
print("Unable to continue.Program terminated.")
exit()
else:
print("One or more inputs is not greater than zero")
print("Unable to continue.Program terminated.")
exit()
else:
print("One or more inputs is not numeric!")
print("Unable to continue.Program terminated.")
exit()
if type(x) == int and type(y) == int:
if x > 0 and y > 0: # indented 1
if y > x: # indented 3
sum_of_numbers = [] # indented 4
You need to have consistent indentation, preferably four spaces for each indent, as per PEP8.
Without that, the Python compiler (or you as well, really) can't tell how your code is meant to be structured.
hi there i'm learning python
i like to know if this script can be better or shorter
import sys
g = 1
def trying():
q = input('enter (y or yes) to retry')
if not q == 'y' or q == 'yes':
return 0
while g == True:
try:
t = int(input('please enter an integer:'))
r = t % 2
if r == 0:
print('your number is even')
if trying() == 0:
g = 0
else:
print('your number is odd')
if trying() == 0:
g = 0
except ValueError:
print('sorry you need to enter numbers only')
If you want in shorter, here is my version..
while True:
try:
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
if input('Enter (y or yes) to retry: ') not in ['y', 'yes']: break
except ValueError:
print('Sorry you need to enter numbers only')
What you want here is a do-while loop. You can easily implement it by adding a break statement to a infinite while-loop. More on this topic can be found here.
Next thing, you have to add a try-except statement as there is a string to integer conversion is happening.
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
This statement will return "Your number is even" if the input is even else it will return "Your number is odd". This method is called python ternary operator.
Then you can wrap it with a print-function to print the returned string. Look here.
input('Enter (y or yes) to retry: ') not in ['y', 'yes']
This check whether the user input is not there in the given list. So if user input is neither "y" or "yes", while-loop will break.
Here is an example of how the code can be made simpler. Remember that code should rarely be repeated. In most cases, if you have repeating lines of code it can be simplified.
while True:
try:
t = int(input('please enter an integer:'))
if t % 2 == 0: print('your number is even')
else: print('your number is odd')
q = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'): break
except ValueError:
print('sorry you need to enter numbers only')
def trying():
question = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'):
return 1
return 0
while True:
try:
num1 = int(input('please enter an integer:'))
num2 = t % 2
if not num2:
print('your number is even')
else:
print('your number is odd')
if trying():
break
except ValueError:
print('sorry you need to enter numbers only')
You don't have to import sys in your program as you didn't used it and you don't have to. You don't have to store anything in a variable for a while loop. Just assigning True and breaking out will do. If you're looking for anything that is True (this includes an unempty list, string, and dictionaries; and numbers not equal to 0). You should make if var:. If the variable evaluates to True. The conditional block will be executed. This is a clearer syntax so it is recommended. Name your variables with words, not with letters. This will not make your code longer and it will make your code better.
This is all I can do with your code. If there is more, please state them.
I'm making a calculator in python that takes in two numbers and returns the greatest common factor of it. When I create a function that returns the same numbers of the two lists of factors, I keep getting a 'index' error even if I stated
if len(one) == 0 and len(two) == 0:
here's my code:
def work(one, two):
for i in range(len(one)):
for j in range(len(two)):
if len(one) != 0 and len(two) != 0:
if one[i] == two[j]:
one.pop(i)
two.pop(j)
if len(one) == 0 or len(two) == 0:
break
else:
work(primeF, primeF2)
break
work(primeF, primeF2)
What could I do to fix this?
You can greatly simplify your code by using what is already available in Python's standard library:
>>> import fractions
>>> work = fractions.gcd
>>> work(12345, 67890)
15
The fractions.gcd function should do exactly what you want without the need for more code. Here is a copy of the function from the module's source:
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
I think that instead of checking whether the list length is 0, you need to be checking that the list is long enough to include your index.
There is an even easier way to do it without modules (I just used time for supplements)
import time
def gcf (num1, num2): #The Actual Calculator
if num1 > num2:
num1, num2 = num2, num1
for x in range (num1, 0, -1):
if num1 % x == 0 and num2 % x == 0:
return x
def run(): #This section is defined so that it can be run multiple times
num1 = int(input("First Number: ")) #First number
num2 = int(input("Second Number: ")) #Second number
print (str (gcf (num1, num2)))
run_again = input("Run again? y or yes for yes: ")
if run_again == "yes" or run_again == "Y" or run_again == "Yes" or
run_again == "y":
run()
elif run_again == "hello":
print("hi")
run()
else:
print("Goodbye!")
time.sleep(1.5)
quit()
#Runs the code
run()