Lesson 4 Python Basics
Lesson 4 Python Basics
4.1. Introduction
Python can be executed by writing directly in the command line or y creating a python file on the server,
using the .py file extension, and running it in the command line. You can also run Python from a
Graphical User Interface (GUI) environment as well, if you have a GUI application / IDE on your system
that supports Python.
Example
Comments in Python:
#This is a comment
#written in
#more than just one line
print("Hello, World!") #Another comment
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
You can get the data type of a variable with the type()function-print(type(x)).
String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Variable names are case-sensitive.
Python allows you to assign a single value to several variables simultaneously.
x=y=4
In Python, constants are usually declared and assigned in a module. Here, the module is a new file
containing variables, functions, etc which is imported to the main file. Inside the module, constants are
written in all capital letters and underscores separating the words.
4.5. Data types and type casting
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: str
4.6. Operators
Operators are used to perform operations on variables and values. They can be grouped into:
arithmetic, assignment, comparison and logical operators
Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponentiation
// Floor division
4.6.2. Assignment Operators
Assignment operators are used to assign values to variables.
Examples: x=5, x+=1.
4.6.3. Comparison Operators
Comparison operators are used to compare two values.
Operator Name
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
4.6.4. Logical Operators
Logical operators are used to combine conditional statements i.e AND, OR, NOT.
4.7. Functions
A function is a block of code which only runs when it is called. You can pass data, known as parameters,
into a function. A function can return data as a result.
A function is defined using the def keyword:
def my_function():
print("Hello from a function")
To call a function, use the function name followed by parenthesis:
my_function()
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error.