We can do simple calculations with Python by entering a calculation directly into the Python console.
>>> 2 + 3 5
The parentheses determine which operations are performed first.
>>> 2 * (3 + 4) 14
>>> -10 -10
>>> 10/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero
The ** operator in Python is used to raise the number on the left to the power of the exponent of the right.
>>> 2**3 8
>>> 6 % 4 2
You can use the modulo function (%) with 10 to find the ones’ place of an integer.
>>> 2%10 2
random.randint(5, 10) could return any integer between 5 and 10 including both 5 and 10. We need to
import random to use this method.
import random num = random.randint(5, 10) print(num)
x = x + 5to
x += 3. We can apply with other operators such as -, *, / and % as well.
These operators can be used on types other than numbers such as strings.
>>> x = "Hello" >>> print(x) Hello >>> x += " World" >>> print(x) Hello World
In Python, comments start with a #. To add a multiline comment you could insert a # for each line.
# This is a comment
Python uses indentation to indicate a block of code. Python will give you an error if you skip the indentation.
number = 10 if number > 2: print("Number is greater than two!")
A variable stores a value in Python program.
We define a variable using an equals sign (=).
Variables can be reassigned as many times as you want, in order to change their value.
>>> x = 5 >>> print(x) 5 >>> x = "Hello" >>> print(x) Hello
Note: If you try to reference a variable you haven’t assigned, the program will show error.
Rules for variable name
print() function displays the string value on the screen. The message to be printed should be surrounded by quotes.
If no arguments are provided, the print() function will output a blank line.
To get input from the user in Python, we use input function.
The function prompts the user for input, and returns what they enter as a string.
>>> input("Enter your name: ") Enter your name: Jane 'Jane'
len() function returns the number of characters in the string
Python point to the location of error with a ^ character.
Modules (sometimes called packages or libraries) help group together related sets of tools in Python.
import pandas as pd