From MantidProject
Python Basics
- Variable assignment in Python is simpler than in other languages as you do not specify types
# Here x is initialized to 5 and Python then treats this as an integer
x = 5
# It can be incremented and have all of the expected operations applied to it
x += 1
# Later on it can be used for something else
x = "a string" # Now x is a string and adding a number produces an error
x + 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
- To convert objects to a string use the
str() function
x = 42
"The answer is " + str(x)
- Note that, in this case,
str(x) is not the same as 'x'
- The Python for loop is much the same as in other languages
for i in range(0, 5):
print i
# Prints numbers 0 -> 4
# Lists can be accessed directly
fibs = [1,1,2,3,5]
for i in fibs:
print i
# prints each value in the list
- Testing values is also similar
if x < 5:
print "Do something for lower regime"
elif x == 5:
print "Do something for match"
else:
print "Do something for upper regime"
- Most importantly, Python uses indentation not braces to mark whether you are still within a function, if-statement or for loop.
previous contents next