Code for Python as Prime and function [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Stuck on this problem and I couldn't find an answer and my code keeps failing.
Write a function called specialPrime which takes in an integer as an argument and returns True if the integer is a prime number and length of the integer squared is less than six digits, False if it is not a prime number or the integer squared is greater than six digits. Write a program which prompts the user to type in an integer and uses you specialPrime function to determine whether or not the integer is special.
Example Interaction
Enter a number: 140
140 is not a special prime number.
Enter a number: 89
89 is a special prime number.
My code
def specialPrime(isPrime,G6):
isPrime= int(input('Enter a number:')
if isPrime < 2 return False
elif isPrime == 2
return True
for n in range(2, x)
if x % n ==0:
return False
return True
G6 = len(isPrime**2)
if G6 > 6: return False
else
return True
while True
print( isPrime + 'is a special number')
else
print( isPrime + 'is not a special prime')
`

First:
Write a function called specialPrime which takes in an integer as an argument and returns True [or] False
Your function doesn't take an integer as an argument, it takes two arguments that… I'm not sure what they're intended to be, because you ignore them anyway. So, start with that. Also, give it a meaningful name. isPrime sounds like a flag that tells you whether a number is prime, or a function that figures out whether a number is prime, not a candidate number that may or may not be prime. So:
def specialPrime(number):
The next part of your code is close, but it's got problems too:
You're supposed to be testing the value you got as an argument, not some completely different value you got from input.
if, elif, for, and all other "compound statements" in Python need colons.
if, etc., statements with multi-line bodies need those bodies indented.
What is x? You were testing isPrime, and suddenly you're testing another variable that you haven't even defined anywhere.
You return True if the number is == 2, and also if it's > 2 but has no divisors between 2 and the number. That means you aren't testing the other condition; you're just assuming it's always true.
So:
if number < 2: return False
elif isPrime == 2:
pass
for n in range(2, number):
if number % n ==0:
return False
This can all be improved in multiple ways, but those are the minimal changes to make it make sense as Python code.
Next, you're trying to take the length of a number. Numbers don't have lengths. You can take the length of a string representation of a number:
digits = len(str(number**2))
if digits > 6:
… or you can do arithmetic to test the number of digits:
square = number**2
if square > 999999:
Also, notice the names digits and square, which tell you that it's a count of digits, or a square of a number, instead of G6, which tells you that it's a group of the 6 major EU countries.
Either way, you then have some of the same problems from the first block with colons and indents again, which you need to fix the same way.
Finally:
Write a program which prompts the user to type in an integer and uses you specialPrime function to determine whether or not the integer is special.
There's nothing about a while True-type loop here—it's a reasonable extension to the program, but get the basics working first.
So you need to prompt the user to type in an integer. Here is where you use input:
number = input('Enter a number:')
But the result of input is a string. If the user types 23, what you get is the string '23'. So, you need to call int to convert it:
number = int(input('Enter a number:'))
Now you have to call your function:
if specialPrime(number):
And again, you have some of the same errors with colons and indents that you need to fix.
After all of those fixes, the code will run. If there are no logic errors in your tests, it will give the right answer. If there are… well, you can debug it from there.

You could modify your code to use a couple of helper functions for each of the two requirements of special_prime(x):
def squared_less_than_six_digits(x):
return len(str(x**2)) < 6
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
if x % n == 0:
return False
return True
def special_prime(x):
return is_prime(x) and squared_less_than_six_digits(x)
def main():
user_input = 0
while True:
try:
user_input = int(input("Please enter an integer:"))
except ValueError:
print("Error: You did not enter a integer. Please try again.")
continue
else:
print("You entered the integer {}. Its square is {}.".format(user_input, user_input**2))
break
if special_prime(user_input):
print("It is a special prime.")
else:
print("It is not a special prime.")
if __name__ == "__main__":
main()
Try the above code out here!
Testing:
Prime number whose square is less than six digits:
Please enter an integer: 2
You entered the integer 2. Its square is 4.
It is a special prime.
Prime number whose square is greater than or equal to six digits:
Please enter an integer: 317
You entered the integer 317. Its square is 100489.
It is not a special prime.
Nonprime number whose square is less than six digits:
Please enter an integer: 1
You entered the integer 1. Its square is 1.
It is not a special prime.
Nonprime number whose square is greater than or equal to six digits:
Please enter an integer: 318
You entered the integer 318. Its square is 101124.
It is not a special prime.

Related

Python Program to Find Factorial of Number Using Recursion

The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 is 12345*6 = 720. Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
I would like help just to know how to read the entries and call the functions
For that purpose you can add the following code below your functions:
# main program
method = {
"IV": add_node,
"IA": add_edge,
"RV": delete_node,
"RA": delete_edge
}
numinputlines = int(input())
for _ in range(numinputlines):
instruction, *rest = input().split()
if len(rest) == 3: # There is a cost:
rest[-1] = int(rest[-1])
method[instruction](*rest)
The method dictionary helps to translate a 2-letter code to a method that needs to be called. As the arguments to those methods are all in the same order, you can just capture those in a list rest, and "unpack" that list when passing the arguments. There is just one special thing to take care of. Two methods get a cost argument, and it must be of number type. Since input is read as string, you need to convert that cost string to a number. The if statement takes care of this case.
This should answer your question, but it does not finish the exercise. You will still have to debug your code. For instance, currently your code will raise an exception on the example input you have given -- vertex "B" is referenced in IA B A 1 before it is added with IV B.
Also, you'll need to add the code to produce the output.
But since your question was about capturing the input and calling the functions, I have left the rest for you to tackle.
How do I calculate a factorial of an integer in Python? Note that the factorial function is defined only for positive integers; therefore, you should also check that n >= 0 and that isinstance(n, int). Otherwise, raise a ValueError or a TypeError respectively.
def factorial(n):
if(not isinstance(n, int) or n < 0):
raise ValueError("Invalid argument")
if (n==1 or n==0):
return 1
else:
return (n * factorial(n - 1))
# Driver Code
num = int(input("Please enter a number"))
print("Factorial : ",factorial(num))

Collatz from automate the boring stuff

I know there are multiple posts on this question. But I could not post my code in any other way except by asking a question. Can someone please help me understand how I can stop n from being input into the collatz function each time the global scope executes.
Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling collatz() on that number
until the function returns the value 1.
(Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence,
you’ll arrive at 1! Even mathematicians aren’t sure why.
Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)#
Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.
desired output
3
10
5
16
8
4
2
1
Input Validation
Add try and except statements to the previous project to detect whether the user types in a noninteger string.
Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy').
In the except clause, print a message to the user saying they must enter an integer.
def collatz(number):
if number%2==0:
number=number//2
print(number)
elif number%2==1:
number=3*number+1
print(number)
print('Enter number: ')
n=int(input())
while n!=1:
collatz(n)
You‘ve created an infinite loop, since your „n“ doesn‘t change within the loop and „n!=1“ is never met as long as the user doesn’t input “1” in the beginning.
Try this:
def collatz(number):
if number % 2 == 0:
number = number // 2
else:
number = 3 * number + 1
print(number)
return number
n = int(input("Enter number: "))
while n != 1:
n = collatz(n)

Why does prime number checker say 9 is a prime number?

print "Type a number"
num = int(raw_input("> "))
if num % 2 == 0:
print "This is not a prime number"
else:
print "This is a prime number"
When I type '9' it says it's a prime number, which it isn't:
Type a number
> 9
This is a prime number
Is my code too simple? Is there something it doesn't check?
You're only checking if it is an even number, by checking if it is divisible by 2. But 9 is divisible by 3 so you need to check that also. The easiest way would be to check all numbers up to the square root of the number you're checking for primality.
All you are doing here is checking whether or not a number is evenly divisible by 2. Since 9 / 2 = 4.5, it's not evenly divisible by 2 thus going to the else clause.
Here is a condensed, working version of what you probably want:
def is_prime(a):
return all(a % i for i in xrange(2, a))
To check if number is prime you have to validate is it devisible by any number in range [2, sqrt(n)].
Following code does exactly the same:
import math
def is_prime(n):
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
This method is good for small number, but if n is real big number then you need something faster. And in this case you can use Miller–Rabin primality test which checks primality with a certain probability.
You are checking if a given number is even or not, and 9 is not even so your code prints out "This is a prime number"
Please take a look at this Stackoverflow question for a detailed explanation on how to check for prime numbers using Python.

Can anyone figure out this code for me?

import random
print "Welcome to the number guesser program. We will pick a number between 1 and 100 and then ask you to pick a number between 1 and 100. If your number is 10 integers away from the number, you win!"
rand_num = random.randint(1, 100)
user_input = raw_input('Put in your guess:').isdigit()
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
Whenever I try to run this code, the computer always generates the number 1. And if I put in a number that is 10 (or less) integers away from one it will still display the else statement. I will have my gratitude to whoever can solve my predicament. I am new to python try to keep your answers simple please.
raw_input returns a string you entered as input. isdigit() checks whether a string is a digit or not and returns True or False.
In your code you're assigning the return value of isdigit to user_input So, you get either True or False. Then you convert it to a number, thus getting either one or zero. This is not what you want.
Let user_input be just a result of raw_input. Then check whether it is a valid number with user_input.isdigit(). If it's not a number, print an error message and exit (or re-ask for input), else convert user_input to an integer and go on.
The problem is product by this sentenc:
user_input = raw_input('Put in your guess:').isdigit().
The return value of isdigit() is True or False. When you enter 1 or any digit number, it will return True(True=1,False=0), so you will always get 1, if you enter digit. You can change like this:
import random
print "Welcome to the number guesser program.
We will pick a number between
1 and 100 and then ask you to pick a number
between 1 and 100. If your number is 10 integers
away from the number, you win!"
rand_num = random.randint(1, 100)
user_input= raw_input('Put in your guess:')
is_digit = user_input.isdigit()
if is_digit==True:
number = int(user_input)
print number
if abs(rand_num - number) &lt= 10:
print "Winner"
else:
print "Loser"
else:
print 'Your input is not a digit.'
Look at this line:
user_input = raw_input('Put in your guess:').isdigit()
The function raw_input gives you user input, but then you call isdigit and as consequence in your variable user_input you get result of isdigit. So, it has boolean value.
Then in
number = int(user_input) you cast it to integer type. In python true is 1 and false is 0. That's why you always get 1.

Python 2.7 / loop / break is changing my outcome [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
smallest = None
largest = None
while True :
number = raw_input('Enter a number from -10 to 9: ')
if largest < number :
largest = number
if smallest is None :
smallest = number
elif number < smallest :
smallest = number
if number == 'done': break
print 'Largest number is: ',largest
print 'Smallest number is ',smallest
I have no idea why my "smallest" is alright while "largest" outcome is always done. I think that "break" is somehow affecting it. Could You point out my mistake?
The problem is that you are first updating smallest and largest even if the user entered done. So first of all, you should check whether the input is 'done' and abort immediately before updating any of your numbers.
That being said, there are multiple other issues with your code:
if largest < number – You are updating largest if the number is smaller than the previously stored one, making it have the same logic as smallest. Of course, you will not end up with the largest number that way.
raw_input() returns a string, not a number. So if the user types for example 5, then what raw_input() returns is the string '5'. So every comparison you make is a string comparison (e.g. '2' < '5'). Because string comparisons are based on character codes, this will incidentally work for single-digit numbers but you should really convert the strings into proper numbers first.
You mention an allowed range of -10 to 9 but you never actually enforce that.
Something like this will work:
smallest = None
largest = None
while True:
number = raw_input('Enter a number from -10 to 9: ')
if number == 'done':
break
# convert into a number
try:
num = int(number)
except ValueError:
print('That was not a valid number')
continue # restart the loop
# validate the number range
if num < -10 or num > 9:
print('The number is out of the allowed range')
continue
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
print 'Largest number is:', largest
print 'Smallest number is:', smallest
If you encounter done, your loop should break immediately. But in your codes, you have put the break at the end. So before that, previous logic is being executed. And done as a string can be compared.
>>> None < 'done'
True
>>>
So your largest is set to done since largest < None in that case.
Quick Fix
We now moved the break on top, so this should fix the issue:
smallest = None
largest = None
while True :
number = raw_input('Enter a number from -10 to 9: ')
if number == 'done':
break
if largest < number :
largest = number
if smallest is None :
smallest = number
elif number < smallest :
smallest = number
print 'Largest number is: ',largest
print 'Smallest number is ',smallest
Handling Numbers
The raw_input returns string. But we want to compare numbers. So we should convert the inputs to int.
try:
num = int(number)
except ValueError:
print('Please enter a valid integer')
continue # skip the input and continue with the loop

Categories