1. Variables, operators and functions.#
Excuting a cell in python#
The print() function in Python is used to output or display text or other information on the screen. It can be used to display a string of text, the value of a variable, or the result of a calculation. The text or information that you want to display is passed as an argument inside the parenthesis of the print() function.
Print () command#
To execute a cell in Python, you can use the run command in Jupyter Notebook or press the “Run” button in the toolbar. You can also use the keyboard shortcut Shift + Enter to execute the cell.
Lets start by excecuting our first code by printing the words ‘Hello world’. Press Shift+Enter to run the cell below. You should see the output “Hello, World!” displayed below the cell. Notice that we have to write the sentence inside the quotation marks to indicate that the data is of string type.
Alternatively, You can also execute the code by clicking on the Run button in the toolbar or by using the run command in the Jupyter Notebook.
print ('Hello, world!')
Hello, world!
Now, try to fill in your name and print the following sentence in the next cell:
print ('My name is _____')
My name is _____
Basic input and out definitions in python#
Value#
In Python, a value is any data that can be stored in a variable. It can be a number (such as an integer or a float), a string (a sequence of characters), a Boolean (True or False), or other types of data. For example
x = 5 # x is a variable that holds an integer value of 5
y = "Hello World" # y is a variable that holds a string value of "Hello World"
z = True # z is a variable that holds a Boolean value of True
Variable#
A variable is a container that holds a value, which is like a label or a name given to the value that is stored inside it. You can use variables to store values and then use them later in your code. You can also change the value of a variable at any time. For example:
x = 5 # x is a variable that holds an integer value of 5
x = x + 2 # x now holds the value of 7
String#
A string is a sequence of characters, enclosed in quotation marks. You can use strings to store text, such as words and sentences. You can also use them to display messages to the user or to create strings that hold specific data, like a name or an address. Strings are a very important data type in python and you will use it very frequently. For example:
"Hello World"
'Hello World'
List#
A list in Python is a collection of values stored in a single object, similar to arrays in other programming languages. Lists can contain elements of any type, including numbers, strings, and other objects.
To create a list in Python, you can use square bracket [ ] notation and include the values you want to store in the list, separated by commas.
For a beginner, it’s important to remember the following when creating lists in Python:
Lists start with a square bracket [ ]
Values in the list are separated by commas
Lists can contain elements of any type, including numbers, strings, and other objects.
# create a list
my_list = [1, 2, 3.14, "Hello", True]
# print the list
print(my_list)
[1, 2, 3.14, 'Hello', True]
Indexing in Python is a way to access specific elements in a list or array. Think of a list as a row of boxes, where each box contains a value. The index is the number assigned to each box [ ] and it allows us to locate a specific value or object. Lists in Python are zero-indexed, meaning that the first element in the list is stored at index 0, the second element is stored at index 1, and so on. For example, we an print any element in out created list by specifying the index releated:
# access elements by index
print(my_list[0]) # prints the integer 1
print(my_list[3]) # prints the string "Hello"
print (my_list[2]) # prints the float 3.14
1
Hello
3.14
type () of data in python#
In Python, you can use the built-in type() function to determine the type of an object. For example:
x = 5
print(type(x)) # Output: <class 'int'>
y = "hello"
print(type(y)) # Output: <class 'str'>
z = [1, 2, 3]
print(type(z)) # Output: <class 'list'>
<class 'int'>
<class 'str'>
<class 'list'>
You can also check an object’s type very simply by:
x2 = 5
type(x2) # Output: int
int
y2 = 'hello'
type(y2) # Output: str
str
z2 = [1, 2, 3]
type(z2) # Output: list
list
Arithmetic Operators#
Math sign |
Python sign |
name |
---|---|---|
+ |
+ |
addition |
- |
- |
subtraction |
* |
* |
multiplication |
/ |
/ |
division |
^ |
** |
exponentiation |
mod |
% |
modulus |
// |
floor division |
Arithmetic operators: These operators perform mathematical operations, such as addition, subtraction, multiplication, and division. Examples:
x = 5
y = 2
print(x + y) # Output: 7
print(x - y) # Output: 3
print(x * y) # Output: 10
print(x / y) # Output: 2.5
print(x**y) # output: 25
7
3
10
2.5
25
Error codes in python#
When you run a Python script or code in a cell, the code is executed line by line, starting from the first line and moving down the code.
If an error occurs, Python will stop executing the code at the line where the error occurs and will display an error message. The first line of the error will indicating the line number where the error occurred. This is often the most informative as it tells you where in your code the problem is. The last line in the error message will tell you what the problem in this line is.
The code results in a TypeError because you are trying to add a variable of type integer (a) to a variable of type string (b). In python, you can only add two variables of the same type. You can’t add an int to a string. If you want to concatenate the string and the int you can convert the int to string before adding them together.
Here is an example:
a = 0
b = "hello"
c = str(a) + b
print (c)
0hello
Or you can use the format() method to insert the value of a into the string b.
a = 5
b = "hello {}"
c = b.format(a)
print (c)
hello 5
Or you can use f-strings (formatted string literals) that are available from python 3.6 and above. You can show a nummerical output with any string you want using f-strings. The code you need to type for f-strings: f ‘ text {output} ‘. The output has to be inside the curly brackets –> { }
a = 5
b = "hello"
c = f"{b} {a}"
print (c)
hello 5
Comparison Operators
In Python, you often want to compare a value with another. For that, you use comparison operators.#
Math sign
Python sign
Meaning
\(=\)
\(==\)
Equal to
\(>\)
\(>\)
Greater than
\(<\)
\(<\)
Less than
\(\geqslant\)
\(>=\)
Greater than or equal to
\(\leqslant\)
\(<=\)
Less than or equal to
\(\neq\)
\(!=\)
Not equal to
Comparison operators: These operators compare two values and return a Boolean value (True or False). Examples:
x = 5
y = 2
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
False
True
True
False
True
False
Control flow statements in Python#
There are several control flow statements in Python that are used to control the flow of execution of a program. The most important ones are:
if statement: The if statement is used to check a certain condition, and if the condition is true, the code within the if block will be executed. If the condition is false, the code within the if block will be skipped. For example:
x = 5
if x > 0:
print("x is positive")
x is positive
if-else statement: The if-else statement is an extension of the if statement, which allows you to specify a block of code to be executed if the condition is true, and a different block of code to be executed if the condition is false. Example:
x = -2
if x > 0:
print("x is positive")
else:
print("x is non-positive")
x is non-positive
if-elif-else statement: The if-elif-else statement is an extension of the if-else statement, which allows you to check multiple conditions and execute different code blocks based on the first condition that is true. This is how you use them:
x = 0
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
x2 = -2
if x2 > 0:
print("x2 is positive")
elif x2 == 0:
print("x2 is zero")
else:
print("x2 is negative")
x is zero
x2 is negative
Indexing#
Indexing is a method in Python to access individual elements in a list by their position. This is a fundamental feature of Python’s list data structure, allowing you to retrieve specific elements from the list. Elements are stored in a sequential manner and can be accessed using their index (integer value indicating their position).
Functions#
In Python, a function is a block of code that can be reused multiple times throughout a program. Functions are useful for organizing and structuring code, and for breaking down complex tasks into smaller, more manageable pieces.
Below are some examples of common built-in Python functions and what they do:
print()
Prints input to screen
type()
Returns the type of the input
abs()
Returns the absolute value of the input
min()
Returns the minimum value of the input.
(input could be a list, tuple, etc.)
max()
Same as above, but returns the maximum value
sum()
Returns the sum of the input
(input could be a list, tuple, etc.)
Here is a step-by-step guide on how to create any function in Python:
Step 1: Define the function using the def keyword, followed by the function name, and a set of parentheses.
Step 2: Define the code block that will be executed when the function is called. This code block should be indented underneath the function definition. For example:
def greet():
print("Hello, World!")
Step 3: (Optional) Add parameters to the function, which are values that can be passed into the function when it is called. These parameters are defined within the parentheses of the function definition. For example:
def greet(name):
print("Hello, " + name + "!")
Step 4: (Optional) Add a return statement to the function, which is used to return a value or an expression from the function. For example:
def add(x, y):
return x + y
Step 5: Call the function by using the function name, followed by a set of parentheses. For example:
greet("John Weller")
Hello, John Weller!
Thus, to create and use the function we write it all in one cell as follows:
def greet(name):
print("Hello, " + name + "!")
greet("John")
greet("Mary Jane")
Hello, John!
Hello, Mary Jane!
In this example, the function greet() is defined with one parameter name, the function is called twice, first with “John” as an argument, then with “Mary” as an argument, the function will print out a greeting message each time it’s called –> the input of the created function is the argument and the output is the greeting message.
Functions are essential to programming, they allow you to organize, structure and reuse your code in an efficient and readable way.
Math sign |
Python sign |
Meaning |
---|---|---|
\(=\) |
\(==\) |
Equal to |
\(>\) |
\(>\) |
Greater than |
\(<\) |
\(<\) |
Less than |
\(\geqslant\) |
\(>=\) |
Greater than or equal to |
\(\leqslant\) |
\(<=\) |
Less than or equal to |
\(\neq\) |
\(!=\) |
Not equal to |
Comparison operators: These operators compare two values and return a Boolean value (True or False). Examples:
x = 5
y = 2
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
False
True
True
False
True
False
Control flow statements in Python#
There are several control flow statements in Python that are used to control the flow of execution of a program. The most important ones are:
if statement: The if statement is used to check a certain condition, and if the condition is true, the code within the if block will be executed. If the condition is false, the code within the if block will be skipped. For example:
x = 5
if x > 0:
print("x is positive")
x is positive
if-else statement: The if-else statement is an extension of the if statement, which allows you to specify a block of code to be executed if the condition is true, and a different block of code to be executed if the condition is false. Example:
x = -2
if x > 0:
print("x is positive")
else:
print("x is non-positive")
x is non-positive
if-elif-else statement: The if-elif-else statement is an extension of the if-else statement, which allows you to check multiple conditions and execute different code blocks based on the first condition that is true. This is how you use them:
x = 0
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
x2 = -2
if x2 > 0:
print("x2 is positive")
elif x2 == 0:
print("x2 is zero")
else:
print("x2 is negative")
x is zero
x2 is negative
Indexing#
Indexing is a method in Python to access individual elements in a list by their position. This is a fundamental feature of Python’s list data structure, allowing you to retrieve specific elements from the list. Elements are stored in a sequential manner and can be accessed using their index (integer value indicating their position).
Functions#
In Python, a function is a block of code that can be reused multiple times throughout a program. Functions are useful for organizing and structuring code, and for breaking down complex tasks into smaller, more manageable pieces.
Below are some examples of common built-in Python functions and what they do:
print()
Prints input to screentype()
Returns the type of the inputabs()
Returns the absolute value of the inputmin()
Returns the minimum value of the input. (input could be a list, tuple, etc.)max()
Same as above, but returns the maximum valuesum()
Returns the sum of the input (input could be a list, tuple, etc.)
Here is a step-by-step guide on how to create any function in Python:
Step 1: Define the function using the def keyword, followed by the function name, and a set of parentheses.
Step 2: Define the code block that will be executed when the function is called. This code block should be indented underneath the function definition. For example:
def greet():
print("Hello, World!")
Step 3: (Optional) Add parameters to the function, which are values that can be passed into the function when it is called. These parameters are defined within the parentheses of the function definition. For example:
def greet(name):
print("Hello, " + name + "!")
Step 4: (Optional) Add a return statement to the function, which is used to return a value or an expression from the function. For example:
def add(x, y):
return x + y
Step 5: Call the function by using the function name, followed by a set of parentheses. For example:
greet("John Weller")
Hello, John Weller!
Thus, to create and use the function we write it all in one cell as follows:
def greet(name):
print("Hello, " + name + "!")
greet("John")
greet("Mary Jane")
Hello, John!
Hello, Mary Jane!
In this example, the function greet() is defined with one parameter name, the function is called twice, first with “John” as an argument, then with “Mary” as an argument, the function will print out a greeting message each time it’s called –> the input of the created function is the argument and the output is the greeting message.
Functions are essential to programming, they allow you to organize, structure and reuse your code in an efficient and readable way.