Input Remainder Prime Number - python-3.x

I'm trying to make a program that will tell the user if the inputted number is either a prime number or not. I would like to know how to format it to where it will return the remainder. I have the following .py file that I made, but I keep getting error "not all arguments converted during string formatting":
i = 2
x = input("Input your proposed prime number now:\n")
number = x % i
print (number)

#Rishav had incorrect formatting, try:
x = int(input(Input your proposed prime number now:\n"))
if you are working with decimals, you can use:
y = float(input("Input a decimal > "))

input returns a string in Python3. Use :
x = int(input("Input your proposed prime number now:\n")

Related

Loop won't finish...Poor indentation?

I am new to python and Jupyter Notebook
The objective of the code I am writing is to request the user to introduce 10 different integers. The program is supposed to return the highest odd number introduced previously by the user.
My code is as followws:
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: '))
if c%2==0:
print('The number is even')
elif c> y
y=c
print('y')
i=i+1
My loop is running over and over again, and I don't get a solution.
I guess the code is well written. It must be a slight detail I am not seeing.
Any help would be much appreciated!
You have elif c > y, you should just need to add a colon there so it's elif c > y:
Yup.
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: ')) # This line was off
if c%2==0:
print('The number is even')
elif c> y: # Need also ':'
y=c
print('y')
i=i+1
You can right this in a much compact fashion like so.
Start by asking for 10 numbers in a single line, separated by a space. Then split the string by , into a list of numbers and exit the code if exactly 10 numbers are not provided.
numbers_str = input("Input 10 integers separated by a comma(,) >>> ")
numbers = [int(number.strip()) for number in numbers_str.split(',')]
if len(numbers) != 10:
print("You didn't enter 10 numbers! try again")
exit()
A bad run of the code above might be
Input 10 integers separated by a comma(,) >>> 1,2,3,4
You didn't enter 10 numbers! try again
Assuming 10 integers are provided, loop through the elements, considering only odd numbers and updating highest odd number as you go.
largest = None
for number in numbers:
if number % 2 != 0 and (not largest or number > largest):
largest = number
Finally, check if the largest number is None, which means we didn't have any odd numbers, so provide the user that information, otherwise display the largest odd number
if largest is None:
print("You didn't enter any odd numbers")
else:
print("Your largest odd number was:", largest)
Possible outputs are
Input 10 integers separated by a comma(,) >>> 1,2,3,4,5,6,7,8,9,10
Your largest odd number was: 9
Input 10 integers separated by a comma(,) >>> 2,4,6,8,2,4,6,8,2,4
You didn't enter any odd numbers

Convert binary integer to decimal using bellow algorithm

Can anyone please give me instruction how to write the program using this algorithm?
To convert binary integer to decimal, start from the left. Take your current total, multiply it by two and add the current digit. Continue until there are no more digits left.
First need to input the binary number as a string then select one by one digits of binary number
num=input("Enter the binary integer Number: ")
num=str(num)
decimal=''
rem=0
i=0
i=int(i)
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
decimal=int(rem)
print(decimal)
This code only calculate 4 digits of binary numbers. How can i add a while loop in this code?
Yes, you can put that in a loop:
binary = input("Enter the binary integer Number: ")
decimal = 0
for dig in binary:
decimal = decimal*2 + int(dig)
print(decimal)
Note that in Python 3, input already returns a string type value, so you don't need to convert it with str().
You can use the int() function:
binary_string = input('Please input a binary number: ')
print(int(binary_string, 2))
A one liner, just because it is possible:
print(int(input('Please input a binary number: '), 2))
But if you really want to do this with a loop, you can do:
binary_string = input('Please input a binary number: ')
result = 0
multiplier = 1
for digit in binary_string[::-1]:
result += int(digit) * multiplier
multiplier *= 2
print(result)

How to convert an improper fraction to a mixed number, using python

I have to write a program that converts an improper fraction to a mixed number. Prompt the user for the numerator and the denominator, then calculate and display the equivalent mixed number. numerator is 23 and denominator is 6.
This is what I have so far...
num = int(input('Type numerator'))
dem = int(input('Type denominator'))
I'm not exactly sure what the next step is...I know the answer is supposed to be The mixed number is 3 and 5/6.
Assuming that your inputs are always integer values, you can use the divide and mod operators to do this.
The following should work:
a = num // dem
b = num % dem
print 'The mixed number is {} and {}/{}'.format(a, b, dem)
Good question. Here's one solution using Fraction function. Fraction is nice because it reduces fractions. You use floor divide (//) to strip out the whole number and then feed the remaining fraction to Fraction:
From fractions import Fraction
num = int(input('Type numerator'))
dem = int(input('Type denominator'))
Print str(num // dem) + ' and ' + str(Fraction(num%dem,dem)) if num//dem != 0 else str(Fraction(num%dem,dem))
[Python 3.5] (https://docs.python.org/2/library/fractions.html#fractions.Fraction) Extended reading on Fraction. Because you feed it num and dem rather than a pure decimal, it is pretty fail-safe.
This also gets rid of response of '0 and ...' which was bothering me.
Without using fractions module, we have to find the greatest common divider (borrowing gcd function from fractions) reduce our initial fraction and then use brilliant solution from #Jenner Felton
def gcdm(num,dem):
while dem:
num, dem = dem, num%dem
return num
gcd = gcdm(num,dem)
num, dem = num/gcd, dem/gcd
Print "%d and %d/%d" % ((num//dem), (num%dem),dem) if num//dem !=0 else "%d/%d" % (num%dem,dem)
As the other answers point out, you can use the integer division and modulo operators to get the numbers you want.
Another aspect to coding this problem that will make things easier is creating a while loop along with a try, except block for the entry of the improper fraction so that you do not get exceptions.
It would look like this:
while True:
try:
num = int(input('Type numerator'))
break
except:
continue
Split this off into a separate function to make things a bit nicer:
def get_data(message, f = lambda data: data):
'''Prompts the user for data entry.
Function f is applied to data; any exception encountered
results in user being prompted again.
Entry is simply returned if no function is supplied.'''
message = str(message)
while True:
try:
num = f(input(message))
break
except:
continue
return num
num = get_data('Type numerator', int)
den = get_data('Type denominator', int)
Here's my one-liner for obtaining the mixed number:
'%s%s%s' % ('%s ' % (num//den) if num//den != 0 else '', '%s/' % (num%den) if num%den != 0 else '', '%s' % den if num%den != 0 else '')

How to use calculated results in a repetitive algorithm

This is what I want to accomplish:
let the user type in a number with four digits
if this number is not equal to 6174 (Kaprekar’s constant) then sort the numbers in two ways:
a. from the biggest to the smallest number
b. from the smallest to the biggest
Subtract the bigger number with the smaller
If the result is not equal to 6174, then do the calculation again and write the result for each and every calculation
When the result is equal to 6174, write a message to show that the calculation is done
This is what I’ve tried:
print("type in a number")
number = (input())
while number != 6174:
start_big = "".join(sorted(number, reverse=True))
start_small = "".join(sorted(number))
number = (int(start_big)-int(start_small))
print(number)
print("Calculation finnished!")
I’m getting the error:
start_big = "".join(sorted(number, reverse=True)) TypeError: 'int'
object is not iterable
When you calculate this:
number = (int(start_big)-int(start_small))
The type of number becomes int, so in the next iteration the error occurs.
One solution would be
print("type in a number")
number = input()
while number != "6174":
start_big = "".join(sorted(number, reverse=True))
start_small = "".join(sorted(number))
number = str((int(start_big) - int(start_small)))
print(number)
print("Calculation finnished!")
you have to convert the input number to an iterable, you can just do
number = iter(number)
also you need to change the while loop condition:
while int(number) != 6174:
for printing the number just do this:
number = str((int(start_big)-int(start_small)))
You are almost there. You need to convert number to an iterable. I suggest:
start_big = "".join(sorted(str(number), reverse=True))
start_small = "".join(sorted(str(number)number))
You have multiple issues with your solution:
input() always returns a string, so number will never be an integer and as such it will never be equal to 6174. So your loop will still run for an input of 6174.
You need to convert the string into a number first, you can do that by simply calling int() on the string. Note that this may fail, so you might want to ask the user for input until they enter a valid number.
Once number is an integer, it is no longer an iterable, so you cannot call sorted() on it. If you want to sort the digits, then you need to convert it into a string first: sorted(str(number)).

Finding a number sequence in an integer

Guys heres my problem:
I am trying to read an integer from the user(e.g. 12345)
How can i check if the pattern "34" exists in the first integer?
My constraint is that i cannot convert it to string and cannot use arrays.
Here is what i managed to write to print some of the patterns that exists in 12345:
import math
int1 = int(input("input an integer: "))
#I used this to find out how many digits are in the integer
count = math.ceil(math.log10(int1))
for i in range(count):
print (int1 % (10 ** (i+1)))
for i in range(count):
print (int1 // (10 ** (i+1)))
Since this seems to be homework, I won't provide an answer, but only a rough hint.
Hint: extract each digit of the number using divmod(n, 10), which returns n without the last digit and the last digit of n. Hold the current digit and the previous digit in variables and compare them with the pattern, 34, each time a new a digit is extracted.

Resources