[Tutor] Newbie. Please help

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Jul 10 12:17:15 CEST 2013


On 8 July 2013 10:44, Sandile Mnukwa <sandile.mnukwa at gmail.com> wrote:
> I just started using Python recently, and i need help with the following: Please assist.
>
> 1.        Create another function that generates a random number (You will have to import the relevant library to do this)

You should do these steps one at a time. You have code for step 3 but
you haven't finished step 1 yet. If it says create a function then you
need to write something like

def my_function_name():
    random_number = <some code goes here>
    return random_number

Since you haven't done that you haven't done step 1.

> 2.        Create a function that is called from the main function, that accepts a number as a parameter and determines if the number is even or odd

Your main function is empty. You're not calling anything from it.

> 3.        Now enhance your script to generate 10 random even numbers and write them to a file

Don't attempt this step until you've got the others sorted.

>
> So far what i have done is:
> import random
> def main():
>     pass

The main function above is empty (it doesn't do anything). You need to
replace the line that says 'pass' with other lines of code that do
whatever your program is supposed to do.

>
> if __name__ == '__main__':
>     main()

Here you call the main function but it doesn't do anything since the
function is empty. The code below is not part of your main function.
You probably want to move it in there (in place of the line that says
'pass').

> for evenNumber in range (0, 20, 2):
>     print random.randrange(0, 101, 2)
>
> f = open("C:\Users\Documents\Myproj.txt", "w");
> print f
> f = open("C:\Users\Documents\Myproj.txt", "a");
> print f

You only need to open the file once in 'w' mode.

>
> value = random.randrange(0, 101, 2, )
> value1 = random.randrange(0, 201, 2, )
> value2 = random.randrange(0, 301, 2, )
>
> myString = str(value)
> myString1 = str(value1)
> myString2 = str(value2)
>
> print f.write(myString)
> print f.write(myString1)
> print f.write(myString2)

You don't need to use 'print' on the lines above since you're writing
to a file and print is for showing things in the terminal. Although
you could use print to write to the file e.g.:

print >> f, myString

If you do that then there's no need to convert the values into strings
with 'str' above.

> f.close()


Oscar


More information about the Tutor mailing list