How to save python codes in files?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Jun 14 02:12:51 EDT 2007


En Thu, 14 Jun 2007 01:56:13 -0300, why? <jimbomaan at gmail.com> escribió:

> I tried but its not working. Here's a code for sum of two numbers. Now
> how do i save it?
>
>>>>  #! /usr/bin/env python
> ...
>>>> def sum(x,y):
> ...     return x+y
> ...
>>>> x=int(raw_input('Enter a number: '))
> Enter a number: 35
>>>> y=int(raw_input('Enter a number: '))
> Enter a number: 7
>>>> print 'sum is', sum(x,y)
> sum is 42


You *don't* write your program inside Python; the interactive prompt is  
just for testing a few lines of code. Instead, use another program (a text  
editor) to create a file containing your source code, save it using a name  
like test1.py, and run it from a shell prompt using: python test1.py

I think that Red Hat comes with gedit as the default editor, you should  
find it under Accesories, Text Editor or similar; any other editor (like  
nano) would be fine too. Open it and write your program:

=== begin ===
#! /usr/bin/env python

def sum(x,y):
     return x+y

x=int(raw_input('Enter a number: '))
y=int(raw_input('Enter a number: '))
print 'sum is', sum(x,y)
=== end ===

Copy all text between the marks === begin ===, and === end === (but not  
including those marks).
Save it into your home directory - when prompted for a name, type  
"test1.py" (without quotes). (If you don't know what is your home  
directory, read your OS documentation).
Now open a shell prompt (or terminal). Run the command "ls" (without  
quotes; press ENTER). You should see test1.py listed. (If not, use the cd  
command to go to your home directory and try again). Now execute "python  
test1.py" (again, without quotes) and you should be asked for the numbers,  
and the program should display the sum (as you already have seen inside  
the Python interpreter).
If you want to change the program: go back into the editor, modify it,  
save it (with the same name, or a different one), switch to the shell  
prompt and run it again.
These are the very basics of writing a text file and executing a Python  
program from the shell prompt. There are more powerful editors that are  
aware of Python syntax, by example, and can display the source code with  
different colors for keywords, numbers, comments, etc. Other programs  
combine an editor + debugger + code autocompletion + other nice features  
(they're called IDEs, in general).

I hope this is of some help. You should read the OS documentation for more  
info on how to edit a file and such things.

-- 
Gabriel Genellina




More information about the Python-list mailing list