Python
Python
Python interface
python script (script.py)
Example
print (7+10)
<script.py> output:
17
In[1]:
You can add comments to Python scripts. To add comments to your Python
script, you use the # tag.
Example
#Addition
print (7+10)
<script.py> output:
17
In[1]:
Python as a calculator
Python is perfectly suited to do basic calculations. Apart from addition,
subtraction, multiplication and division, there is also support for more
advanced operations such as:
Exponentiation: **. This operator raises the number to its left to the power of
the number to its right. For example 4**2 will give 16.
Modulo: %. This operator returns the remainder of the division of the number
to the left by the number on its right. For example 18 % 7 equals 4.
Examples
#Addition, subtraction
Print(5 + 5)
Print(5 - 5)
#Multiplication, division, modulo, exponentiation
Print(3 * 5)
Print(10 / 2)
Print(18 % 7)
Print(4 ** 2
Suppose you have $100, which you can invest with a 10% return each year.
After one year, it's 100×1.1=110100×1.1=110 dollars, and after two years
it's 100×1.1×1.1=121100×1.1×1.1=121. Add code to calculate how much
money you end up with after 7 years, and print the result.
Print(100 * 1.1 **7)
<script.py> output :
10
0
15
5.0
4
16
194.87171000000012
In[1]:
In Python, a variable allows you to refer to a value with a name. To create a
variable use =, like this example:
x=5
You can now use the name of this variable, x, instead of the actual value, 5.
Remember, = in Python means assignment, it doesn't test equality.
Examples
Savings = 100
Print(savings)
<script.py> output :
100
In[1] :
Savings = 100
Growth_multiplier = 1.1
Result = 194.87171000000012
Print(result)
<script.py> output :
194.87171000000012
In[1] :
Type conversion
Using the + operator to paste together two strings can be very useful in
building custom messages.
Suppose, for example, that you've calculated the return of your investment
and want to summarize the results in a string. Assuming the
integer savings and float result are defined, you can try something like this:
print("I started with $" + savings + " and now have $" + result + ".
Awesome!")
This will not work, though, as you cannot simply sum strings and
integers/floats.
To fix the error, you'll need to explicitly convert the types of your variables.
More specifically, you'll need str(), to convert a value into a
string. str(savings), for example, will convert the integer savings to a string.
Similar functions such as int(), float() and bool() will help you convert
Python values into any type.
Example
Savings = 100
Result = 100 * 1.1 **7
Print(“I started with $” + str(savings) + “and now have $” + str(result) +
“Awesome!”)
Pi_string = 3.1415926
Pi_float = float(pi_string)