How to Code in Pythonby Mark Keller
Python is an interpreted scripting language with simple, readable code intended to be intuitive and even fun to use --- hence its name, derived from Monty Python's Flying Circus. Learning Python is remarkably easy, due to both its simplicity and the detailed documentation available online. A simple Python code can be typed up and run in less than five minutes.
Download and Python. If you use Windows, enter "cmd" in the Run dialog or the Start Menu search bar and run "set path=%path%;C:\python32" at the prompt. This will add Python to your computer's path environment variable, allowing it to be easily run at the command line.
Open a simple text editor such as Notepad or gedit. If you run a Unix-based operating system such as Linux or OSX, type the following as the first line of the file: #! /usr/bin/env python3.2 This will allow you to run the program as a standalone script.
Use the "Import" command to include an external library in your code. The "sys" library contains many useful functions, allowing you to do things such as detect and use command-line arguments. Type the following line of code: import sys
Use variables without declaring them ahead of time. Unlike traditional programming languages such as C++, Python is dynamically, implicitly typed, allowing it to detect variable types on the fly. To assign command-line argument 0, the script's filename, to a string variable, enter the following line of code: name = sys.argv
Use the + operator for both adding numbers and concatenating strings. Because Python is an object-oriented language, arithmetic operators can be used in all sorts of surprising ways, even allowing you to multiply strings. Enter the following lines of code: howdy = "Hello, " greeting = howdy * 3 + "World! My name is " + name + "!" print(greeting)
Save your file as "howdy.py" in your home folder. If you are using a Unix variant, open a shell terminal and enter "chmod u+x howdy.py" to make your script executable.
Run your program. If you're using Windows, type "python3.2 howdy.py" at the command line. This can be abbreviated to "./howdy.py" on Unix variants. The program output should look like this: Hello, Hello, Hello, World! My name is howdy.py!
- check If you're using a newer or older version of Python, replace "python3.2" in your code and shell commands with the appropriate version number.
- photo_camera BananaStock/BananaStock/Getty Images
Click here to provide feedback on this article