Python Code Examples - Sample Script Coding Tutorial For Beginners
Python Code Examples - Sample Script Coding Tutorial For Beginners
Forum Donate
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 1/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
What we will cover:
Learn to code — free 3,000-hour curriculum
Variable De nitions in Python
Python Operators
Conditionals in Python
Functions in Python
Recursion in Python
and more...
💡 Tip: throughout this article, I will use <> to indicate that this part
of the syntax will be replaced by the element described by the text.
For example, <var> means that this will be replaced by a variable
when we write the code.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 2/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
<var_name> = <value>
For example:
age = 56
name = "Nora"
color = "Blue"
If the name of a variable has more than one word, then the Style Guide
for Python Code recommends separating words with an underscore
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 3/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
my_list = [1, 2, 3, 4, 5]
💡 Tip: The Style Guide for Python Code (PEP 8) has great suggestions
that you should follow to write clean Python code.
You just need to call the print() function and write "Hello, Worl
d!" within parentheses:
print("Hello, World!")
"Hello, World!"
Integers
Integers are numbers without decimals. You can check if a number is
an integer with the type() function. If the output is <class 'int'> ,
then the number is an integer.
For example:
>>> type(1)
<class 'int'>
>>> type(15)
<class 'int'>
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 5/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> type(0)
<class 'int'>
Forum Donate
Floats
Floats are numbers with decimals. You can detect them visually by
locating the decimal point. If we call type() to check the data type of
these values, we will see this as the output:
<class 'float'>
>>> type(4.5)
<class 'float'>
>>> type(5.8)
<class 'float'>
>>> type(2342423424.3)
<class 'float'>
>>> type(4.0)
<class 'float'>
>>> type(0.0)
<class 'float'>
>>> type(-23.5)
<class 'float'>
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 6/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Complex Learn to code — free 3,000-hour curriculum
Complex numbers have a real part and an imaginary part denoted
with j . You can create complex numbers in Python with complex() .
The rst argument will be the real part and the second argument will
be the imaginary part.
>>> complex(4, 5)
(4+5j)
>>> complex(6, 8)
(6+8j)
>>> complex(0, 0)
0j
>>> complex(5)
(5+0j)
>>> complex(0, 4)
4j
Strings in Python
Strings incredibly helpful in Python. They contain a sequence of
characters and they are usually used to represent text in the code.
For example:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 7/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
"Hello, World!"
Learn to code — free 3,000-hour curriculum
'Hello, World!'
💡 Tip: Yes! You used a string when you wrote the "Hello, World!"
program. Whenever you see a value surrounded by single or double
quotes in Python, that is a string.
Strings can contain any character that we can type in our keyboard,
including numbers, symbols, and other special characters.
For example:
"45678"
"my_email@email.com"
"#IlovePython"
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 8/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
💡 Tip: Spaces are also counted as characters in a string.
Learn to code — free 3,000-hour curriculum
String Indexing
We can use indices to access the characters of a string in our Python
program. An index is an integer that represents a speci c position in
the string. They are associated to the character at that position.
String: H e l l o
Index: 0 1 2 3 4
💡 Tip: Indices start from 0 and they are incremented by 1 for each
character to the right.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 9/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
For example:
Learn to code — free 3,000-hour curriculum
>>> my_string[0]
'H'
>>> my_string[1]
'e'
>>> my_string[2]
'l'
>>> my_string[3]
'l'
>>> my_string[4]
'o'
>>> my_string[-1]
'o'
>>> my_string[-2]
'l'
>>> my_string[-3]
'l'
>>> my_string[-4]
'e'
>>> my_string[-5]
'H'
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 10/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
String Slicing
We may also need to get a slice of a string or a subset of its characters.
We can do so with string slicing.
<string_variable>[start:stop:step]
start is the index of the rst character that will be included in the
slice. By default, it's 0 .
<string_variable>[start:stop]
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 11/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
For example:
Learn to code — free 3,000-hour curriculum
>>> freecodecamp[2:8]
'eeCode'
>>> freecodecamp[0:3]
'fre'
>>> freecodecamp[0:4]
'free'
>>> freecodecamp[4:7]
'Cod'
>>> freecodecamp[4:8]
'Code'
>>> freecodecamp[8:11]
'Cam'
>>> freecodecamp[8:12]
'Camp'
>>> freecodecamp[8:13]
'Camp'
💡 Tip: Notice that if the value of a parameter goes beyond the valid
range of indices, the slice will still be presented. This is how the
creators of Python implemented this feature of string slicing.
If we customize the step , we will "jump" from one index to the next
according to this value.
For example:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 12/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Learn
>>> freecodecamp to code — free 3,000-hour curriculum
= "freeCodeCamp"
>>> freecodecamp[0:9:2]
'feCdC'
>>> freecodecamp[2:10:3]
'eoC'
>>> freecodecamp[1:12:4]
'roa'
>>> freecodecamp[4:8:2]
'Cd'
>>> freecodecamp[3:9:2]
'eoe'
>>> freecodecamp[1:10:5]
'rd'
>>> freecodecamp[10:2:-1]
'maCedoCe'
>>> freecodecamp[11:4:-2]
'paeo'
>>> freecodecamp[5:2:-4]
'o'
And we can omit a parameter to use its default value. We just have to
include the corresponding colon ( : ) if we omit start , stop , or both:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 13/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Learn
>>> freecodecamp to code — free 3,000-hour curriculum
= "freeCodeCamp"
# Default start
>>> freecodecamp[:8:2]
'feCd'
# Default stop
>>> freecodecamp[4::3]
'Cem'
💡 Tip: The last example is one of the most common ways to reverse a
string.
f-Strings
In Python 3.6 and more recent versions, we can use a type of string
called f-string that helps us format our strings much more easily.
first_name = "Nora"
favorite_language = "Python"
value = 5
5 multiplied by 2 is: 10
We can also call methods within the curly braces and the value
returned will be replaced in the string when we run the program:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 15/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
print(f"{freecodecamp.lower()}")
freecodecamp
String Methods
Strings have methods, which represent common functionality that has
been implemented by Python developers, so we can use it in our
programs directly. They are very helpful to perform common
operations.
<string_variable>.<method_name>(<arguments>)
For example:
>>> freecodecamp.capitalize()
'Freecodecamp'
>>> freecodecamp.count("C")
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 16/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> eecodeca p.cou t( C )
2 Forum Donate
>>> freecodecamp.index("p")
11
>>> freecodecamp.isalnum()
True
>>> freecodecamp.isalpha()
True
>>> freecodecamp.isdecimal()
False
>>> freecodecamp.isdigit()
False
>>> freecodecamp.isidentifier()
True
>>> freecodecamp.islower()
False
>>> freecodecamp.isnumeric()
False
>>> freecodecamp.isprintable()
True
>>> freecodecamp.isspace()
False
>>> freecodecamp.istitle()
False
>>> freecodecamp.isupper()
False
>>> freecodecamp.lower()
'freecodecamp'
>>> freecodecamp.lstrip("f")
'reeCodeCamp'
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 17/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> freecodecamp.rstrip("p")
'freeCodeCam' Learn to code — free 3,000-hour curriculum
>>> freecodecamp.split("C")
['free', 'ode', 'amp']
>>> freecodecamp.swapcase()
'FREEcODEcAMP'
>>> freecodecamp.title()
'Freecodecamp'
>>> freecodecamp.upper()
'FREECODECAMP'
💡 Tip: All string methods return copies of the string. They do not
modify the string because strings are immutable in Python.
Booleans in Python
Boolean values are True and False in Python. They must start with
an uppercase letter to be recognized as a boolean value.
For example:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 18/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> type(true)
Traceback (most recent call last):
File "<pyshell#92>", line 1, in <module>
type(true)
NameError: name 'true' is not defined
>>> type(false)
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
type(false)
NameError: name 'false' is not defined
Lists in Python
Now that we've covered the basic data types in Python, let's start
covering the built-in data structures. First, we have lists.
[1, 2, 3, 4, 5]
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 19/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
my_list = [1, 2, 3, 4, 5]
Nested Lists
Lists can contain values of any data type, even other lists. These inner
lists are called nested lists.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 20/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
In this example, [1, 2, 3] and [4, 5, 6] are nested lists.
Learn to code — free 3,000-hour curriculum
Here we have other valid examples:
>>> my_list[0]
[1, 2, 3]
>>> my_list[1]
[4, 5, 6]
Forum Donate
[0, 2, 0],
Learn
[1, 0, 3]] to code — free 3,000-hour curriculum
List Length
We can use the len() function to get the length of a list (the number
of elements it contains).
For example:
>>> len(my_list)
4
<list_variable>[<index>] = <value>
For example:
>>> letters
['z', 'b', 'c', 'd']
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 22/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
For example:
>>> my_list.append(5)
>>> my_list
[1, 2, 3, 4, 5]
For example:
>>> my_list.remove(3)
>>> my_list
[1, 2, 4]
💡 Tip: This will only remove the rst occurrence of the element. For
example, if we try to remove the number 3 from a list that has two
number 3s, the second number will not be removed:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 23/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> my_list.remove(3)
>>> my_list
[1, 2, 3, 4]
List Indexing
We can index a list just like we index strings, with indices that start
from 0 :
>>> letters[0]
'a'
>>> letters[1]
'b'
>>> letters[2]
'c'
>>> letters[3]
'd'
List Slicing
We can also get a slice of a list using the same syntax that we used
with strings and we can omit the parameters to use their default
values. Now, instead of adding characters to the slice, we will be
adding the elements of the list.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 24/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
For example:
>>> my_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> my_list[2:6:2]
['c', 'e']
>>> my_list[2:8]
['c', 'd', 'e', 'f', 'g', 'h']
>>> my_list[1:10]
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> my_list[4:8:2]
['e', 'g']
>>> my_list[::-1]
['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
>>> my_list[::-2]
['i', 'g', 'e', 'c', 'a']
>>> my_list[8:1:-1]
['i', 'h', 'g', 'f', 'e', 'd', 'c']
List Methods
Python also has list methods already implemented to help us perform
common list operations. Here are some examples of the most
commonly used list methods:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 25/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> my_list = [1, 2, 3, 3, 4]
Learn to code — free 3,000-hour curriculum
>>> my_list.append(5)
>>> my_list
[1, 2, 3, 3, 4, 5]
>>> my_list.remove(2)
>>> my_list
[1, 15, 3, 3, 4, 5, 6, 7, 8, 2, 2]
>>> my_list.pop()
2
>>> my_list.index(6)
6
>>> my_list.count(2)
1
>>> my_list.sort()
>>> my_list
[1, 2, 3, 3, 4, 5, 6, 7, 8, 15]
>>> my_list.reverse()
>>> my_list
[15, 8, 7, 6, 5, 4, 3, 3, 2, 1]
>>> my_list.clear()
>>> my_list
[]
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 26/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Tuples in Python
Learn to code — free 3,000-hour curriculum
To de ne a tuple in Python, we use parentheses () and separate the
elements with a comma. It is recommended to add a space after each
comma to make the code more readable.
(1, 2, 3, 4, 5)
my_tuple = (1, 2, 3, 4, 5)
Tuple Indexing
We can access each element of a tuple with its corresponding index:
>>> my_tuple[0]
1
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 27/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> my_tuple[2]
3
>>> my_tuple[3]
4
>>> my_tuple[-1]
4
>>> my_tuple[-2]
3
>>> my_tuple[-3]
2
>>> my_tuple[-4]
1
Tuple Length
To nd the length of a tuple, we use the len() function, passing the
tuple as argument:
Nested Tuples
Tuples can contain values of any data type, even lists and other tuples.
These inner tuples are called nested tuples.
In this example, we have a nested tuple (4, 5, 6) and a list. You can
access these nested data structures with their corresponding index.
For example:
>>> my_tuple[0]
[1, 2, 3]
>>> my_tuple[1]
(4, 5, 6)
Tuple Slicing
We can slice a tuple just like we sliced lists and strings. The same
principle and rules apply.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 29/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
For example:
>>> my_tuple[3:8]
(7, 8, 9, 10)
>>> my_tuple[2:9:2]
(6, 8, 10)
>>> my_tuple[:8]
(4, 5, 6, 7, 8, 9, 10)
>>> my_tuple[:6]
(4, 5, 6, 7, 8, 9)
>>> my_tuple[:4]
(4, 5, 6, 7)
>>> my_tuple[3:]
(7, 8, 9, 10)
>>> my_tuple[2:5:2]
(6, 8)
>>> my_tuple[::2]
(4, 6, 8, 10)
>>> my_tuple[::-1]
(10, 9, 8, 7, 6, 5, 4)
>>> my_tuple[4:1:-1]
(8, 7, 6)
Tuple Methods
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 30/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> my_tuple.count(6)
2
>>> my_tuple.index(7)
5
Tuple Assignment
In Python, we have a really cool feature called Tuple Assignment. With
this type of assignment, we can assign values to multiple variables on
the same line.
For example:
# Tuple Assignment
>>> a, b = 1, 2
>>> a
1
>>> b
2
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 31/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> a = 1
>>> b = 2
>>> a
2
>>> b
1
Dictionaries in Python
Now let's start diving into dictionaries. This built-in data structure lets
us create pairs of values where one value is associated with another
one.
The key is separated from the value with a colon : , like this:
Forum Donate
Strings: {"City 1": 456, "City 2": 577, "City 3": 678}
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 33/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Dictionary Length
Learn to code — free 3,000-hour curriculum
To get the number of key-value pairs, we use the len() function:
>>> len(my_dict)
4
<variable_with_dictionary>[<key>]
For example:
print(my_dict["a"])
1
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 34/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
<variable_with_dictionary>[<key>] = <value>
For example:
>>> my_dict["b"] = 6
<variable_with_dictionary>[<new_key>] = <value>
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 35/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> my_dict["e"] = 5
del <dictionary_variable>[<key>]
For example:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 36/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
{'a': 1, 'b': 2, 'd': 4}
Learn to code — free 3,000-hour curriculum
Dictionary Methods
These are some examples of the most commonly used dictionary
methods:
>>> my_dict.get("c")
3
>>> my_dict.items()
dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
>>> my_dict.keys()
dict_keys(['a', 'b', 'c', 'd'])
>>> my_dict.pop("d")
4
>>> my_dict.popitem()
('c', 3)
>>> my_dict
{'a': 1, 'b': 2}
>>> my_dict
{'a': 1, 'b': 2, 'f': 25}
>>> my_dict.values()
dict_values([1, 2, 25, 3, 4, 5])
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 37/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> my_dict.clear()
Learn to code — free 3,000-hour curriculum
>>> my_dict
{}
🔸 Python Operators
Great. Now you know the syntax of the basic data types and built-in
data structures in Python, so let's start diving into operators in
Python. They are essential to perform operations and to form
expressions.
Addition: +
>>> 5 + 6
11
>>> 0 + 6
6
Forum Donate
💡 Tip: The last two examples are curious, right? This operator
behaves differently based on the data type of the operands.
When they are strings, this operator concatenates the strings and
when they are Boolean values, it performs a particular operation.
Subtraction: -
>>> 5 - 6
-1
>>> 10 - 3
7
>>> 5 - 6
-1
>>> 4.5 - 7
-2.5
Multiplication: *
>>> 5 * 6
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 39/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> 5 * 6
30 Forum Donate
>>> 10 * 100
1000
>>> 4 * 0
0
>>> 4 * (-6)
-24
>>> "Hello" * 4
'HelloHelloHelloHello'
>>> "Hello" * 0
''
>>> "Hello" * -1
''
Exponentiation: **
>>> 6 ** 8
1679616
>>> 5 ** 2
25
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 40/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> 16 ** (1/2)
4.0
>>> 16 ** (0.5)
4.0
>>> 3 ** (-1)
0.3333333333333333
Division: /
>>> 25 / 5
5.0
>>> 3 / 6
0.5
>>> 0 / 5
0.0
>>> 1 / 2
0.5
>>> 6 / 7
0.8571428571428571
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 41/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> -3 / -4
0.75 Forum Donate
>>> -3 / 4
-0.75
💡 Tip: this operator returns a float as the result, even if the decimal
part is .0
>>> 5 / 0
Traceback (most recent call last):
File "<pyshell#109>", line 1, in <module>
5 / 0
ZeroDivisionError: division by zero
Integer Division: //
This operator returns an integer if the operands are integers. If they
are oats, the result will be a oat with .0 as the decimal part
because it truncates the decimal part.
>>> 5 // 6
0
>>> 8 // 2
4
>>> -4 // -5
0
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 42/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> -5 // 8
Forum Donate
-1
Learn to code — free 3,000-hour curriculum
>>> 0 // 5
0
Modulo: %
>>> 1 % 5
1
>>> 2 % 5
2
>>> 3 % 5
3
>>> 4 % 5
4
>>> 5 % 5
0
>>> 5 % 8
5
>>> 3 % 1
0
>>> 15 % 3
0
>>> 17 % 8
1
>>> 2568 % 4
0
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 43/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> 0 % 6
0
Comparison Operators
These operators are:
Equal to: ==
>>> 5 > 6
False
>>> 10 > 8
T
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 44/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
True
Forum Donate
>>> 8 > 8
Learn to code — free 3,000-hour curriculum
False
>>> 8 >= 5
True
>>> 8 >= 8
True
>>> 5 < 6
True
>>> 10 < 8
False
>>> 8 < 8
False
>>> 8 <= 5
False
>>> 8 <= 8
True
>>> 8 <= 10
True
>>> 56 == 56
True
>>> 56 == 78
False
>>> 34 != 59
True
>>> 67 != 67
False
Forum Donate
>>> a = 1
>>> b = 2
>>> a < b
True
>>> a <= b
True
>>> a > b
False
>>> a >= b
False
>>> a == b
False
>>> a != b
True
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 46/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
💡 Tip: notice that the comparison operator is == while the
Learn to code — free 3,000-hour curriculum
assignment operator is = . Their effect is different. == returns True
or False while = assigns a value to a variable.
a < b < c
>>> a = 1
>>> b = 2
>>> c = 3
Logical Operators
There are three logical operators in Python: and , or , and not . Each
one of these operators has its own truth table and they are essential
to work with conditionals.
The or operator:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 48/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
For example:
>>> a = 6
>>> b = 3
Assignment Operators
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 49/137
5/4/2021
g p
Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum
Assignment operators are used to assign a value to a variable. Donate
For example:
>>> x = 3
>>> x
3
>>> x += 15
>>> x
18
>>> x -= 2
>>> x
16
>>> x *= 2
>>> x
32
>>> x %= 5
>>> x
2
>>> x /= 1
>>> x
2.0
>>> x //= 2
>>> x
1.0
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 50/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> x **= 5
>>> x
Forum Donate
1.0
Learn to code — free 3,000-hour curriculum
Membership Operators
You can check if an element is in a sequence or not with the operators:
in and not in . The result will be either True or False .
For example:
>>> 5 in [1, 2, 3, 4, 5]
True
>>> 8 in [1, 2, 3, 4, 5]
False
>>> 5 in (1, 2, 3, 4, 5)
True
>>> 8 in (1, 2, 3, 4, 5)
False
5 t i [1 2 3 4 5]
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 51/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> 5 not in [1, 2, 3, 4, 5]
False Forum Donate
We typically use them with variables that store sequences, like in this
example:
🔹 Conditionals in Python
Now let's see how we can write conditionals to make certain parts of
our code run (or not) based on whether a condition is True or False .
if statements in Python
This is the syntax of a basic if statement:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 52/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
if <condition>:
<code> Learn to code — free 3,000-hour curriculum
If the condition is True , the code will run. Else, if it's False , the code
will not run.
💡 Tip: there is a colon ( : ) at the end of the rst line and the code is
indented. This is essential in Python to make the code belong to the
conditional.
False Condition
x = 5
if x > 9:
print("Hello, World!")
True Condition
Here we have another example. Now the condition is True :
color = "Blue"
if color == "Blue":
print("This is my favorite color")
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 53/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
print( This is my favorite color )
Forum Donate
x = 5
if x > 9:
print("Hello!")
print("End")
End
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 54/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
x = 15 Forum Donate
print("End")
Hello!
End
Examples of Conditionals
This is another example of a conditional:
favorite_season = "Summer"
if favorite_season == "Summer":
print("That is my favorite season too!")
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 55/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
favorite_season = "Winter"
Learn to code — free 3,000-hour curriculum
if favorite_season == "Summer":
print("That is my favorite season too!")
if <condition>:
<code>
else:
<code>
💡 Tip: notice that the two code blocks are indented ( if and else ).
This is essential for Python to be able to differentiate between the
code that belongs to the main program and the code that belongs to
the conditional.
True Condition
x = 15
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 56/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
print("End")
Hello!
End
When the condition of the if clause is True , this clause runs. The el
se clause doesn't run.
False Condition
Now the else clause runs because the condition is False .
x = 5
if x > 9:
print("Hello!")
else:
print("Bye!")
print("End")
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 57/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Bye!
Forum Donate
End
Learn to code — free 3,000-hour curriculum
x = 5
if x < 9:
print("Hello!")
elif x < 15:
print("It's great to see you")
else:
print("Bye!")
print("End")
We have two conditions x < 9 and x < 15 . Only the code block from
the rst condition that is True from top to bottom will be executed.
Hello!
End
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 58/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Because the rst condition is True : x < 9 .
Learn to code — free 3,000-hour curriculum
In this example, the rst condition x < 9 is False but the second
condition x < 15 is True , so the code that belongs to this clause will
run.
x = 13
if x < 9:
print("Hello!")
elif x < 15:
print("It's great to see you")
else:
print("Bye!")
print("End")
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 59/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
x = 25
Learn to code — free 3,000-hour curriculum
if x < 9:
print("Hello!")
elif x < 15:
print("End")
Bye!
End
if favorite_season == "Winter":
print("That is my favorite season too")
elif favorite_season == "Summer":
print("Summer is amazing")
elif favorite_season == "Spring":
print("I love spring")
else:
print("Fall is my mom's favorite season")
Each condition will be checked and only the code block of the rst
diti th t l t t T ill If f th T
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 60/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
condition that evaluates to True will run. If none of them are True ,
Forum Donate
the else clause will run.
Learn to code — free 3,000-hour curriculum
💡 Tip: Each integer is assigned to the loop variable one at a time per
iteration.
Forum Donate
it's 0 .
step : the value that will be added to each element to get the
next element in the sequence. By default, it's 1 .
for i in range(5):
print(i)
Output:
0
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 62/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
1
Forum Donate
2
3 Learn to code — free 3,000-hour curriculum
4
Output:
0
2
4
6
8
10
12
14
16
18
20
22
24
26
28
>>> f i (8)
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 63/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> for num in range(8):
print("Hello" * num) Forum Donate
Output:
Hello
HelloHello
HelloHelloHello
HelloHelloHelloHello
HelloHelloHelloHelloHello
HelloHelloHelloHelloHelloHello
HelloHelloHelloHelloHelloHelloHello
We can also use for loops with built-in data structures such as lists:
Output:
a
b
c
d
Forum Donate
These are some examples with two parameters:
Learn to code — free 3,000-hour curriculum
print(i)
Output:
2
3
4
5
6
7
8
9
Code:
Output:
PythonPython
PythonPythonPython
PythonPythonPythonPython
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 65/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Code: Learn to code — free 3,000-hour curriculum
Output:
c
d
Code:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 66/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Output:
Learn to code — free 3,000-hour curriculum
3
5
7
9
11
13
15
Code:
Output:
10
9
8
7
6
Code:
Output:
f
e
d
H
e
l
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 68/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
l Forum Donate
o
, Learn to code — free 3,000-hour curriculum
W
o
r
l
d
!
h
e
l
l
o
H
E
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 69/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
L Forum Donate
L
O Learn to code — free 3,000-hour curriculum
2
3
4
5
Code:
Output:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 70/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
We just write the name of the variable that stores the dictionary as
the iterable.
For example:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 71/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
a
b Learn to code — free 3,000-hour curriculum
c
💡 Tip: you can assign any valid name to the loop variable.
For example:
1
2
3
a 1
b 2
c 3
('a', 1)
('b', 2)
('c', 3)
Odd: 1
Even: 2
break
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 74/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> my_list = [1, 2, 3, 4, 5]
Learn to code — free 3,000-hour curriculum
>>> for elem in my_list:
if elem % 2 == 0:
print("continue")
continue
print("Odd:", elem)
Odd: 1
continue
Odd: 3
continue
Odd: 5
For example:
1 5
2 6
3 7
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 75/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
4 8
Forum Donate
For example:
0 5
1 6
2 7
3 8
0 H
1 e
2 l
3 l
4 o
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 76/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
If you start the Learn
counter from—0free
to code , you can use the
3,000-hour index and the current
curriculum
value in the same iteration to modify the sequence:
>>> my_list
[15, 18, 21, 24]
You can start the counter from a different number by passing a second
argument to enumerate() :
2 H
3 e
4 l
5 l
6 o
💡 Ti if i f d h l d ' d if i
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 77/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
💡 Tip: if break is found, the else clause doesn't run and if break is
Forum Donate
not found, the else clause runs.
Learn to code — free 3,000-hour curriculum
my_list = [1, 2, 3, 4, 5]
Not Found
However, if the break statement runs, the else clause doesn't run.
We can see this in the example below:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 78/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Found
while <condition>:
<code>
💡 Tip: in while loops, you must update the variables that are part of
the condition to make sure that the condition will eventually become
False .
For example:
>>> x = 6
x += 1
Forum Donate
>>> x = 4
HelloHelloHelloHello
HelloHelloHello
HelloHello
Hello
>>> num = 5
*****
***
*
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 80/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum
Break and Continue Donate
continue stops the current iteration and starts the next one.
For example:
>>> x = 5
5
Even: 6
>>> x = 5
Odd: 5
Odd: 7
Odd: 9
Odd: 11
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 81/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Odd: 11
Odd: 13 Forum Donate
In the example below, the break statement is not found because none
of the numbers are even before the condition becomes False , so the
else clause runs.
x = 5
5
7
9
11
13
All numbers were odd
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 82/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
But in this version of the example, the break statement is found and
the else clauseLearn to code
doesn't run:— free 3,000-hour curriculum
x = 5
print(x)
x += 1 # Now we are incrementing the value by 1
else:
print("All numbers were odd")
5
Even number found
This usually happens when the variables in the condition are not
updated properly during the execution of the loop.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 83/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> x = 5
5
5
5
5
5
5
5
5
5
.
.
.
# The output continues indefinitely
💡 Tip: to stop this process, type CTRL + C . You should see a Keyboard
Interrupt message.
💡 Tip: the inner loop runs for each iteration of the outer loop.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 84/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
0 0
0 1
1 0
1 1
2 0
2 1
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 85/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> num_rows = 5
*****
****
***
**
*
>>> i = 5
💡 Tip: we can also have for loops within while loops and while loops
within for loops.
🔹 Functions in Python
In Python, we can de ne functions to make our code reusable, more
readable, and organized. This is the basic syntax of a Python function:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 87/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> print_pattern()
****
****
****
****
💡 Tip: You have to write an empty pair of parentheses after the name
of the function to call it.
def welcome_student(name):
print(f"Hi, {name}! Welcome to class.")
When we call the function, we just need to pass one value as argument
and that value will be replaced where we use the parameter in the
function de nition:
def print_pattern(num_rows):
for i in range(num_rows):
for num_cols in range(num_rows-i):
print("*", end="")
print()
You can see the different outputs for different values of num_rows :
>>> print_pattern(3)
***
**
*
>>> print_pattern(5)
*****
****
***
**
*
>>> print_pattern(8)
********
*******
******
*****
****
***
**
*
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 89/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
FunctionsLearn
with Two
to code or3,000-hour
— free More curriculum
Parameters in
Python
To de ne two or more parameters, we just separate them with a
comma:
>>> print_sum(4, 5)
9
>>> print_sum(8, 9)
17
>>> print_sum(0, 0)
0
>>> print_sum(3, 5)
8
We can adapt the function that we just saw with one parameter to
work with two parameters and print a pattern with a customized
character:
print()
Forum Donate
You can see the output with the customized character is that we call
the function passing the two arguments:
Forum Donate
We will often need to return a value from a function. We can do this
Learn to code — free 3,000-hour curriculum
with the return statement in Python. We just need to write this in
the function de nition:
return <value_to_return>
💡 Tip: the function stops immediately when return is found and the
value is returned.
Now we can call the function and assign the result to a variable
because the result is returned by the function:
In this example, the function returns the rst even element found in
the sequence:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 92/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
💡 Tip: The Style Guide for Python Code mentions that we shouldn't
"use spaces around the = sign when used to indicate a keyword
argument."
If we call the function without this argument, you can see the output:
>>> print_product(4)
20
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 94/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> print_product(3, 4)
12 Learn to code — free 3,000-hour curriculum
Now we have the option to use the default value or customize it:
>>> print_pattern(5)
*****
****
***
**
*
Forum Donate
🔸 Recursion in Python
A recursive function is a function that calls itself. These functions have
a base case that stops the recursive process and a recursive case that
continues the recursive process by making another recursive call.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
def fibonacci(n):
if n == 0 or n == 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
>>> 5 / 0
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
5 / 0
ZeroDivisionError: division by zero
>>> 7 // 0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
7 // 0
ZeroDivisionError: integer division or modulo by zero
>>> 8 % 0
Traceback (most recent call last):
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 97/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module> Forum Donate
8 % 0
Learninteger
ZeroDivisionError: to code division
— free 3,000-hour
or modulo curriculum
by zero
>>> my_list[15]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
my_list[15]
IndexError: list index out of range
>>> my_dict["d"]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
my_dict["d"]
KeyError: 'd'
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 98/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
>>> factorial(5)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
factorial(5)
File "<pyshell#5>", line 5, in factorial
return n * factorial(n)
File "<pyshell#5>", line 5, in factorial
return n * factorial(n)
File "<pyshell#5>", line 5, in factorial
return n * factorial(n)
[Previous line repeated 1021 more times]
File "<pyshell#5>", line 2, in factorial
if n == 0 or n == 1:
RecursionError: maximum recursion depth exceeded in comparison
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 99/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
try:
<code_that_may_raise_an_exception>
except:
<code_to_handle_the_exception_if_it_occurs>
try:
my_list = [1, 2, 3, 4]
print(my_list[index])
except:
print("Please enter a valid index.")
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 100/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Please enter a valid index.
Learn to code — free 3,000-hour curriculum
Because the except clause runs. However, if the value is valid, the
code in try will run as expected.
a = int(input("Enter a: "))
b = int(input("Enter b: "))
try:
division = a / b
print(division)
except:
print("Please enter valid values.")
Enter a: 5
Enter b: 0
Forum Donate
For example:
try:
my_list = [1, 2, 3, 4]
print(my_list[index])
except IndexError: # specify the type
print("Please enter a valid index.")
a = int(input("Enter a: "))
b = int(input("Enter b: "))
try:
division = a / b
print(division)
except ZeroDivisionError: # specify the type
print("Please enter valid values.")
Forum Donate
We only need to add as <name> , like this:
Learn to code — free 3,000-hour curriculum
try:
<code_that_may_raise_an_exception>
except <exception_type> as <name>:
<code_to_handle_an_exception_if_it_occurs>
For example:
try:
my_list = [1, 2, 3, 4]
print(my_list[index])
except IndexError as e:
print("Exception raised:", e)
a = int(input("Enter a: "))
b = int(input("Enter b: "))
try:
di i i / b
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 103/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
division = a / b
print(division) Forum Donate
except ZeroDivisionError as err:
Learn
print("Please to code
enter — free
valid 3,000-hour
values.", err) curriculum
try:
<code_that_may_raise_an_exception>
except:
<code_to_handle_an_exception_if_it_occurs>
else:
<code_that_only_runs_if_no_exception_in_try>
For example:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
try:
division = a / b
print(division)
except ZeroDivisionError as err:
print("Please enter valid values " err)
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 104/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
print( Please enter valid values. , err)
else: Forum Donate
print("Both values were valid.")
Learn to code — free 3,000-hour curriculum
But if both values are valid, for example 5 and 4 for a and b
respectively, the else clause runs after try is completed and we see:
1.25
Both values were valid.
For example:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
try:
division = a / b
print(division)
except ZeroDivisionError as err:
print("Please enter valid values.", err)
else:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 105/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
else:
print("Both values were valid.") Forum Donate
finally:
Learn to code — free 3,000-hour curriculum
print("Finally!")
If both values are valid, the output is the result of the division and:
💡 Tip: this clause can be used, for example, to close les even if the
code throws an exception.
🔸 Object-Oriented Programming
in Python
In Object-Oriented Programming (OOP), we de ne classes that act as
blueprints to create objects in Python with attributes and methods
(functionality associated with the objects).
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 106/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
class <className>:
Learn to code — free 3,000-hour curriculum
<class_attribute_name> = <value>
💡 Tip: self refers to an instance of the class (an object created with
the class blueprint).
As you can see, a class can have many different elements so let's
analyze them in detail:
Class Header
The rst line of the class de nition has the class keyword and the
name of the class:
class Dog:
class House:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 107/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
💡 Tip: If the class inherits attributes and methods from another class,
we will see the name of the class within parentheses:
class Poodle(Dog):
class Truck(Vehicle):
class Mom(FamilyMember):
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 108/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
class Dog:
💡 Tip: notice the double leading and trailing underscore in the name
__init__ .
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 109/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
class Circle:
def __init__(self):
self.radius = 1
To create an instance:
💡 Tip: self is like a parameter that acts "behind the scenes", so even
if you see it in the method de nition, you shouldn't consider it when
you pass the arguments.
Default Arguments
We can also assign default values for the attributes and give the
option to the user if they would like to customize the value.
This is an example:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 110/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
class Circle:
Learn to code — free 3,000-hour curriculum
def __init__(self, radius=1):
self.radius = radius
Now we can create a Circle instance with the default value for the
radius by omitting the value or customize it by passing a value:
# Default value
# Customized value
>>> my_circle2 = Circle(5)
<object_variable>.<attribute>
For example:
# Class definition
>>> class Dog:
# Create instance
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 111/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
# Create instance
>>> my_dog = Dog("Nora", 10) Forum Donate
>>> my_dog.age
10
<object_variable>.<attribute> = <new_value>
For example:
>>> my_dog.name
'Nora'
>>> my_dog.name
'Norita'
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 112/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
del <object_variable>.<attribute>
For example:
>>> my_dog.name
'Nora'
>>> my_dog.name
Traceback (most recent call last):
File "<pyshell#77>", line 1, in <module>
my_dog.name
AttributeError: 'Dog' object has no attribute 'name'
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 113/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> my_dog.name
'Nora'
>>> my_dog
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
my_dog
NameError: name 'my_dog' is not defined
For example:
class Dog:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 115/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
class Dog:
<class_name>.<attribute>
For example:
kingdom = "Animalia"
>>> Dog.kingdom
'Animalia'
💡 Tip: You can use this syntax within the class as well.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 116/137
💡 Tip: You can use this syntax within the class as well.
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
<class_name>.<attribute> = <value>
For example:
kingdom = "Animalia"
>>> Dog.kingdom
'Animalia'
>>> Dog.kingdom
'New Kingdom'
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 117/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
kingdom = "Animalia"
Forum Donate
def __init__(self, name, age):
Learn to code — free 3,000-hour curriculum
self.name = name
self.age = age
>>> Dog.kingdom
'Animalia'
>>> Dog.kingdom
Traceback (most recent call last):
File "<pyshell#88>", line 1, in <module>
Dog.kingdom
AttributeError: type object 'Dog' has no attribute 'kingdom'
💡 Tip: Instance methods can work with the attributes of the instance
that is calling the method if we write self.<attribute> in the method
de nition.
This is the basic syntax of a method in a class. They are usually located
below __init__ :
class <ClassName>:
# Class attributes
# __init__
class Dog:
def bark(self):
print(f"woof-woof. I'm {self.name}")
<object_variable>.<method>(<arguments>)
For example:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 119/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
Here we have aLearn
Player class—with
to code an increment_speed
free 3,000-hour curriculum method with
one parameter:
class Player:
# Create instance
>>> my_player = Player("Nora")
P i G dS i P h
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 120/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
@property
def <property_name>(self):
return self.<attribute>
@<property_name>.setter
def <property_name>(self, <param>):
self.<attribute> = <param>
@<property_name>.deleter
def <property_name>(self):
del self.<attribute>
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 121/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
💡 Tip: you can write any code that you need in these methods to get,
Learn to code — free 3,000-hour curriculum
set, and delete an attribute. It is recommended to keep them as simple
as possible.
This is an example:
class Dog:
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
self._name = new_name
@name.deleter
def name(self):
del self._name
If we add descriptive print statements, we can see that they are called
when we perform their operation:
@property
def name(self):
print("Calling getter")
return self._name
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 122/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
@name.setter
Forum Donate
def name(self, new_name):
Learn to code — free 3,000-hour curriculum
print("Calling setter")
self._name = new_name
@name.deleter
def name(self):
print("Calling deleter")
del self._name
>>> my_dog.name
Calling getter
'Nora'
>>> my_dog.name
Calling getter
'Norita'
Forum Donate
To read a le, we use this syntax:
Learn to code — free 3,000-hour curriculum
We can also specify that we want to open the le in read mode with an
"r" :
But this is already the default mode to open a le, so we can omit it
like in the rst example.
This is an example:
or...
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 124/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
💡 Tip: that's right! We can iterate over the lines of the Forum
le using a forDonate
loop. The le path cantobe
Learn relative
code — freeto the Python
3,000-hour script that we are
curriculum
running or it can be an absolute path.
For example:
When you run the program, a new le will be created if it doesn't exist
already in the path that we speci ed.
Forum Donate
For example:
This small change will keep the existing content of the le and it will
add the new content to the end.
If we run the program again, these strings will be added to the end of
the le:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 126/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
import os
if os.path.exists("<file_path>"):
os.remove("<file_path>")
else:
<code>
For example:
import os
if os.path.exists("famous_quotes.txt"):
os.remove("famous_quotes.txt")
else:
print("This file doesn't exist")
You might have noticed the rst line that says import os . This is an
import statement. Let's see why they are helpful and how you can
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 127/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
First Alternative:
import <module_name>
For example:
import math
If we use this import statement, we will need to add the name of the
module before the name of the function or element that we are
referring to in our code:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 128/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Second Alternative:
For example:
import math as m
In our code, we can use the new name that we assigned instead of the
original name of the module:
Third Alternative:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 129/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
For example: Learn to code — free 3,000-hour curriculum
With this import statement, we can call the function directly without
speci ying the name of the module:
>>> sqrt(25)
5.0
Fourth Alternative:
For example:
With this import statement, we can assign a new name to the element
imported from the module:
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 130/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Fifth Alternative:
This statement imports all the elements of the module and you can
refer to them directly by their name without specifying the name of
the module.
For example:
>>> sqrt(25)
5.0
>>> factorial(5)
120
>>> floor(4.6)
4
>>> gcd(5, 8)
1
💡 Tip: this type of import statement can make it more dif cult for us
to know which elements belong to which module, particularly when
we are importing elements from multiple modules.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 131/137
5/4/2021
p g p
Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
According to the Style Guide for Python Code:
Learn to code — free 3,000-hour curriculum
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 132/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
💡 Tip: you should only use them when they do not make your code
more dif cult to read and understand.
Forum Donate
List comprehensions generate the entire sequence at once and
Learn to code — free 3,000-hour curriculum
store it in memory.
We can check this with the sys module. In the example below, you
can see that their size in memory is very different:
We can use generator expressions to iterate in a for loop and get the
elements one at a time. But if we need to store the elements in a list,
then we should use list comprehension.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 134/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Forum Donate
>>> approved_students
{'Nora': 78, 'Gino': 100, 'Lulu': 67}
I really hope you liked this article and found it helpful. Now you know
how to write and work with the most important elements of Python.
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 135/137
5/4/2021 Python Code Examples – Sample Script Coding Tutorial for Beginners
Estefania Cassingena
Computer Science Navone
and Mathematics Forum
Student | Udemy Instructor | Author atDonate
freeCodeCamp News
Learn to code — free 3,000-hour curriculum
If you read this far, tweet to the author to show them you care.
Tweet a thanks
Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public. We also have
thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives and help pay for servers,
services, and staff.
Trending Guides
Our Nonpro t
About Alumni Network Open Source Shop Support Sponsors Academic Honesty
https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-how-to-work-with-files-in-python 137/137