Python general syntax
Python general syntax
Or by creating a python file on the server, using the .py file extension, and running it
in the Command Line:
Python Indentations
Where in other programming languages the indentation in code is for readability only,
in Python the indentation is very important.
Example
if 5 > 2:
print("Five is greater than two!")
Example
if 5 > 2:
print("Five is greater than two!")
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Docstrings
Python also has extended documentation capability, called docstrings.
Python uses triple quotes at the beginning and end of the docstring:
Example
Docstrings are also comments:
"""This is a
multiline docstring."""
print("Hello, World!")
Python Variables
Creating Variables
Unlike other programming languages, Python has no command for declaring a
variable.
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can even change
type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:
Output Variables
The Python print statement is often used to output variables.
Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
Example
x = 5
y = 10
print(x + y)
If you try to combine a string and a number, Python will give you an error:
Example
x = 5
y = "John"
print(x + y)
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing one or
more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Delete a variable
You can also delete variable using the command del "variable name".
a=45
print(a)
del a
print(a)