Chapter 1. Basic Concepts and Techniques
Chapter 1. Basic Concepts and Techniques
Or:
print("Hello, World!") #This is a comment
SYNTAX
Python Comments:
• Multiline Comments:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
SYNTAX
Variables: Variables are containers for storing data values.
• Creating Variables:
x=5
y = "John"
print(x)
print(y)
object(s) Any object, and as many as you like. Will be converted to string before printed
sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default is ' '
end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)
flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False).
Default is False
PYTHON DATA TYPES
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
PYTHON NUMBERS
• There are three numeric types in Python:
int
float
complex
• Type Conversion: convert from one type to another with the int(), float(), and
complex() methods.
• Random Number: Python has a built-in module called random that can be used to
make random numbers
#Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
PYTHON STRINGS
• Strings in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "hello".
• Assign String to a Variable: Assigning a string to a variable is done with the
variable name followed by an equal sign and the string.
a = "Hello"
print(a)
PYTHON STRINGS
• Multiline Strings: Can assign a multiline string to a variable by using three quotes.
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
• Strings are Arrays: Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])
PYTHON STRINGS
• String Length: To get the length of a string, use the len() function.
a =“Hello, World!"
print(len(a))
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
PYTHON OPERATORS
• Python Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
PYTHON OPERATORS
• Python Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
PYTHON OPERATORS
• Python Logical Operators
• Ordered.
• Tuples are ordered, it means that the items have a defined order, and that order will not
change.
• Unchangeable.
• Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
• Allow Duplicates.
• Since tuples are indexed, they can have items with the same value.
PYTHON SETS
• Sets are used to store multiple items in a single variable.
• A set is a collection which is unordered, unchangeable*, and unindexed.
• Sets are written with curly brackets.
• Ex:
thisset = {"apple", "banana", "cherry"}
print(thisset)
PYTHON SETS
• Set Items.
• Set items are unordered, unchangeable, and do not allow duplicate values.
• Unordered.
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and cannot be referred to
by index or key.
• Unchangeable.
• Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
• Ex:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
PYTHON DICTIONARIES
• Ordered or Unordered?
• Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has
been created.
• Duplicates Not Allowed.
• Dictionaries cannot have two items with the same key:
• Ex:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
SYNTAX
Example 1: solve the equation ax + b = 0
"""
Solves the linear equation ax + b = 0 for x.
Args:
a: The coefficient of the x term.
b: The constant term.
Returns:
The solution for x, or None if a is 0 and b is not 0,
or float('inf') if both a and b are 0.
"""
SYNTAX
Example 1: solve the equation ax + b = 0
def solve_linear_equation(a, b):
if a == 0:
if b != 0:
return None # No solution if a is 0 and b is not 0
else:
return float('inf') # Infinite solutions if a and b are both 0
else:
return -b / a
SYNTAX
Example 1: solve the equation ax + b = 0
# Example usage:
a=2
b=3
solution = solve_linear_equation(a, b)
print(f"The solution for the equation {a}x + {b} = 0 is x = {solution}")
SYNTAX
Example 2: solve the equation ax2 + bx + c = 0
"""
This function solves the quadratic equation ax^2 + bx + c = 0 using the quadratic formula.
Args:
a: The coefficient of the x^2 term.
b: The coefficient of the x term.
c: The constant term.
Returns:
A tuple containing the two solutions of the equation, or None if there are no real solutions.
"""
SYNTAX
Example 2: solve the equation ax2 + bx + c = 0
def quadratic_equation(a, b, c):
if a == 0:
return None # Not a quadratic equation
discriminant = b**2 - 4 * a * c
if discriminant < 0:
return None # No real solutions
elif discriminant == 0:
return -b / (2 * a) # One real solution
else:
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
return root1, root2
SYNTAX
Example 2: solve the equation ax2 + bx + c = 0
# Example usage
a=1
b=2
c=1
roots = quadratic_equation(a, b, c)
if roots is None:
print("No real solutions")
elif isinstance(roots, float):
print("One real solution:", roots)
else:
print("Two real solutions:", roots[0], roots[1])
PYTHON IF ... ELSE
Python Conditions and If statements:
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
PYTHON IF ... ELSE
Python Conditions and If statements:
• An "if statement" is written by using the if keyword.
Ex:
a = 33
b = 200
if b > a:
print("b is greater than a")
PYTHON IF ... ELSE
Python Conditions and If statements:
• Elif: The elif keyword is Python's way of saying "if the previous conditions were not true, then try
this condition".
Ex:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
PYTHON IF ... ELSE
Python Conditions and If statements:
• Short Hand If ... Else
Ex: If you have only one statement to execute:
if a > b: print("a is greater than b")
Ex: If you have two statement to execute, one for if, and one for else:
a=2
b = 330
print("A") if a > b else print("B")
Ex: You can also have multiple else statements on the same line:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
PYTHON IF ... ELSE
Python Conditions and If statements:
• The and, or, and not keyword is a logical operator, they are used to combine conditional
statements:
Ex:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
if a > b or a > c:
print("At least one of the conditions is True")
if not a > b:
print("a is NOT greater than b")
PYTHON IF ... ELSE
Python Conditions and If statements:
• Nested If: You can have if statements inside if statements, this is called nested if statements.
Ex:
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
PYTHON LOOPS
• Python has two primitive loop commands:
• while loops
• for loops
THE WHILE LOOPS
• The while loops: With the while loop we can execute a set of
statements as long as a condition is true.
• Ex:
i=1
while i < 6:
print(i)
i += 1
THE WHILE LOOPS
• The else Statement: With the else statement we can run a
block of code once when the condition no longer is true.
• Ex:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
THE FOR LOOPS
• The for loops: A for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set, or a string).
• Ex:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
THE FOR LOOPS
• Looping Through a String: Even strings are iterable objects,
they contain a sequence of characters.
• Ex:
for x in "banana":
print(x)
THE FOR LOOPS
• The range() Function: To loop through a set of code a
specified number of times, we can use the range() function.
The range() function returns a sequence of numbers, starting
from 0 by default, and increments by 1 (by default), and ends
at a specified number.
• Ex:
for x in range(6):
print(x)
THE FOR LOOPS
• The range() Function: The range() function defaults to 0 as a
starting value, however it is possible to specify the starting
value by adding a parameter: range(start, end), which means
values from start to end (but not including end).
• Ex:
for x in range(2, 6):
print(x)
THE FOR LOOPS
• The break Statement: With the break statement we can stop
the loop before it has looped through all the items.
• Ex:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
THE FOR LOOPS
• The continue Statement: With the continue statement we can stop the
current iteration of the loop, and continue with the next.
• Ex:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
THE FOR LOOPS
• Else in For Loop: The else keyword in a for loop specifies a block of
code to be executed when the loop is finished.
• Ex:
for x in range(6):
print(x)
else:
print("Finally finished!")
THE FOR LOOPS
• Nested Loops: A nested loop is a loop inside a loop. The "inner loop"
will be executed one time for each iteration of the "outer loop".
• Ex:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
PYTHON 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.
PYTHON FUNCTIONS
• Creating a Function.
• In Python a function is defined using the def keyword.
• Example:
def my_function():
print("Hello from a function")
PYTHON FUNCTIONS
• Arguments.
• 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:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
PYTHON FUNCTIONS
• Number of Arguments.
• By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
• Example: This function expects 2 arguments, and gets 2 arguments.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
PYTHON FUNCTIONS
• Arbitrary Arguments, *args.
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the
items accordingly
• Example:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
PYTHON FUNCTIONS
• Return Values.
• To let a function return a value, use the return statement.
• Example:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
PYTHON MODULES
• Consider a module to be the same as a code library.
• A file containing a set of functions you want to include in your application.
PYTHON MODULES
• Create a Module.
• To create a module just save the code you want in a file with the file extension
.py.
• Example: Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
PYTHON MODULES
• Use a Module.
• Now can use the module just created, by using the import statement.
• Example:
import mymodule
mymodule.greeting("Jonathan")
PYTHON MODULES
• Variables in Module.
• The module can contain functions, as already described, but also variables of
all types (arrays, dictionaries, objects etc).
• Example: Save this code in the file mymodule.py.
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
PYTHON MODULES
• Variables in Module.
• Example: Import the module named mymodule, and access the person1
dictionary.
import mymodule
a = mymodule.person1["age"]
print(a)
PYTHON MODULES
• Naming a Module.
• You can name the module file whatever you like, but it must have the file
extension .py.
• Re-naming a Module.
• You can create an alias when you import a module, by using the as keyword.
• Example: Create an alias for mymodule called mx.
import mymodule as mx
a = mx.person1["age"]
print(a)
PYTHON MODULES
• Built-in Modules.
• There are several built-in modules in Python, which you can import whenever
you like.
• Example: Import and use the platform module.
import platform
x = platform.system()
print(x)
PYTHON MODULES
• Using the dir() Function.
• There is a built-in function to list all the function names (or variable names) in
a module. The dir() function.
• Example: List all the defined names belonging to the platform module.
import platform
x = dir(platform)
print(x)
OBJECT ORIENTED PROGRAMMING
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and
methods.
•A Class is like an object constructor, or a "blueprint" for creating
objects.
OBJECT ORIENTED PROGRAMMING
• Create a Class.
• To create a class, use the keyword class.
• Example:
class MyClass:
x=5
OBJECT ORIENTED PROGRAMMING
• Create Object.
• Create an object named p1, and print the value of x.
• Example:
p1 = MyClass()
print(p1.x)
OBJECT ORIENTED PROGRAMMING
• The __init__() Function.
• All classes have a function called __init__(), which is always executed when
the class is being initiated.
• Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created.
OBJECT ORIENTED PROGRAMMING
• The __init__() Function.
• Example: Create a class named Person, use the __init__() function to assign values for name
and age
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
• Note: The __init__() function is called automatically every time the class is being used to
create a new object.
OBJECT ORIENTED PROGRAMMING
• The __str__() Function.
• The __str__() function controls what should be returned when the class object
is represented as a string.
• If the __str__() function is not set, the string representation of the object is
returned.
OBJECT ORIENTED PROGRAMMING
• The __str__() Function.
• Example: The string representation of an object WITH the __str__() function.
class Person:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
OBJECT ORIENTED PROGRAMMING
• Object Methods.
• Objects can also contain methods. Methods in objects are functions that belong to the object.
• Example: Insert a function that prints a greeting, and execute it on the p1 object.
class Person:
def __init__(self, name, age):
self.name = name
Note: The self parameter is a reference to the
self.age = age current instance of the class, and is used to
def myfunc(self): access variables that belong to the class.
• Delete Objects
• You can delete objects by using the del keyword
• Example: Delete the p1 object.
del p1
DEBUGGING AND FIXING ERRORS
SUMMARY