[Tutor] Writing Function Definitions

Dave Angel davea at davea.name
Wed Oct 9 13:28:16 CEST 2013


On 8/10/2013 18:50, Connor Hood wrote:

> Hi, I am taking a class in order to learn Python. 

Welcome to Python, and to Python-tutor.

> One of the exercises I need to do is write function definitions. I
> cannot figure out how to do one of them. To show you an example here is a similar problem:
>  If m is an integer, then isPrime(m) iff m is prime.The code:
> # Prompts the user for an integer m and then computes and prints whether# m is prime or not.
> # isPrime(m): I -> Bool# If m is an integer, then isPrime(m) if and only if m is prime.def isPrime(m):    return False if m <= 1 else isPrimeItr(1,0,m)
> # isPrimeItr(i,a,m): I x I x I -> Booldef isPrimeItr(i,a,m):    return False if a> 2 else True if a == 2 and i == m +1 else isPrimeItr(i+1,a+1,m) if m % i == 0 else isPrimeItr(i+1,a,m)
> # print a brief description of the program followed by an empty lineprint("Computing Prime Numbers")print("Prompts the user an integer value for m and then computes and")print("prints if m is prime or not.")print()
> # prompt the user for a value for mm = eval(input("Enter an integer value for m: "))
> # print if m is primeprint("The value that", m, "is a prime integer is", isPrime(m))
> ------------------------------------------------------------------------------------------------------------------------
> These are the problems I am having problem with:
> If m and n are integers, then anyPrimes(m,n) iff there are any prime numbers in the interval [m,n).
> If m and n are integers, then countPrimes(m,n) is the number of prime numbers in the interval [m,n).
> If anyone could help that would be great. Thank you. 		 	   		  
>
You've posted using html email, and the lines are squished together.  it
makes it quite hard to make sense out of your Python code.  Please use
text email in the future for posting here.

Alan's suggestions pretty much cover mine.  Make your code readable,
rather than clever while you're learning.

The two new functions you need can be written without recursion.  And if
you write countPrimes() first, it should be very easy to write
anyPrimes().

Have you written any top-level code to test the existing functions?  Or
to test the ones you're about to write?  Frequently wrting the test code
makes it clearer how to write the actual code.  Suggest you test first
with literal numbers, so you can rerun those tests quickily, rather than
always having to type in values to input statements.

I'm curious, what is the intent of i, a, and m in the existing function
isPrimeItr() ? 

BTW, Alan omitted a colon in his rewriting of the function.  The last
line needed a colon after the 'else'.


-- 
DaveA




More information about the Tutor mailing list