Difference between revisions of "Python: Basic Syntax"

From OnnoWiki
Jump to navigation Jump to search
Line 19: Line 19:
 
Ketik teks berikut pada prompt Python dan tekan Enter -
 
Ketik teks berikut pada prompt Python dan tekan Enter -
  
  >>> print "Hello, Python!"
+
  >>> print ("Hello, Python!");
  
If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result −
+
Akan menghasilkan
  
Hello, Python!
+
Hello, Python!
  
 
===Script Mode Programming===
 
===Script Mode Programming===

Revision as of 09:11, 25 January 2021

Bahasa Python memiliki banyak kesamaan dengan Perl, C, dan Java. Namun, ada beberapa perbedaan yang nyata dengan bahasa-bahasa tersebut.


First Python Program

Mari kita jalankan program dalam berbagai mode pemrograman.

Interactive Mode Programming

Memanggil interpreter tanpa meneruskan file skrip sebagai parameter akan menampilkan prompt berikut -

$ python
Python 3.8.5 (default, Sep  4 2020, 07:30:14) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Ketik teks berikut pada prompt Python dan tekan Enter -

>>> print ("Hello, Python!");

Akan menghasilkan

Hello, Python!

Script Mode Programming

Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.

Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a test.py file −

print "Hello, Python!"

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −

$ python test.py

This produces the following result −

Hello, Python!

Let us try another way to execute a Python script. Here is the modified test.py file −

#!/usr/bin/python
print "Hello, Python!"

We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −

$ chmod +x test.py     # This is to make file executable
$./test.py

This produces the following result −

Hello, Python!