Printing a string is possible with the print( ) function.
print("Let's print some text!")
Let's print some text!
Excercise: Write a code that will print your name.
In Python types of variables don't need to be set. Let's create two different type of variables and print them.
count = 450
words = "Welcome to Python. It won't bite!"
print(count)
print(words)
450 Welcome to Python. It won't bite!
Excercise: Save a number 900 to a variable (you can name it whatever you like). After that print a number that one will get when one adds a number 100 to the variable that you created.
Simple calculations can be done straight in the code. With more complex calculations the modules can be used.
3 + 5
8
3 * 5
15
# In Python 2 the result of the division is given as an integer. Python 3 can also return a float.
# In Python 2 this can be fixed by writing "from __future__ import division" in the code cell before the calculation.
print(7 / 5)
from __future__ import division
print(7 / 5)
1.4 1.4
Functions are subprograms that can be called to do some specific task that they are made to do. For example let's use the function abs( ) that will calculate the absolute value of the argument given to it. Let's also use the function len( ) that will return the length of the argument given to it.
abs(-9)
9
len("Particle accelerator")
20
Excercise: Try the function len( ) and define the number of the characters in your name with it. Does the function count also spaces?
It is also possible to create own functions. Let's create a function squaring( ) that will calculate and return a square root of the argument that is given to it and print a text "You just used the function." Let's use that function for the number 4.
def squaring(a):
print(a*a)
print("You just used the function.")
squaring(4)
16 You just used the function.
Excercise: Create a function that will multiply the argument given to it by the number 2.