Base_syntax
Python is an interpreted programming language, this means that as a developer you write Python (.py) files in a text editor and then put those files into the python interpreter to be executed.
The way to run a python file is like this on the command line:
1
C:\Users\*Your Name*>python helloworld.py
Python can be run as a command line itself.
Type the following on the Windows, Mac or Linux command line:
1
C:\Users\Your Name>python
Or, if the “python” command did not work, you can try “py”:
1
C:\Users\Your Name>py
Indentation
Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
1 | if 5 > 2: |
The number of spaces is up to you as a programmer, but it has to be at least one.
You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:
Syntax Error:
1 | if 5 > 2: |
Variables
In Python, variables are created when you assign a value to it:
1
2
3
4x=5
y="Hello"
print(x)
print(y)output
1
25
HelloVariables do not need to be declared with any particular type, and can even change type after they have been set.
1
2
3x=5
x="Hello"
print(x)output
1
Hello
String variables can be declared either by using single or double quotes:
1
2
3x = "John"
# is the same as
x = 'John'Casting
If you want to specify the data type of a variable, this can be done with casting.
1
2
3x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0Get the Type
You can get the data type of a variable with the
type()function.1
2
3
4x = 5
y = "John"
print(type(x))
print(type(y))Variable name
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (age, Age and AGE are three different variables)
- A variable name cannot be any of the Python keywords.
Output Variable
In the
print()function, you output multiple variables, separated by a comma:1
2
3
4
5
6x="Python"
y="is"
z="awesome"
print(x,y,z)
#Python is awesomeYou can also use the
+operator to output multiple variables:(But
+will not separate the word by space. In the string , the function of+is concatenating the strings)1
2
3
4x = "Python"
y = "is"
z = "awesome"
print(x + ' ' + y + ' ' + z)For numbers, the
+character works as a mathematical operator:1
2
3x = 5
y = 10
print(x + y)In the
print()function, when you try to combine a string and a number with the+operator, Python will give you an error:1
2
3x = 5
y = "John"
print(x + y)The best way to output multiple variables in the
print()function is to separate them with commas, which even support different data types:1
2
3x = 5
y = "John"
print(x, y)Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
1
2
3
4
5
6
7
8
9x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)Global Keyword
To create a global variable inside a function, you can use the
globalkeyword.1
2
3
4
5
6def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Data Types
Python has the following data types built-in by default, in these categories:
| 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 |
Setting the data type
| Example | Data Type |
|---|---|
| x = “Hello World” | str |
| x = 20 | int |
| x = 20.5 | float |
| x = 1j | complex |
| x = [“apple”, “banana”, “cherry”] | list |
| x = (“apple”, “banana”, “cherry”) | tuple |
| x = range(6) | range |
| x = {“name” : “John”, “age” : 36} | dict |
| x = {“apple”, “banana”, “cherry”} | set |
| x = frozenset({“apple”, “banana”, “cherry”}) | frozenset |
| x = True | bool |
| x = b”Hello” | bytes |
| x = bytearray(5) | bytearray |
| x = memoryview(bytes(5)) | memoryview |
| x = None | NoneType |
Get the data types
You can get the data type of any object by using the
type()function:1
2
3x = 5
print(type(x))
# <class 'int'>
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
‘hello’ is the same as “hello”.
Multiline Strings
You can assign a multiline string to a variable by using three quotes, Or three single quotes:
1 | a = """Lorem ipsum dolor sit amet, |
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
1 | a = "Hello, World!" |
String Length
To get the length of a string, use the len() function.
1 | a = "Hello, World!" |
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
1 | txt = "The best things in life are free!" |
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
1 | b = "Hello, World!" |
By leaving out the start index, the range will start at the first character:
1 | b = "Hello, World!" |
By leaving out the end index, the range will go to the end:
1 | b = "Hello, World!" |
Modify Strings
Python has a set of built-in methods that you can use on strings.
The upper() method returns the string in upper case:
1 | a = "Hello, World!" |
The lower() method returns the string in lower case:
1 | a = "Hello, World!" |
The strip() method removes any whitespace from the beginning or the end:
1 | a = " Hello, World! " |
The replace() method replaces a string with another string:
1 | a = "Hello, World!" |
The split() method returns a list where the text between the specified separator becomes the list items.
1 | a = "Hello, World!" |
Python Collections
There are four collection data types in the Python programming language:
Listis a collection which is ordered and changeable. Allows duplicate members.Tupleis a collection which is ordered and unchangeable. Allows duplicate members.Setis a collection which is unordered, unchangeable, and unindexed. No duplicate members.Dictionaryis a collection which is ordered and changeable. No duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.
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 means that we cannot change the items after the set has been created.
Duplicates Not Allowed Sets cannot have two items with the same value.
Lists
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
List items are ordered, changeable, and allow duplicate values.
Listsare created usingsquare brackets:1
2a=[1,2,3,4,5]
print(a)output
1
[1, 2, 3, 4, 5]
A list can contain different data types:
1
list1 = ["abc", 34, True, 40, "male"]
The list() Constructor
It is also possible to use the list() constructor when creating a new list.
1 | thislist = list(("apple", "banana", "cherry")) # note the double round-brackets |
List Length
To determine how many items a list has, use the len() function:
1 | thislist = ["apple", "banana", "cherry"] |
output
1 | 3 |
Data Types
List items can be of any data type. A list can contain different data types:
1 | list1 = ["abc", 34, True, 40, "male"] |
Access List Items
List items are indexed and you can access them by referring to the index number:
1 | thislist = ["apple", "banana", "cherry"] |
output
1 | apple |
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
1 | thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] |
output
1 | ['cherry', 'orange', 'kiwi'] |
Note: The search will start at index 2 (included) and end at index 5 (not included). Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
1 | thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] |
output
1 | ['apple', 'banana', 'cherry', 'orange'] |
By leaving out the end value, the range will go on to the end of the list:
1 | thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] |
output
1 | ['cherry', 'orange', 'kiwi', 'melon', 'mango'] |
Insert items
To insert a new list item, without replacing any of the existing values, we can use the insert() method.
1 | thislist = ["apple", "banana", "cherry"] |
output
1 | ['apple', 'banana', 'hello', 'cherry'] |
Append Items
To add an item to the end of the list, use the append() method:
1 | thislist = ["apple", "banana", "cherry"] |
output
1 | ['apple', 'banana', 'cherry', 'orange'] |
Extend List
To append elements from another list to the current list, use the extend() method.
1 | thislist = ["apple", "banana", "cherry"] |
output
1 | ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya'] |
Remove
The remove() method removes the specified item.
1 | thislist = ["apple", "banana", "cherry"] |
output
1 | ['apple', 'cherry'] |
The pop() method removes the specified index.
1 | thislist = ["apple", "banana", "cherry"] |
output
1 | ['apple', 'cherry'] |
Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
1 | thislist = ["apple", "banana", "cherry"] |
Loop Through a List
You can loop through the list items by using a for loop:
1 | thislist = ["apple", "banana", "cherry"] |
Loop Through the Index Numbers
You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
range(5) function: Create a sequence of numbers from 0 to 4
1 | thislist = ["apple", "banana", "cherry"] |
Using a While Loop
You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
1 | thislist = ["apple", "banana", "cherry"] |
Looping Using List Comprehension
List Comprehension offers the shortest syntax for looping through lists:
1 | thislist = ["apple", "banana", "cherry"] |
List Methods
Python has a set of built-in methods that you can use on lists.
| Method | Description |
|---|---|
| append() | Adds an element at the end of the list |
| clear() | Removes all the elements from the list |
| copy() | Returns a copy of the list |
| count() | Returns the number of elements with the specified value |
| extend() | Add the elements of a list (or any iterable), to the end of the current list |
| index() | Returns the index of the first element with the specified value |
| insert() | Adds an element at the specified position |
| pop() | Removes the element at the specified position |
| remove() | Removes the item with the specified value |
| reverse() | Reverses the order of the list |
| sort() | Sorts the list |
Tuples
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets
1 | thistuple = ("apple", "banana", "cherry") |
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
1 | thistuple = ("apple",) |
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
1 | thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets |
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
1 | thistuple = ("apple", "banana", "cherry") |
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
1 | thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") |
Add Items
Since tuples are immutable, they do not have a build-in append() method, but there are other ways to add items to a tuple.
Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.
1
2
3
4
5
6thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)
#('apple', 'banana', 'cherry', 'orange')Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple:
1
2
3
4
5thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items:
1 | Convert the tuple into a list, remove "apple", and convert it back into a tuple: |
Loop Through a Tuple
Iterate through the items and print the values:
1 | thistuple = ("apple", "banana", "cherry") |
You can also loop through the tuple items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
1 | thistuple = ("apple", "banana", "cherry") |
Using a While Loop
You can loop through the tuple items by using a while loop.
Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
1 | thistuple = ("apple", "banana", "cherry") |
Set
Sets are written with curly brackets.
A set is a collection which is unordered, unchangeable, unindexed, and Duplicates Not Allowed. So you cannot be sure in which order the items will appear.
1 | thisset = {"apple", "banana", "cherry"} |
Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
1 | thisset = {"apple", "banana", "cherry"} |
Check if “banana” is present in the set:
1 | thisset = {"apple", "banana", "cherry"} |
Add Items
Add an item to a set, using the add() method:
1 | thisset = {"apple", "banana", "cherry"} |
Add Sets
To add items from another set into the current set, use the update() method.
1 | thisset = {"apple", "banana", "cherry"} |
The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).
1 | thisset = {"apple", "banana", "cherry"} |
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
1 | thisset = {"apple", "banana", "cherry"} |
Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered, changeable and do not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
1 | thisdict={ |
The dict() Constructor
1 | thisdict = dict(name = "John", age = 36, country = "Norway") |
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
1 | thisdict = dict(name = "John", age = 36, country = "Norway") |
Get Keys
The keys() method will return a list of all the keys in the dictionary.
1 | thisdict = dict(name = "John", age = 36, country = "Norway") |
Get Values
The values() method will return a list of all the values in the dictionary.
1 | thisdict = dict(name = "John", age = 36, country = "Norway") |
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
1 | thisdict = dict(name = "John", age = 36, country = "Norway") |
Change Values
You can change the value of a specific item by referring to its key name:
1 | thisdict = { |
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
1 | thisdict = { |
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
1 | thisdict = { |
The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.
1 | thisdict = { |
The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
1 | thisdict = { |
The clear() method empties the dictionary:
1 | thisdict = { |
Loop Through a Dictionary
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
1 | thisdict = dict(name = "John", age = 36, country = "Norway") |
You can use the keys() method to return the keys of a dictionary:
1 | for x in thisdict.keys(): |
Return the values
1 | thisdict = dict(name = "John", age = 36, country = "Norway") |
You can also use the values() method to return values of a dictionary:
1 | for x in thisdict.values(): |
Loop through both keys and values, by using the items() method:
1 | thisdict = dict(name = "John", age = 36, country = "Norway") |
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
If … Else
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.
If statements
1 | a = 33 |
Elif
The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”.
1 | a = 33 |
Else
The else keyword catches anything which isn’t caught by the preceding conditions.
1 | a = 200 |
And
The and keyword is a logical operator, and is used to combine conditional statements:
1 | a = 200 |
Or
The or keyword is a logical operator, and is used to combine conditional statements:
1 | a = 200 |
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional statement:
1 | a = 33 |
The pass Statement
if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
1 | a = 33 |
Loops
Python has two primitive loop commands:
- while loops
- for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
1 | i=0 |
Note: remember to increment i, or else the loop will continue forever.
With the break statement we can stop the loop even if the while condition is true:
1 | i = 1 |
With the continue statement we can stop the current iteration, and continue with the next:
1 | i = 0 |
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).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
1 | fruits = ["apple", "banana", "cherry"] |
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.
1 | for x in range(6): |
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
1 | for x in range(2,6): |
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):
1 | for x in range(2,6,2): |
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.
Creating a Function
In Python a function is defined using the def keyword:
1 | def my_function(): |
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function’s perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.
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.
The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
1 | def my_function(fname): |
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:
1 | def my_function(*kids): |
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
1 | def my_function(child3, child2, child1): |
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
1 | def my_function(food): |
Return Values
To let a function return a value, use the return statement:
1 | def my_function(x): |
Recursion
The process of repeating a function, each time applying it to the result of the previous stage.
Python also accepts function recursion, which means a defined function can call itself.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
As a example which is a function that counts the factorial:
1 | def tri_recursion(k): |
output
1 | Recursion Example Results |
As you can see, every time the statement result = k + tri_recursion(k - 1) is based on the previous result.
Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
lambda *arguments* : *expression*
1 | x = lambda a : a + 10 |
1 | x = lambda a,b :a*b |
Arrays
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Classes/Objects
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.
Create a class
Create a class named MyClass, with a property named x:
1 | class MyClass: |
Create an Object
1 | p1=MyClass() |
The __init__() function
The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in init() function.
All classes have a function called __init__(), which is always executed when the class is being initiated. Note: The __init__() function is called automatically every time the class is being used to create a new object.
Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:
1 | class Person: |
output
1 | ferry |
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
1 | class Person: |
output
1 | Hello, my name is ferry |
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:
1 | Use the words *mysillyobject* and *abc* instead of *self*: |
Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:
1 | class Person: |
Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
super() Function
super() function that will make the child class inherit all the methods and properties from its parent:
1 | class Student(Person): |
Iterator vs Iterable
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
If you have learned C language, you can take an iterator in Python as an point in C
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from. All these objects have a iter() method which is used to get an iterator:
1 | mytuple = ("apple", "banana", "cherry") |
output
1 | apple |
Try & Except
The
tryblock lets you test a block of code for errors.The
exceptblock lets you handle the error.The
finallyblock lets you execute code, regardless of the result of the try- and except blocks.
As an example,
1 | try: |
The try block generate the except, because the x variable is not defined.
Since the try block raises an error, the except block will be executed.
output
1 | An exception occurred |
If there have not a try block, the program will crash and raise a error.
1 | print(x) |
output
1 | Traceback (most recent call last): |
Many Exceptions
You can define as many exceptions as you want.
And also you can execute a special except block for a special kind of error.
1 | try: |
output
1 | Variable x is not defined |
Scope
A variable is only available from inside the region it is created. This is called scope.
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.
The module can contain functions, but also variables of all types (arrays, dictionaries, objects etc)
Create a Module
To create a module just save the code you want in a file with the file extension .py
1 | person1 = { |
Save this code in a file named mymodule.py
Use a Module
Now we can use the module we just created, by using the import statement:
1 | import mymodule |
Note: When using a function from a module, use the syntax: module_name.variable_name.
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Create an alias for mymodule called mx:
1 | import mymodule as mx |
dir() Function
There is a built-in function to list all the function names (or variable names) in a module. The dir() function:
List all the defined names belonging to the platform module:
1 | import platform |
Import From Module
You can choose to import only parts from a module, by using the from keyword.
1 | from mymodule import person1 |
File Handling
Python has several functions for creating, reading, updating, and deleting files.
open()
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
Using "w" you won’t be able to read the file.
"x" - Create - Creates the specified file, returns an error if the file exists
read()
The open() function returns a file object, which has a read() method for reading the content of the file:
1 | f = open("demofile.txt", "r") |
write()
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
1 | f = open("demofile2.txt", "a") |
Note: the “w” method will overwrite the entire file.
1 | f = open("demofile3.txt", "w") |
close()
It is a good practice to always close the file when you are done with it.
1 | f = open("demofile.txt", "r") |
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
1 | import os |
with open
When you use with statement with open function, you do not need to close the file at the end, because with would automatically close it for you.
1 | with open("text.txt", "w") as f: |
JSON in Python
Python has a built-in package called json, which can be used to work with JSON data.
If you have a JSON string, you can parse it by using the json.loads() method.
1 | import json |
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
1 | import json |
if __name__ == "__main__"
Python files are called modules and they are identified by the .py file extension. A module can define functions, classes, and variables.
__name__ is a model name. When a model is executed, __name__ equal to __main__. When a model is not executed, __name__ equal to its file name.
It’s boilerplate code that protects users from accidentally invoking the script when they didn’t intend to.
It allows the code in the module to be importable by other modules, without executing the code block beneath on import.
