I want to check whether a number is multiple of second. What's wrong with the following code?
def is_multiple(x,y):
if x!=0 & (y%x)==0 :
print("true")
else:
print("false")
end
print("A program in python")
x=input("enter a number :")
y=input("enter its multiple :")
is_multiple(x,y)
error:
TypeError: not all arguments converted during string formatting
You are using the binary AND operator &; you want the boolean AND operator here, and:
x and (y % x) == 0
Next, you want to get your inputs converted to integers:
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
You'll get a NameError for that end expression on a line, drop that altogether, Python doesn't need those.
You can test for just x; in a boolean context such as an if statement, a number is considered to be false if 0:
if x and y % x == 0:
Your function is_multiple() should probably just return a boolean; leave printing to the part of the program doing all the other input/output:
def is_multiple(x, y):
return x and (y % x) == 0
print("A program in python")
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
if is_multiple(x, y):
print("true")
else:
print("false")
That last part could simplified if using a conditional expression:
print("A program in python")
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
print("true" if is_multiple(x, y) else "false")
Some things to mention:
Conditions with and, not & (binary operator)
Convert input to numbers (for example using int()) - you might also want to catch if something other than a number is entered
This should work:
def is_multiple(x,y):
if x != 0 and y%x == 0:
print("true")
else:
print("false")
print("A program in python")
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
is_multiple(x, y)
Use and operator instead of bitwise & operator.
You need to conver values to integers using int()
def is_multiple(x,y):
if x!=0 and (y%x)==0 :
print("true")
else:
print("false")
print("A program in python")
x = int(input("enter a number :"))
y = int(input("enter its multiple :"))
is_multiple(x,y)
I tried this and worked also for when x and/or y are equal to 0. Idk if there's a shorter way of writing it.
Tested with (4,12), (12, 4), (2,0), (0,2), (0, 0)
(result should be : False True False True True).
def exo1(x,y):
#x = int(input("input number x: "))
#y = int(input("input number y: "))
if x==0 and y==0:
return True
if x>0 and y==0:
return False
if y>0 and x==0:
return True
if x!=0 and y!=0 and (x%y)==0:
return True
else:
return False
print(exo1())
print(exo1(4,12))
print(exo1(12,4))
print(exo1(2,0))
print(exo1(0,2))
print(exo1(0,0))
Related
This is a simple function that checks the values entered by the user and returns true if x is a multiple of y, if not it returns false. When I run the code, it prompts the user to enter a number for x and y but does not display whether it is true or false. What am I doing wrong?
def is_multiple(x, y):
if (y % x) == 0:
print("True")
else:
print("False")
x = int(input("enter any number :"))
y = int(input("enter a multiple :"))
You have to call the function after you get the arguments.
def is_multiple(x, y):
if y % x == 0:
print("True")
else:
print("False")
# Using different names to stress the difference between
# function parameters and function arguments.
n = int(input("enter any number :"))
m = int(input("enter a multiple :"))
is_multiple(n, m)
As others have mentioned, you have to call the function.
Add this at the end:
is_multiple(x, y)
You could make your function much more useful by doing this however:
def is_multiple(x, y):
if (y % x) == 0:
return True
else:
return False
x = int(input("enter any number :"))
y = int(input("enter a multiple :"))
print(is_multiple(x, y))
Now your function actually returns a value that you can use however you'd like. In this case, it is printing the returned value.
call the function which you declared above
is_multiple(x,y)
I am making a program that asks for 2 random numbers and prints a random integer between the 2 numbers that have been asked for. My code works except for the times where I give 2 consecutive numbers, it won't print a decimal/float.
import random
def bound():
print("Give me a number")
s = input()
print("Give me another number")
x = input()
w = random.randint(int(s),int(x))
if w == s:
None
if w == x:
None
else:
print(w)
bound()
You're so close! Just replace randint with uniform:
def bound():
print("Give me a number")
s = input()
print("Give me another number")
x = input()
w = random.uniform(int(s),int(x))
if w == s:
None
if w == x:
None
else:
print(w)
bound()
randint returns an integer, whereas uniform returns a random float from between the numbers passed.
randint generates integer value, to get the decimal value you can use uniform.
Try this
def bound():
print("Give me a number")
s = input()
print("Give me another number")
x = input()
if int(s)+1 == int(x): # check for continuity
w = random.uniform(int(s),int(x))
else:
w = random.randint(int(s),int(x))
if w == s:
None
if w == x:
None
else:
print(w)
bound()
This will return a integer value if numbers are not continuous and a float value if they are continuous.
You can use random.uniform for 2 consecutive numbers and normal random.randint for non consecutive numbers. randint is basically random integer: random and integer. It basically fetches integers from a given range.
def bound():
print("Give me a number")
s = input()
print("Give me another number")
x = input()
w = random.uniform(int(s),int(x))
print(w)
bound()
Your specification is unclear. In my mind, if I say "pick a number between 1 and 4", then the possible answers are 1, 2, 3, or 4. In that case:
def bound():
x = int(input("Enter lower bound:"))
y = int(input("Enter upper bound:"))
return random.randint(x,y)
If you want a real number between 1 and 4 (where 2.773 is a valid answer), then you want:
def bound():
x = int(input("Enter lower bound:"))
y = int(input("Enter upper bound:"))
return random.uniform(x,y)
If you want an integer between the two endpoints but excluding the two endpoints, which seems silly, then you want:
def bound():
x = int(input("Enter lower bound:"))
y = int(input("Enter upper bound:"))
if abs(y-x) <= 1:
print("There are no integers between",x,"and",y)
return None
else:
return random.randint(x+1,y-1)
This question already exists:
Checking if a number is prime in Python [duplicate]
Closed 1 year ago.
I am currently using python3.9. I have coded a python block of code in which I have put an if else Condition but when I enter my input such as 15 then both conditions became true like the following. I want to know how an if-else condition can be true in both case. You can see it in following screenshot so that you can understand well and help me in this.:
x = input("Enter a number: ")
x = int(x)
def my_func(y):
for i in range(1, y):
if y % i == 0:
print("It is consecutive")
elif y < 2:
print("It is smaller than 2")
else:
print("It is prime")
break
my_func(x)
you are checking multiple times, on one iteration condition may return one aswer, on next - other, in your case firstly it is divisble by 1, prints "It is consecutive", then not divisble by 2 and prints "It is prime", then meets break statement, make an individual check for <2 and then iterate over numbers, and then if it does not return anything print "It is prime", like this
x = input("Enter a number: ")
x = int(x)
def my_func(y):
if y<2:
print("It is smaller than 2")
return
else:
# A prime will not have any factors greater than 1
for i in range(2, y):
if y % i == 0:
print("It is consecutive")
return
print("It is prime")
my_func(x)
The result you are getting is because of the for loop .
For the first iteration the if condition evaluates to true (15 % 1 == 0). So "It is consecutive" is printed , the remaining elif and else conditions are not checked for
For the second iteration, if condition is false (15 % 2 == 0 is false) .It goes to elif condition (y < 2) which is false too , since 15 < 2 is false . The flow goes into the else block and does whatever is specified in it (in this case prints "it is prime" and breaks from the loop )
Hence you get both the statements.
Conclusion - The if-else block isn't executing simultaneously . It is due to the for loop the condition changes and hence the result
So your for-loop is doing the following:
for i in range(1, 15): # Iterate over 1,2,3,4,..
# 1 - [(15 % 1) = 0, True, print("It is consecutive")
# 2 - [(15 % 2) != 0, False...
# (y < 2), False...
# print("It is prime")]
I suspect you want something more like the following:
x = input("Enter a number: ")
x = int(x)
def my_func(y):
# Any number less than 2 is not prime
if y < 2:
print("It is smaller than 2")
# Exit the function early and don't continue onto the for loop
return
for i in range(2, y):
# if this evaluates as True for any of i < y then y is not prime
if y % i == 0:
print("It is consecutive")
# Exit the function and do not complete the for loop
return
# If we have reached here then the for loop has executed fully and no values of i have been found to be factors of y, therefore y is prime
print("It is prime")
my_func(x)
It isn't True in multiple if branches. but for different values of the for loop. If that's code is a primality test, it should be more like that
def my_func(y):
if y < 2:
print("Lower than 2")
return
for i in range(2, y):
if y % i == 0:
print("It is consecutive, because of", i)
break
else:
print("It is prime")
# else is triggered if no `break` used
I just started learning python. I have some experience with C++ from school. The problem is to write code that prints the largest odd number from user input and to print relevant feedback if there isn't any odd number. What is wrong with this code and are there better ways to solve this problem?
#To print the largest odd number
x = input ("Enter first number: ")
y = input ("Enter second number: ")
z = input ("Enter third number: ")
if x % 2 == 0 and y % 2 == 0 and z % 2 == 0:
print ("There are no odd numbers")
if x % 2 != 0 and x > y and x > z:
print (x, " is the largest odd number")
if y % 2 != 0 and y > x and y > z:
print (y, " is the largest odd number")
if z % 2 != 0 and z > x and z > y:
print (z, " is the largest odd number")
elif x == y == z:
print ("All the numbers have the same value")
Maybe the logic becomes easier if you make it into a small list and sort it:
x = input ("Enter first number: ")
y = input ("Enter second number: ")
z = input ("Enter third number: ")
odds = sorted([ i for i in [x,y,z] if int(i)%2 ],reverse=True)
if not odds:
print("No odd number")
elif odds.count(odds[0]) == len(odds):
print("All odd numbers are equal")
else:
print(f"{odds[0]} is the largest odd number")
2 things: 1. Convert data. 2. Your code isn't formatted correctly, by the looks of it.
For 1:
x = int(input(("Enter first number: ")) #Do this for y and z
For 2- your code will never return the largest odd number if the largest odd number is smaller than the largest even number. For example [20, 9, 5]. To fix that:
#Create a list to work with
num_li = [x,y,z]
#Get all the odd numbers
num_li = [i for i in num_li if i%2!=0]
#If no odd numbers
if len(num_li) == 0:
print('No odds')
#Print the largest odd number
else:
num_li.sort(reverse = True)
print('The largest odd number is: ' + str(num_li[0]))
There are two problems with the current version of the code:
1)TypeError - You are receiving strings as inputs and treating them like integers
2)Logical error - your conditions do not cover all cases.
I rewrote the code. strings are converted to int and all cases are covered.
Working example:
x = int(input ("Enter first number: "))
y = int(input ("Enter second number: "))
z = int(input ("Enter third number: "))
numbers = [x, y, z]
odd_numbers = []
for number in numbers: // loop through the numbers and create an odd number list
if number % 2 != 0:
odd_numbers.append(number)
if odd_numbers: //print out the largest number in the list using max()
print(max(odd_numbers))
else:
print("No odd numbers")// if the list is empty this will be printed
I am very new to python, and I am trying to make a program that allows a user to enter three numbers and the program will tell them the sum, average, product, and the odd numbers of the numbers. I just can't seem to find a way to get the odd numbers listed on one line. Here is what I have:
def main():
x, y, z = eval(input("Enter three integers, each seperated by a comma: "))
Sum = (x+y+z)
Average = (x+y+z)/3
Product = (x*y*z)
print("Sum:", Sum)
print("Average:", Average)
print("Product:", Product)
print("Odd Numbers: ")
if (x % 2) != 0:
print(x)
if (y % 2) != 0:
print(y)
if (z % 2) != 0:
print(z)
main()
This one liner will work.
print('Odd Numbers:', ', '.join(str(num) for num in (x,y,z) if num % 2))
"if num % 2" resolves to a boolean true if the number is odd and false if even through an implicit conversion to boolean from integer. All values that are accepted need to be converted via "str(num)" to a string for use with ', '.join, which connects the string version of the odd numbers with a ', ' between them.
This will add all the odd numbers into an array, then print the array with a space between each value in the array. Got the join line from this SO answer.
odd_numbers = []
print("Odd Numbers: ")
if (x % 2) != 0:
odd_numbers.append(x)
if (y % 2) != 0:
odd_numbers.append(y)
if (z % 2) != 0:
odd_numbers.append(z)
print " ".join([str(x) for x in odd_numbers] )
Within your print, you can set your end character using end from a newline to a space to print them on one line.
print("Odd Numbers:",end=" ")
if (x % 2) != 0:
print(x,end=" ")
if (y % 2) != 0:
print(y,end=" ")
if (z % 2) != 0:
print(z,end=" ")
The output will be:
x y z if they are all odd.
Another note is that the use of eval should be carefully if not never used due to the security risks
Instead you can accomplish the user input of comma-separated values using the split function to return a list of values from the users.
userInput = input("Enter three integers, each seperated by a comma: ")
userInputList = userInput.split(",") #Split on the comma
#Assign x,y,z from userInput
x = userInput[0]
y = userInput[1]
z = userInput[2]