Python Code Samples - Sample Script Coding Tutorial for Beginners (2023)

Table of Contents
What we will address: 🔹 Variable definitions in Python 🔸 Hello world! Python program 🔹 Built-in data types and data structures in Python Python Numeric Data Types: Integer, Float, and Complex Strings em Python Boolean Values ​​in Python Listen in Python Tupel em Python Dictionaries in Python 🔸 Python Operators Arithmetic Operators in Python 🔹 Conditions in Python What ifPython Instructions on the other handPython Instructions if/elif/elsePython Instructions 🔸 For loops em Python DieReach()function in python How to iterate over iterables in Python Iterate over dictionary keys, values, and key-value pairs Stop and continue in Python The zip() function in Python The enumerate() function in Python 🔹 While loops in Python 🔸 Nested Loops in Python Nested For Loops in Python Nested while loops in Python 🔹 Functions in Python Function without parameters in Python Function with one parameter in Python Functions with two or more parameters in Python How to return a value in Python A standard argument in Python 🔸 Recursion in Python 🔹 Exception Handling in Python Common Exceptions in Python Try/Besidesem Python How to catch a specific exception type in Python How to assign a name to exception object in Python Try/Besides/andersem Python Try/Besides/anders/Finallyem Python 🔸 Object Oriented Programming in Python class header __inside side__and instance attributes How to create an instance indisputably standard How to get an instance attribute How to update an instance attribute How to remove an instance attribute How to delete an instance Public vs non-public attributes in Python Python class attributes How to get a class attribute How to update a class attribute How to delete a class attribute How to define methods Properties, Getters, and Setters in Python 🔹 How to work with files in Python How to read files in Python How to write to a file in Python How to append to a file in Python How to Delete a File in Python 🔸 Import statements to Python First alternative: Second alternative: Third alternative: Fourth alternative: Fifth alternative: 🔹 List and dictionary comprehension in Python List comprehension in Python List comprehensions versus generator expressions in Python Dictionary understanding in Python
/ #Python
Python Code Samples - Sample Script Coding Tutorial for Beginners (1)
Estefânia Cassingena Navone
Python Code Samples - Sample Script Coding Tutorial for Beginners (2)

Hey! Warm welcome. If you're learning Python, this article is for you. You'll find a detailed description of Python syntax and lots of code examples to guide you on your coding journey.

What we will address:

  • Variable definitions in Python
  • Hello World! Python program
  • Python built-in data types and data structures
  • Python Operators
  • Conditions in Python
  • For loops em Python
  • While loops in Python
  • Nested Loops in Python
  • Functions in Python
  • Recursion in Python
  • Exception Handling in Python
  • Object Oriented Programming in Python
  • How to work with files in Python
  • Import statements to Python
  • List and Dictionary Comprehension in Python
  • and more...

Are you ready? Let's start! 🔅

💡Principal:In this article I will use<>to indicate that this part of the syntax is replaced by the element described in the text. For example,<guerra>means this will be replaced by a variable when writing code.

🔹 Variable definitions in Python

The most fundamental building block of any programming language is the concept of a variable, a name, and a place in memory that we reserve for a value.

In Python, we use this syntax to create a variable and assign a value to that variable:

<var_name> = <valor>

For example:

Alter = 56
name = "Nora"
color = "blue"
Grades = [67, 100, 87, 56]

If a variable name consists of more than one word, then thePython code style guiderecommends separating words with an underscore "to the extent necessary to improve readability".

For example:

my_list = [1, 2, 3, 4, 5]

💡Principal:The Style Guide for Python Code (PEP 8) has great suggestions to follow for writing clean Python code.

🔸 Hello world! Python program

Before we dive into the data types and data structures you can use in Python, let's look at how to write your first Python program.

All you have to do is callpressure()work and write"Hello World!"on supports:

print("Hello Welt!")

After running the program, you will see this message:

"Hello World!"

💡Principal:write in"Hello World!"The program is a tradition in the developer community. Most developers start programming by writing this program.

Great. You've just written your first Python program. Now let's start learning about data types and the built-in data structures you can use in Python.

🔹 Built-in data types and data structures in Python

We have several basic data types and built-in data structures that we can work with in our programs. Each has its own specific uses. Let's see them in detail.

Python Numeric Data Types: Integer, Float, and Complex

These are the numeric types you can work with in Python:

whole numbers

Integers are numbers without decimal places. With you can check if a number is an integertill()Occupation. If the output is<class 'int'>, then the number is an integer.

For example:

>>> type(1)<class 'int'>>>> type(15)<class 'int'>>>> type(0)<class 'int'>>>> type(-46)<class ' int'>

nothing

Floats are numbers with decimals. You can visually recognize them by locating the decimal point. if we calltill()To check the data type of these values, we see this as the output:

<class 'float'>

Here we have some examples:

>>> 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'>

Complex

Complex numbers have a real part and an imaginary part, which is denoted byj. You can create complex numbers in Python withComplex(). The first argument is the real part and the second argument is the imaginary part.

These are some examples:

>>> complex(4, 5)(4+5j)>>> complex(6, 8)(6+8j)>>> complex(3.4, 3.4)(3.4+3.4j)>>> complex(0, 0)0j>>> complex(5)(5+0j)>>> complex(0, 4)4j

Strings em Python

Incredibly useful strings in Python. They contain a string of characters and are typically used to represent text in code.

For example:

"Hello World!"
'Hello World!'

We can use the two single quotes''or double quotes""to define a string. Both are valid and equivalent, but you must choose one and use it consistently throughout the program.

💡 Tip:Yes! You used a string when you wrote this"Hello World!"Program. In Python, whenever you see a value enclosed in single or double quotes, it's a string.

Strings can contain any character that we can type on our keyboard, including numbers, symbols and other special characters.

For example:

"45678"
"meine_email@email.com"
"#EuamoPython"

💡 Tip:Spaces are also counted as characters in a string.

Quotes in strings

If we define a string with double quotes"", so we can use single quotes inside the string. For example:

"I am 20 years old"

If we define a string with single quotes'', so we can use double quotes inside the string. For example:

"My favorite book is Sense and Sensibility"

string indexing

We can use indexes to access characters in a string in our Python program. An index is an integer that represents a specific position in the string. They are associated with the character at that position.

This is a string graph"Hi":

String: H e l l o Index: 0 1 2 3 4

💡 Tip:The indices start at0and are incremented by1for each character to the right.

For example:

>>> my_string = "Hello">>> my_string[0]'H'>>> my_string[1]'e'>>> my_string[2]'l'>>> my_string[3]'l'>> > minha_string[4]'o'

We can also use negative subscripts to access these characters:

>>> my_string = "Hallo">>> my_string[-1]'o'>>> my_string[-2]'l'>>> my_string[-3]'l'>>> my_string[-4]' e'>>> minha_string[-5]'H'

💡 Tip:we often use-1to access the last character of a string.

rope cutting

We may also need to get a chunk of a string or a subset of its characters. We can do this with string cutting.

This is the general syntax:

<string_variable>[start:stop:step]

Startis the index of the first character included in the slice. By default it is0.

  • Pareis the index of the last character of the slice (this character will beNotbe included). By default it is the last character of the string (if we omit this value, the last character will also be included).
  • Stageis how much we will add to the current index to arrive at the next index.

We can provide two parameters to use the default valueStage, which is1. This includes all characters in between.StartePare(not included):

<string_variable>[start:stop]

For example:

>>> freecodecamp = "freeCodeCamp">>> 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 ]'Lager'

💡 Tip:Note that if the value of a parameter exceeds the valid range of indices, the slice will still be displayed. This is how the Python developers implemented this string splitting feature.

if we adjust themStage, we "jump" from one index to the next according to that value.

For example:

>>> freecodecamp = "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'

We can also use aNegativeStep from right to left:

>>> freecodecamp = "freeCodeCamp">>> freecodecamp[10:2:-1]'maCedoCe'>>> freecodecamp[11:4:-2]'paeo'>>> freecodecamp[5:2:-4] 'Ö'

And we can omit a parameter to use its default value. We just need to add the appropriate colon (:) if we omitStart,Pare, or both:

>>> freecodecamp = "freeCodeCamp"# default start and step>>> freecodecamp[:8]'freeCode'# default end and step>>> freecodecamp[4:]'CodeCamp'# default start>>> freecodecamp[:8 :2] 'feCd'# default stop>>> freecodecamp[4::3]'Cem'# default start and stop>>> freecodecamp[::-2]'paeoer'# default start and stop>>> freecodecamp[ ::-1]'pmaCedoCeerf'

💡 Tip:The last example is one of the most common ways to reverse a string.

f-Saiten

In Python 3.6 and newer, we can use a string type called f-string, which helps us format our strings much easier.

To define an f-string, we simply add afbefore single or double quotes. Then we put the variables or expressions in braces inside the string{}. This will substitute its value into the string when we run the program.

For example:

first_name = "Nora"favorite_language = "Python"print(f"Hello, I'm {first_name}. I'm learning {favorite_language}.")

The output is:

Hello, I'm Nora. I'm learning Python.

Here is an example where we calculate the value of an expression and replace the result in the string:

value = 5print(f"{value} multiplied by 2 gives: {value * 2}")

Values ​​are substituted in the output:

5 multiplied by 2 is: 10

We can also call methods inside curly braces and the returned value will be substituted into the string when we run the program:

freecodecamp = "FREECODECAMP"print(f"{freecodecamp.lower()}")

The output is:

freecodecamp

String methods

Strings have methods that represent common functions implemented by Python developers, so we can use them directly in our programs. They are very useful for performing general operations.

This is the general syntax for calling a string method:

<string_variable>.<method_name>(<argumento>)

For example:

>>> freecodecamp = "freeCodeCamp">>> freecodecamp.capitalize()'Freecodecamp'>>> freecodecamp.count("C")2>>> freecodecamp.find("e")2>>> 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.isttitle()False>>> freecodecamp. isupper()False>>> freecodecamp.lower()'freecodecamp'>>> freecodecamp.lstrip("f")'reeCodeCamp'>>> freecodecamp.rstrip("p")'freeCodeCam'>>> freecodecamp.replace( "e", "a")'fraaCodaCamp'>>> freecodecamp.split("C")['free', 'ode', 'amp']>>> freecodecamp.swapcase()'FREEcODEcAMP'>>> freecodecamp .title()'Freecodecamp'>>> freecodecamp.upper()'FREECODECAMP'

To learn more about Python methods, I recommend readingThis articlefrom the Python documentation.

💡Principal:All String methods return copies of the String method. You don't change the string because strings are immutable in Python.

Boolean Values ​​in Python

are boolean valuesTRUTHeINCORRECTin 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'>

If we write them in lowercase, we get an error message:

>>> type(true)Traceback (last call): File "<pyshell#92>", line 1, in <module> type(true)NameError: name 'true' is not defined>>> type(false ) Traceback (last last call): File "<pyshell#93>", line 1, in <module> type(false)NameError: name 'false' is not defined

Listen in Python

Now that we've covered the basic data types in Python, let's start covering the internal data structures. First we have lists.

To define a list, we use square brackets[]where the elements are separated by a comma.

💡 Tip:It is recommended to add a space after each comma to make the code more readable.

For example, here are sample lists:

[1, 2, 3, 4, 5]
["A B C D"]
[3.4, 2.4, 2.6, 3.5]

Lists can contain values ​​of different data types, so this would be a valid list in Python:

[1, "Emily", 3.4]

We can also assign a list to a variable:

my_list = [1, 2, 3, 4, 5]
Letters = ["a", "b", "c", "d"

nested lists

Lists can contain values ​​of any data type, including other lists. These internal lists are callednested lists.

[[1, 2, 3], [4, 5, 6]]

In this example[1, 2, 3]e[4, 5, 6]are nested lists.

Here are other valid examples:

[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
[1, [2, 3, 4], [5, 6, 7], 3,4]

We can access the nested lists by their corresponding index:

>>> my_list = [[1, 2, 3], [4, 5, 6]]>>> my_list[0][1, 2, 3]>>> my_list[1][4, 5, 6]

For example, nested lists can be used to represent the structure of a simple 2D game board, where each number can represent a different element or piece:

# Example board with: # 0 = empty square # 1 = coin # 2 = enemy # 3 = gate board = [[0, 0, 1], [0, 2, 0], [1, 0, 3] ]

list length

We can use thoselen()Function to get the length of a list (the number of elements it contains).

For example:

>>> my_list = [1, 2, 3, 4]>>> len(my_list)4

Update a value in a list

We can update the value at a specific index using this syntax:

<Listenvariable>[<Index>] = <Wert>

For example:

>>> letters = ["a", "b", "c", "d"]>>> letters[0] = "z">>> letters['z', 'b', 'c', 'd']

Add value to a list

We can use this to add a new value to the end of a list.add()Method.

For example:

>>> my_list = [1, 2, 3, 4] >>> my_list.append(5) >>> my_list[1, 2, 3, 4, 5]

Remove a value from a list

We can use this to remove a value from a list.Extinguish()Method.

For example:

>>> my_list = [1, 2, 3, 4] >>> my_list.remove(3) >>> my_list[1, 2, 4]

💡Principal:This only removes the first occurrence of the element. For example, if we try to remove the number 3 from a list of two numbers 3, the second number is not removed:

>>> my_list = [1, 2, 3, 3, 4]>>> my_list.remove(3) >>> my_list[1, 2, 3, 4]

list indexing

We can index a list the same way we index strings, with indices starting at0:

>>> letters = ["a", "b", "c", "d"]>>> letters[0]'a'>>> letters[1]'b'>>> letters[2]' c'>>> letters[3]'d'

listening slicing

We can also get part of a list using the same syntax we use with strings, and we can omit the parameters to use their default values. Instead of adding characters to the slice, let's add the items to the list now.

<list variable>[start:stop:step]

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:

>>> my_list = [1, 2, 3, 3, 4]>>> my_list.append(5)>>> my_list[1, 2, 3, 3, 4, 5]>>> my_list.extend([ 6, 7, 8])>>> my_list[1, 2, 3, 3, 4, 5, 6, 7, 8]>>> my_list.insert(2, 15)>>> my_list[1, 2, 15, 3, 3, 4, 5, 6, 7, 8, 2, 2]>>> 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[]

To learn more about list methods, I recommend readingThis articlefrom the Python documentation.

Tupel em Python

To define a tuple in Python, we use parentheses()and separate items with a comma. It is recommended to add a space after each comma to make the code more readable.

(1, 2, 3, 4, 5)
("A B C D")
(3.4, 2.4, 2.6, 3.5)

We can assign tuples to variables:

my_tuple = (1, 2, 3, 4, 5)

tuple indexing

We can access each element of a tuple with its corresponding index:

>>> my_tuple = (1, 2, 3, 4)>>> my_tuple[0]1>>> my_tuple[1]2>>> my_tuple[2]3>>> my_tuple[3]4

We can also use negative indices:

>>> my_tuple = (1, 2, 3, 4)>>> my_tuple[-1]4>>> my_tuple[-2]3>>> my_tuple[-3]2>>> my_tuple[-4]1

tuple length

To get the length of a tuple, we use thelen()Function, passing the tuple as an argument:

>>> my_tuple = (1, 2, 3, 4) >>> len(my_tuple)4

nested tuples

Tuples can contain values ​​of any data type, even lists and other tuples. These inner tuples are callednested tuples.

([1, 2, 3], (4, 5, 6))

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 = ([1, 2, 3], (4, 5, 6))>>> my_tuple[0][1, 2, 3]>>> my_tuple[1](4, 5, 6)

Tupel-Slicing

We can split a tuple just like we split lists and strings. The same principles and rules apply.

This is the general syntax:

<tuple_variable>[start:stop:step]

For example:

>>> my_tuple = (4, 5, 6, 7, 8, 9, 10)>>> 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

There are two built-in tuple methods in Python:

>>> my_tuple = (4, 4, 5, 6, 6, 7, 8, 9, 10)>>> my_tuple.count(6)2 >>> my_tuple.index(7)5

💡Principal:Tuples are immutable. They cannot be modified, so we cannot add, update, or remove tuple elements. If that's necessary, we need to create a new copy of the tuple.

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.

Values ​​are assigned to the corresponding variables in the order they appear. for example ina, b = 1, 2the value that1is assigned to the variableanand the value2is assigned to the variableb.

For example:

# Tupelzuweisung >>> a, b = 1, 2 >>> a1 >>> b2

💡 Tip:Tuple assignment is often used to swap the values ​​of two variables:

>>> a = 1>>> b = 2# Swap the values ​​>>> a, b = b, a>>> a2>>> b1

Dictionaries in Python

Now let's start diving into dictionaries. With this data structure built in, we can create value pairs where one value is linked to another.

To define a dictionary in Python, we use square brackets{}where key-value pairs are separated by commas.

The key is separated from the value by a colon:, such that:

{"a": 1, "b": 2, "c"; 3}

You can assign the dictionary to a variable:

meu_dict = {"a": 1, "b": 2, "c"; 3}

Keys in a dictionary must be of an immutable data type. For example, they can be strings, numbers, or tuples, but not lists, as lists are mutable.

  • Saiten:{"City 1": 456, "City 2": 577, "City 3": 678}
  • Counting:{1: "Left", 2: "Right", 3: "Up", 4: "Down"}
  • Tupel:{(0, 0): "start", (2, 4): "destination"}

A dictionary's values ​​can be of any data type, so we can assign strings, numbers, lists, tuples, sets, and even other dictionaries as values. Here we have some examples:

{"product_id": 4556, "ingredients": ["tomato", "cheese", "mushrooms"], "price": 10.67}
{"product_id": 4556, "ingredients": ("tomato", "cheese", "mushrooms"), "price": 10.67}
{"id": 567, "name": "Emily", "grades": {"math": 80, "biology": 74, "english": 97}}

dictionary size

To get the number of key-value pairs, we use thelen()Occupation:

>>> meu_dict = {"a": 1, "b": 2, "c": 3, "d": 4}>>> len(my_dict)4

Get a value from a dictionary

To get a value from a dictionary, we use its key with this syntax:

<variable_with_dictionary>[<key>]

This expression is replaced with the value that corresponds to the key.

For example:

meu_dict = {"a": 1, "b": 2, "c": 3, "d": 4}print(my_dict["a"])

The output is the assigned value"an":

1

Update a value in a dictionary

To update the value associated with an existing key, we use the same syntax, but now we add an assignment operator and the value:

<variable_with_dictionary>[<key>] = <value>

For example:

>>> meu_dict = {"a": 1, "b": 2, "c": 3, "d": 4}>>> meu_dict["b"] = 6

Now the dictionary is:

{'a': 1, 'b': 6, 'c': 3, 'd': 4}

Add a key/value pair to a dictionary

Keys in a dictionary must be unique. To add a new key-value pair, we use the same syntax we use to update a value, but now the key must be new.

<variable_with_dictionary>[<new_key>] = <value>

For example:

>>> my_dict = {"a": 1, "b": 2, "c": 3, "d": 4}>>> my_dict["e"] = 5

Now the dictionary has a new key-value pair:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Delete a key-value pair in a dictionary

To delete a key-value pair, we use thevonExpression:

del <dictionary variable>[<key>]

For example:

>>> meu_dict = {"a": 1, "b": 2, "c": 3, "d": 4}>>> del my_dict["c"]

Now the dictionary is:

{'a': 1, 'b': 2, 'd': 4}

dictionary methods

These are some examples of the most commonly used dictionary methods:

>>> meu_dict = {"a": 1, "b": 2, "c": 3, "d": 4}>>> 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'])>>> mein_dict.pop("d")4>>> mein_dict.popitem()('c', 3)>>> mein_dict.setdefault("a ", 15)1>>> mein_dict{'a': 1, 'b': 2}>>> mein_dict.setdefault("f", 25)25>>> mein_dict{'a': 1, 'b' : 2, 'f': 25}>>> my_dict.update({"c": 3, "d": 4, "e": 5})>>> my_dict.values()dict_values([1, 2 , 25, 3, 4, 5])>>> mein_dict.clear()>>> mein_dict{}

To learn more about dictionary methods, I recommendreading this articleof the documentation.

🔸 Python Operators

Great. Now that you know the syntax for the basic data types and built-in data structures in Python, let's start digging into Python's operators. They are essential for performing operations and building expressions.

Arithmetic Operators in Python

These operators are:

Addition: +

>>> 5 + 611 >>> 0 + 66 >>> 3.4 + 5.79.1 >>> "Hello" + ", " + "World" 'Hello, World' >>> True + False1

💡Principal:The last two examples are strange, aren't they? This operator behaves differently depending on the data type of the operands.

If they are strings, this operator concatenates the strings and, if they are boolean, performs a specific operation.

Em Python,TRUTHit's equivalent to1eINCORRECTit's equivalent to0. So the result1 + 0 = 1

Deduction:-

>>> 5 - 6-1 >>> 10 - 37 >>> 5 - 6-1 >>> 4,5 - 5,6 - 2,3-3,3999999999999995 >>> 4,5 - 7-2 ,5>>> - 7,8 - 6,2-14,0

Multiplication: *

>>> 5*630>>> 6*742>>> 10*1001000>>> 4*00>>> 3.4 *6.823.119999999999997>>> 4*(-6)-24>>>(- 6) * (-8)48>>> "Hello" * 4'HelloHelloHello'>>> "Hello" * 0''>>> "Hello" * -1''

💡 Tip:You can "multiply" a string by an integer to repeat the string a specified number of times.

Potentiation: **

>>> 6 ** 81679616 >>> 5 ** 225 >>> 4 ** 01 >>> 16 ** (1/2)4,0 >>> 16 ** (0,5)4,0> >> 125 ** (1/3)4,999999999999999 >>> 4,5 ** 2,331,7971929089206 >>> 3 ** (-1)0,3333333333333333

Classification: /

>>> 25 / 55,0>>> 3 / 60,5>>> 0 / 50,0>>> 2467 / 46730,5279263856195163>>> 1 / 20,5>>> 4,5 / 3,51 ,2857142857142858 >>> 6 / 70,8571428571 -40,75 >>> 3 / -4-0,75 >>> -3 / 4-0,75

💡Principal:this operator returns ato floatas a result, even though the decimal part is.0

If you try to share through0, get oneZeroDivisionError:

>>> 5 / 0Traceback (last call): File "<pyshell#109>", line 1, in <module> 5 / 0ZeroDivisionError: Division by zero

Integer division: //

This operator returns an integer if the operands are integers. If they are floats, the result is a float with.0as decimal part because it truncates to decimal part.

>>> 5 // 60 >>> 8 // 24 >>> -4 // -50 >>> -5 // 8-1 >>> 0 // 50 >>> 156773 // 356440

Module: %

>>> 1% 51>>> 2% 52>>> 3% 53>>> 4% 54>>> 5% 50>>> 5% 85>>> 3% 10>>> 15% 30>> > 17% 81>>> 2568% 40>>> 245% 155>>> 0% 60>>> 3,5% 2.41.1>>> 6,7% -7,8-1,0999999999999996>>> 2,3 % 7.52.3

comparison operators

These operators are:

  • Bigger then:>
  • Better than or equal to:>=
  • Smaller than:<
  • Less than or equal to:<=
  • It's the same as:==
  • Not to be equated with:!=

These comparison operators create expressions that evaluate to bothTRUTHorINCORRECT. Here we have some examples:

>>> 5 > 6False>>> 10 > 8True>>> 8 > 8False>>> 8 >= 5True>>> 8 >= 8True>>> 5 < 6True>>> 10 < 8False>>> 8 < 8False >>> 8 <= 5False>>> 8 <= 8True>>> 8 <= 10True>>> 56 == 56True>>> 56 == 78False>>> 34 != 59True>>> 67 != 67False

We can also use them to compare strings based on their alphabetical order:

>>> "Hello" > "World"False>>> "Hello" >= "World"False>>> "Hello" < "World"True>>> "Hello" <= "World"True>>> " Hello" == "World"False>>> "Hello" != "World"True

We often use them to compare the values ​​of two or more variables:

>>> a = 1>>> b = 2>>> a < bTrue>>> a <= bTrue>>> a > bFalse>>> a >= bFalse>>> a == bFalse>>> a ! = bWahr

💡Principal:Observe that is the comparison operator==while is the assignment operator=. Its effect is different.==ReturnsTRUTHorINCORRECTduring=assigns a value to a variable.

Concatenation of comparison operators

In Python, we can use something called "comparison operator concatenation", where we concatenate comparison operators to make more than one comparison more accurate.

This checks, for example, whetheranIt is less thanbwhat ifbIt is less thanc:

a < b < c

Here we have some examples:

>>> a = 1>>> b = 2>>> c = 3>>> a < b < cVerdadeiro>>> a > b > cFalso>>> a <= b <= cVerdadeiro>>> a >= b >= cFalso>>> a >= b > cFalso>>> a <= b < cVerdadeiro

Logical operators

There are three logical operators in Python:e,or, eNot. Each of these operators has its own truth table and are essential for working with conditions.

DieeOperator:

>>> True and TrueTrue>>> True and FalseFalse>>> False and TrueFalse>>> False and FalseFalse

DieorOperator:

>>> True or TrueTrue>>> True or FalseTrue>>> False or TrueTrue>>> False or FalseFalse

DieNotOperator:

>>> not TrueFalse >>> not FalseTrue

These operators are used to build more complex expressions that combine different operators and variables.

For example:

>>> a = 6 >>> b = 3 >>> a < 6 or b > 2True >>> a >= 3 and b >= 1True >>> (a + b) == 9 and b > 1True> >> ((a % 3) < 2) and ((a + b) == 3) Incorrect

assignment operators

Assignment operators are used to assign a value to a variable.

They are:=,+=,-=,*=,%=,/=,//=,**=

  • Die=The operator assigns the value to the variable.
  • The other operators perform an operation on the current value of the variable and the new value and assign the result to the same variable.

For example:

>>> x = 3 >>> x3 >>> x += 15 >>> x18 >>> x -= 2 >>> x16 >>> x *= 2 >>> x32 >>> x %= 5 >>> x2 >>> x /= 1 >>> x2.0 >>> x //= 2 >>> x1.0 >>> x **= 5 >>> x1.0

💡Tips:These operators perform bitwise operations before assigning the result to the variable:&=,|=,^=,>>=,<<=.

association operator

You can check if an element is in a sequence or not with operators:noenot in. The result will be eitherTRUTHorINCORRECT.

For example:

>>> 5 inches [1, 2, 3, 4, 5]True>>> 8 inches [1, 2, 3, 4, 5]False>>> 5 inches (1, 2, 3, 4, 5) True>>> 8 in (1, 2, 3, 4, 5)False>>> "a" in {"a": 1, "b": 2}True>>> "c" in {"a" : 1, "b": 2}False>>> "h" in "Hello"False>>> "H" in "Hello"True>>> 5 not in [1, 2, 3, 4, 5]False >>> 8 not in (1, 2, 3, 4, 5)True>>> "a" not in {"a": 1, "b": 2}False>>> "c" not in {" a": 1, "b": 2}True>>> "h" not in "Hello"True>>> "H" not in "Hello"False

We often use them with variables that store strings, like in this example:

>>> message = "Hello, World!">>> "e" in messageTrue

🔹 Conditions in Python

Now let's see how we can write conditions so that certain parts of our code are executed (or not), depending on whether a condition is true.TRUTHorINCORRECT.

What ifPython Instructions

This is the syntax of a BasicWhat ifExpression:

if <condition>: <code>

If the condition isTRUTH, the code is executed. on the other handINCORRECT, the code will not run.

💡 Tip:There are two points (:) at the end of the first line and the code is indented. This is essential in Python for the code to belong in the condition.

Here we have some examples:

been wrong

x = 5if x > 9: print("Hello Welt!")

The condition isx > 9and the code isprint("Hello Welt!").

In this case, the conditionINCORRECT, then there is no way out.

true state

Here we have another example. Now is the conditionTRUTH:

color = "Blue" if color =="Blue": print("This is my favorite color")

The output is:

"This is my favorite color"

code after condition

Here's a code example that runs after the condition completes. Note that the last line is not indented, which means it is not part of the condition.

x = 5if x > 9: print("Hello!")print("End")

In this example, the conditionx > 9It isINCORRECT, then the first print statement is not executed, but the last print statement is executed because it is not part of the condition, so the output is:

Fim

However, if the condition isTRUTH, as in this example:

x = 15if x > 9: print("Hello!")print("End")

The output will be:

Hey! The end

Examples of conditionals

This is another example of a condition:

favorite_season = "Summer"if favorite_season == "Summer": print("This is my favorite season too!")

In this case the output is:

This is my favorite season too!

But if we change the value offavorite season:

favorite_season = "Winter"if favorite_season =="Summer": print("This is my favorite season too!")

There will be no output because the condition isINCORRECT.

on the other handPython Instructions

We can add aandersCondition clause clause when we need to specify what should happen if the condition isINCORRECT.

This is the general syntax:

if <condition>: <code>else: <code>

💡 Tip:Note that the two blocks of code are indented (What ifeanders). This is important so that Python can distinguish between code that belongs in the main program and code that belongs in the condition.

Let's see an example with thisandersClause:

true state

x = 15if x > 9: print("Hello!")else: print("Bye!")print("End")

The output is:

Hey! The end

If the state ofWhat ifclause isTRUTH, this clause expires. Theandersclause does not work.

been wrong

Now theandersThe clause executes because the condition isINCORRECT.

x = 5if x > 9: print("Hello!")else: print("Bye!")print("End")

Now the output is:

Goodbye! The end

if/elif/elsePython Instructions

To further customize our terms, we may add one or moreelfClauses to check and handle various conditions. Only the code of the first condition that is evaluatedTRUTHwill run.

💡 Tip: elfmust be written afterWhat ifand beforeanders.

first true condition

x = 5if x < 9: print("Hello!")elif x < 15: print("Good to see you")else: print("Bye!")print("End")

We have two conditionsx < 9ex < 15. So just the first condition block of codeTRUTHrun from top to bottom.

In this case the output is:

Hey! The end

Because the first condition isTRUTH:x < 9.

second true condition

If the first condition isINCORRECT, then the second condition is checked.

In this example, the first conditionx < 9It isINCORRECTbut the second conditionx < 15It isTRUTH, so that the code associated with this clause is executed.

x = 13if x < 9: print("Hello!")elif x < 15: print("Good to see you")else: print("Bye!")print("End")

The output is:

good see you

All conditions are false

If all conditionsINCORRECT, then theandersClause is executed:

x = 25if x < 9: print("Hello!")elif x < 15: print("Good to see you")else: print("Bye!")print("End")

The output will be:

Goodbye! The end

several eleven clauses

We can add as many as we wantelfclauses as needed. This is an example of a condition with twoelfClauses:

if favorite_season == "Winter": print("This is also my favorite season") elif favorite_season == "Summer": print("Summer is great") elif favorite_season == "Spring": print("I love winter" spring " )else: print("Autumn is my mother's favorite season")

Each condition is checked and only the code block for the first condition is evaluated.TRUTHwill run. when none of them areTRUTH, aandersrunning clause.

🔸 For loops em Python

Now that you know how to write conditionals in Python, let's start diving into loops. For loops are amazing programming structures that allow you to repeat a block of code a specified number of times.

This is the basic syntax for writing a for loop in Python:

para <loop_variable> em <iterable>: <code>

The iterable can be a list, tuple, dictionary, string, the sequence returned by Range, a file, or any other type of iterable in Python. we started withReach().

DieReach()function in python

This function returns a sequence of integers that we can use to determine how many iterations (repetitions) of the loop to complete. The loop performs one iteration through the entirety.

💡 Tip:Each integer is assigned to the loop variable individually per iteration.

This is the general syntax for writing a for loopReach():

für <loop_variable> in range(<start>, <stop>, <step>): <code>

As you can see, the range function has three parameters:

  • Start: where the sequence of integers begins. By default it is0.
  • Pare: where the sequence of integers will end (ignoring this value).
  • Stage: The value added to each element to get the next element in the sequence. By default it is1.

You can pass 1, 2 or 3 arguments toReach():

  • With 1 argument, the value is assigned to thePareparameters and default values ​​for the other two parameters are used.
  • With 2 arguments, values ​​are assigned to theStartePareparameters and the default value forStageit is used.
  • With 3 arguments, values ​​are assigned to theStart,Pare, eStageparameters (in order).

Here are some examples witha parameter:

for i in range(5): print(i)

Exit:

01234

💡Principal:the loop variable is automatically updated.

>>> for j in range(15): print(j * 2)

Exit:

0246810121416182022242628

In the following example, we repeat a string as many times as the value of the loop variable specifies:

>>> prepare num in range(8):print("Hello" * num)

Exit:

HalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHallo

We can also use for loops with built-in data structures like lists:

>>> my_list = ["a", "b", "c", "d"]>>> for i in range(len(my_list)):print(my_list[i])

Exit:

A B C D

💡Principal:if you userange(len(<seq>)), you get a sequence of numbers from0untillen(<seq>)-1. This represents the sequence of valid indexes.

These are some examples withtwo parameters:

>>> for i in range(2, 10):print(i)

Exit:

23456789

Code:

>>> for j in range(2, 5):print("Python" * j)

Exit:

PythonPythonPythonPythonPythonPythonPythonPythonPythonPython

Code:

>>> my_list = ["a", "b", "c", "d"]>>> for i in range(2, len(my_list)):print(my_list[i])

Exit:

CD

Code:

>>> my_list = ["a", "b", "c", "d"]>>> for i in range(2, len(my_list)-1):my_list[i] *= i

Now the list is:['a', 'b', 'cc', 'd']

These are some examples withthree parameters:

>>> for i in range(3, 16, 2):print(i)

Exit:

3579111315

Code:

>>> for j in range(10, 5, -1):print(j)

Exit:

109876

Code:

>>> my_list = ["a", "b", "c", "d", "e", "f", "g"]>>> for i in range(len(my_list)-1, 2 , -1):print(my_list[i])

Exit:

º

How to iterate over iterables in Python

We can iterate directly over iterables like lists, tuples, dictionaries, strings and files using for loops. We get each of its elements individually per iteration. This is very helpful for working directly with them.

Let's look at some examples:

Iterate over a string

When we iterate over a string, its characters are assigned to the loop variable one by one (including spaces and symbols).

>>> message = "Hello, World!">>> for char in message:print(char)Hello, World!

We can also iterate over modified copies of the string by calling a String method specifying the iterable in the for loop. This assigns the copy of the string to be used for iterations as an iterable, like this:

>>> word = "Hello">>> for char in word.lower(): # call string methodprint(char)hello
>>> word = "Hello">>> for char in word.upper(): # call string methodprint(char)HELLO

Iterate over lists and tuples

>>> my_list = [2, 3, 4, 5]>>> for num in my_list:print(num)

The output is:

2345

Code:

>>> my_list = (2, 3, 4, 5)>>> for num in my_list:if num % 2 == 0:print("Even")else:print("Odd")

Exit:

EvenOddEvenOdd

Iterate over dictionary keys, values, and key-value pairs

We can iterate over a dictionary's keys, values, and key-value pairs by calling specific dictionary methods. Let's see how.

foriterate over the key, We wrote:

para <var> em <dictionary_variable>: <code>

We simply write the name of the variable that the dictionary stores as an Iterable.

💡 Tip:you can write too<dictionary variable>.keys()but writing the variable name directly is more concise and works just as well.

For example:

>>> my_dict = {"a": 1, "b": 2, "c": 3}>>> para chave em my_dict:print(key)abc

💡 Tip:You can assign any valid name to the loop variable.

foriterate over the values, we use:

para <var> em <dictionary_variable>.values(): <code>

For example:

>>> my_dict = {"a": 1, "b": 2, "c": 3}>>> für Wert in my_dict.values():print(value)123

foriterate over the key-value pairs, we use:

para <key>, <value> in <dictionary_variable>.items(): <code>

💡Principal:We define two loop variables because we want to assign the key and value to the variables that we can use in the loop.

>>> my_dict = {"a": 1, "b": 2, "c": 3}>>> for key, value in my_dict.items():print(key, value)a 1b 2c 3

If we only define one loop variable, that variable will contain a tuple with the key-value pair:

>>> my_dict = {"a": 1, "b": 2, "c": 3}>>> for pair in my_dict.items():print(pair)('a', 1)('b ', 2)('c', 3)

Stop and continue in Python

Now you know how to iterate over sequences in Python. We also have loop control statements to customize what happens when the loop runs:pauseeProceed.

The break statement

DiepauseThe statement is used to stop the loop immediately.

When onepauseis found, the loop will stop and the program will return to its normal execution after the loop.

In the example below, we stop the loop when an even element is found.

>>> my_list = [1, 2, 3, 4, 5]>>> for elem in my_list:if elem % 2 == 0:print("Even:", elem)print("break")breakelse:print ("Ungerade:", elem)Ungerade: 1Gerade: 2Pause

The continue instruction

DieProceedThe statement is used to skip the remainder of the current iteration.

If found while executing the loop, the current iteration stops and a new one starts with the updated value of the loop variable.

In the example below, we skip the current iteration if the element is even and only print the value if the element is odd:

>>> my_list = [1, 2, 3, 4, 5]>>> for elem in my_list:if elem % 2 == 0:print("continue")continueprint("Odd:", elem)Odd: 1continuationOdd : 3próximaOdd: 5

The zip() function in Python

Postal Code()is an awesome built-in function that we can use in Python to iterate through multiple sequences at once and get the matching elements on each iteration.

We just need to pass the strings as arguments to thePostal Code()function and use that result in the loop.

For example:

>>> my_list1 = [1, 2, 3, 4]>>> my_list2 = [5, 6, 7, 8]>>> for elem1, elem2 in zip(my_list1, my_list2):print(elem1, elem2)1 52 63 74 8

The enumerate() function in Python

You can also keep track of a counter as the loop runs with it.Tell ()Occupation. It is usually used to iterate over a sequence and get the corresponding index.

💡 Tip:By default, the counter starts at0.

For example:

>>> minha_lista = [5, 6, 7, 8]>>> for i, elem in enumerate(my_list):print(i, elem)0 51 62 73 8
>>> palavra = "Hallo">>> for i, char in enumerate(word):print(i, char)0 H1 e2 l3 l4 o

If you start the counter0, you can use the index and current value in the same iteration to change the sequence:

>>> minha_lista = [5, 6, 7, 8]>>> for index, num in enumerate(my_list):my_list[index] = num * 3>>> my_list[15, 18, 21, 24]

You can start the counter with a different number by passing a second argument toenumerate():

>>> palavra = "Hallo">>> for i, char in enumerate(word, 2):print(i, char)2 H3 e4 l5 l6 o

To the else clause

For loops also have aandersClause. You can add this clause to the loop if you want to execute a specific block of code when the loop completes all its iterations without encountering thepauseExpression.

💡 Tip:What ifpauseis found thatandersclause is not executed and ifpauseis not found thatandersrunning clause.

In the example below, we are trying to find an item greater than 6 in the list. This element was not found, sopausedoesn't work and theandersrunning clause.

my_list = [1, 2, 3, 4, 5] para elem in my_list: if elem > 6: print("Found") breakelse: print("Not Found")

The output is:

Not found

However, if thepausestatement executes thisandersclause does not work. We can see this in the following example:

my_list = [1, 2, 3, 4, 5, 8] # Agora a lista tem valor 8 para elem em my_list: if elem > 6: print("Found") breakelse: print("Not Found")

The output is:

Found

🔹 While loops in Python

While loops are similar to for loops in that they allow us to repeat a block of code. The difference is that while loops execute while a condition is present.TRUTH.

In a while loop, we define the condition, not the number of iterations. The loop stops when the condition isINCORRECT.

This is the general syntax of a while loop:

while <condition>: <code>

💡Principal:In while loops, you must update the variables that are part of the condition to ensure that the condition eventually becomes true.INCORRECT.

For example:

>>> x = 6 >>> while x < 15:print(x)x += 167891011121314
>>> x = 4>>> while x >= 0:print("Hallo" * x)x -= 1HalloHalloHalloHalloHalloHalloHalloHalloHalloHalloHallo
>>> num = 5 >>> while num >= 1:print("*" * num)num -= 2***********

break and continue

we can also usepauseeProceedwith while loops and they both work exactly the same:

  • pauseimmediately breaks the while loop.
  • Proceedstops the current iteration and starts the next one.

For example:

>>> x = 5>>> while x < 15:if x % 2 == 0:print("Even:", x)breakprint(x)x += 1 5Even: 6
>>> x = 5>>> while x < 15:if x % 2 == 0:x += 1continueprint("Ungerade:", x)x += 1Ungerade: 5Ungerade: 7Ungerade: 9Ungerade: 11Ungerade: 13

Dieandersclause

We can also add aanders-clause for a while loop. What ifpauseis found thatandersThe clause is not executed, but if thepausestatement not found thatandersrunning clause.

In the example below, thepausestatement was not found because none of the numbers before the condition are evenINCORRECT, then theandersrunning clause.

x = 5while x < 15:if x % 2 == 0:print("Even number found")breakprint(x)x += 2else:print("All numbers were odd")

This is the output:

5791113All numbers were odd

But in this version of the example, thepausestatement is found and theandersClause not executed:

x = 5while x < 15:if x % 2 == 0:print("Even number found")breakprint(x)x += 1 # Now we increase the value by 1else:print("All numbers were odd")

The output is:

5Even number found

Loops while infinitos

When we write and work with while loops, we can have what is called an "infinite loop". If the condition is neverINCORRECT, the loop will never stop without outside intervention.

This usually happens when the variables in the condition are not updated correctly during the execution of the loop.

💡 Tip:You must make the necessary updates to these variables to ensure that the condition eventually evaluates toINCORRECT.

For example:

>>> x = 5>>> while x > 2:print(x)555555555...# The output continues indefinitely

💡Principal:To stop this process, typeSTRG + C. you should see oneKeyboard InterruptMessage.

🔸 Nested Loops in Python

We can write for loops inside for loops and while loops inside while loops. These inner loops are called nested loops.

💡Principal:the inner loop executes for each iteration of the outer loop.

Nested For Loops in Python

>>> for i in range(3): for j in range(2): print(i, j)0 00 11 01 12 02 1

If we add print instructions, we can see what's going on behind the scenes:

>>> for i in range(3):print("===> Outer Loop")print(f"i = {i}")for j in range(2):print("Inner Loop")print( f"j = {j}")===> Outer Loopi = 0Inner Loopj = 0Inner Loopj = 1===> Outer Loopi = 1Inner Loopj = 0Inner Loopj = 1===> Outer Loopi = 2Inner Loopj = 0Inner Loopj = 1

The inner loop completes two iterations per iteration of the outer loop. Loop variables are updated when a new iteration starts.

This is another example:

>>> num_rows = 5 >>> for i in range(5):for num_cols in range(num_rows-i):print("*", end="")print()********* ******

Nested while loops in Python

Here is an example of a nested while loop. In this case, we need to update the variables that are part of each condition to ensure the loops exit.

>>> i = 5>>> while i > 0:j = 0while j < 2:print(i, j)j += 1i -= 15 05 14 04 13 03 12 02 11 01 1

💡Principal:We can also have for loops inside while loops and while loops inside for loops.

🔹 Functions in Python

In Python, we can define functions to make our code reusable, more readable and organized. This is the basic syntax of a Python function:

def <function name>(<param1>, <param2>, ...): <code>

💡 Tip:A function can have zero, one or more parameters.

Function without parameters in Python

A function with no parameters has an empty pair of square brackets after its name in the function definition. For example:

def print_pattern(): size = 4 für i in range(size): print("*" * size)

This is the output when we call the function:

>>> print_pattern()****************

💡 Tip:You must put an empty pair of parentheses after the function name to call it.

Function with one parameter in Python

A function with one or more parameters has a parameter list in parentheses after its name in the function definition:

def welcome_student(name): print(f"Hello, {name}! Welcome to class.")

When we call the function we only need to pass a value as an argument and this value will be replaced where we used the parameter in the function definition:

>>> welcome_student("Nora") Hi Nora! Welcome to class.

Here's another example - a function that prints a pattern of asterisks. You need to specify how many lines you want to print:

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 ​​ofnum_rows:

>>> print sample(3)******>>> print sample(5)****>>> print sample(8)**** *** ****** ***********************

Functions with two or more parameters in Python

To define two or more parameters, just separate them with a comma:

def print_sum(a, b): print(a + b)

Now, when we call the function, we need to pass two arguments:

>>> 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 we just saw with one parameter to work with two parameters and print a pattern with a custom character:

def print_pattern(num_rows, char):para i in range(num_rows):for num_cols in range(num_rows-i):print(char, end="")print()

You can see the output with the custom character that we call the function and pass the two arguments:

>>> print_pattern(5, "A")AAAAAAAAAAAAAA>>> print_pattern(8, "%")%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%>>> print_pattern(10, "#")############################## #########################

How to return a value in Python

Great. Now that you know how to define a function, let's see how you can work with return statements.

Many times we need to return a value from a function. We can do this with thatReturnsstatement in Python. We just need to write this in the function definition:

Retorno <value_to_return>

💡 Tip:the function will stop immediately ifReturnsfound and returned the value.

Here we have an example:

def get_rectangle_area(length, width): returns length * width

Now we can call the function and assign the result to a variable, as the result will be returned by the function:

>>> area = get_rectangle_area(4, 5)>>> area20

we can also useReturnswith a condition to return a value based on whether a condition isTRUTHorINCORRECT.

In this example, the function returns the first even element found in the sequence:

def get_first_even(seq): für elem in seq: if elem % 2 == 0: return elem else: return None

When we call the function, we see the expected results:

>>> wert1 = get_first_even([2, 3, 4, 5]) >>> wert12
>>> valor2 = get_first_even([3, 5, 7, 9])>>> print(valor2)Nenhum

💡Principal:if a function does not have aReturnsinstruction or does not find one during its execution, it returnsNoneBy default.

DiePython code style guiderecommends consistent use of return statements. He mentions that we:

Be consistent with return statements. All return statements in a function must return an expression, or none of them must. If a return statement returns an expression, all return statements that do not return a value must explicitly declare it as return None, and an explicit return statement must be present at the end of the function (if accessible).

A standard argument in Python

We can assign default arguments to our function parameters. All we have to do is write<parameter>=<value>in the parameter list.

💡 Tip:DiePython code style guidementions that "we must not use spaces around the = sign when it is used to specify a keyword argument".

In this example, we assign the default value of 5 to the parameterb. If we omit this value when calling the function, the default value will be used.

def print_product(a, b=5): print(a * b)

If we call the function without this argument, you will see the output:

>>> print_product(4)20

We confirmed that the default argument 5 was used in the operation.

But we can also assign a custom value tobpassing a second argument:

>>> print_product(3, 4)12

💡Principal:Parameters with default arguments must be defined at the end of the parameter list. Otherwise, you will see this error:SyntaxError: Non-default argument follows default argument.

Here's another example using the function we wrote to print a pattern. We assign the default value"*"for theCharactersParameter.

def print_pattern(num_rows, char="*"):for i in range(num_rows):for num_cols in range(num_rows-i):print(char, end="")print()

Now we have the option to use the default value or customize it:

>>> print sample(5)****************>>> print sample(6, "&")&&&&&&&&&&&&&&&&&&&&

🔸 Recursion in Python

A recursive function is a function that calls itself. These functions have a base case that interrupts the recursive process and a recursive case that continues the recursive process with another recursive call.

Here are some examples in Python:

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)
def find_power(a, b): if b == 0: return 1 else: return a * find_power(a, b-1)

🔹 Exception Handling in Python

An unexpected error or event that occurs during the execution of a program is called aexception. Thanks to the elements we are about to see, we can avoid terminating the program abruptly in this case.

Let's look at the types of exceptions in Python and how we can handle them.

Common Exceptions in Python

This is a list of common Python exceptions and why they occur:

  • ZeroDivisionError:Raised when the second argument of a division or modulus operation is zero.
>>> 5 / 0Traceback (last call): file "<pyshell#0>", line 1, in <module> 5 / 0ZeroDivisionError: division by zero >>> 7 // 0Traceback (last call): file " <pyshell #1>", line 1, in <module> 7 // 0ZeroDivisionError: integer division or modulus by zero>>> 8 % 0Traceback (last call): File "<pyshell#2>", line 1, in <module> 8 % 0ZeroDivisionError: integer division or modulus by zero
  • Index error:thrown when trying to use an invalid index to access an element of a sequence.
>>> my_list = [3, 4, 5, 6] >>> my_list[15]Traceback (last call): File "<pyshell#4>", line 1, in <module> my_list[15]IndexError : Index out of range list
  • key error:thrown when we try to access a key-value pair that doesn't exist because the key isn't in the dictionary.
>>> my_dict = {"a": 1, "b": 2, "c": 3}>>> my_dict["d"]traceback(last call): file "<pyshell#6>", line 1 , in <module> my_dict["d"]KeyError: 'd'
  • naming error:thrown when we use a variable that has not been previously defined.
>>> bTraceback (last call): File "<pyshell#8>", line 1, in <module> bNameError: Name 'b' not defined
  • recursion error:Fired when the interpreter detects that the maximum recursion depth has been exceeded. This usually occurs when the process never reaches the base case.

In the following example, we get arecursion error. DieFacultyThe function is implemented recursively, but the argument passed to the recursive call isnrather thann-1. Unless the value is already0or1, the base case is not reached because the argument is not decremented, so the process continues and we get this error.

>>> def factorial(n):if n == 0 or n == 1:return 1else:return n * factorial(n)>>> factorial(5)Traceback (last call): File "<pyshell# 6 > ", line 1, in file <module> factorial(5) "<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 n factorial returns * factorial(n) [Previous line is repeated 1021 times] File "<pyshell#5>", line 2, in factorial if n == 0 or n == 1:RecursionError: Maximum recursion depth exceeded in comparison

💡Principal:To learn more about these exceptions, I recommend readingThis articleof the documentation.

Try/Besidesem Python

We can use try/except in Python to catch exceptions as they occur and handle them appropriately. This allows the program to exit gracefully or even recover from the exception.

This is the basic syntax:

versuchen Sie: <code_that_may_raise_an_exception>außer: <code_to_handle_the_exception_if_it_occurs>

For example, if we use user input to access an item in a list, the input might not be a valid index, so an exception might be thrown:

index = int(input("Enter index: "))try: my_list = [1, 2, 3, 4] print(my_list[index])except: print("Please enter a valid index." )

If we enter an invalid value like 15, the output will be:

Enter a valid index.

Because theBesidesrunning clause. However, if the value is valid, the code inTrywill run as expected.

Here we have another example:

a = int(input("Enter a: "))b = int(input("Enter b: ")))try: division = a / b print(division)except: print("Please enter valid values." )

The output is:

Enter a: 5 Enter b: 0 Enter valid values.

How to catch a specific exception type in Python

Instead of catching and handling all possible exceptions that may occur in theTryclause we can catch and handle a specific type of exception. We only need to specify the exception type after theBesidesKeyword:

tente: <code_that_may_raise_an_exception>außer <Ausnahmetyp>: <code_to_handle_an_exception_if_it_occurs>

For example:

index = int(input("Enter index: "))try: my_list = [1, 2, 3, 4] print(my_list[index])except IndexError: # specify type print("Please specify 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 , you enter valid a values.")

How to assign a name to exception object in Python

We can provide a name for the exception object by assigning it to a variable that we can use inBesidesClause. This allows us to access your description and attributes.

We just need to addas <name>, such that:

tente: <code_that_may_raise_an_exception>außer <Ausnahmetyp> as <name>: <code_to_handle_an_exception_if_it_occurs>

For example:

index = int(input("Enter index: "))try: my_list = [1, 2, 3, 4] print(my_list[index])except IndexError as e: print("Exception thrown:", e )

This is the exit when we enterfifteenas Index:

Enter index: 15Exception thrown: List index out of range

This is another example:

a = int(input("Enter a: "))b = int(input("Enter b: ")))try: division = a / b print(division)except ZeroDivisionError as err: print("Por favor insira valores válidos a.", erro)

This is the output when we enter the value0Prob:

Enter valid values. divide by zero

Try/Besides/andersem Python

We can add aandersclause for this structureBesidesif we want to choose what happens if no exception occurs during the execution ofTryClause:

tente: <code_that_may_raise_an_exception>außer: <code_to_handle_an_exception_if_it_occurs>filho: <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 values valid for.", err)else: print("Both values ​​were valid.")

When we enter the values5e0Proanebor the output is:

Enter valid values. divide by zero

But if, for example, both values ​​are valid5e4Proanebor theandersclause expiresTryis complete and we see:

1.25 Both values ​​were valid.

Try/Besides/anders/Finallyem Python

We can also add aFinally-clause when we need to run code that should always run even if an exception is thrownTry.

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 values valid for.", err)else: print("Both values ​​were valid.")finally: print("Finally!")

If both values ​​are valid, the output is the result of division and:

Both values ​​were valid. Finally!

What if an exception is thrown becausebIt is0, We see:

Enter valid values. Division by zero Finally!

DieFinallyThe clause is always executed.

💡 Tip:For example, this clause can be used to close files even if the code raises an exception.

🔸 Object Oriented Programming in Python

In object-oriented programming (OOP), we define classes that serve as blueprints for creating Python objects with attributes and methods (object-associated functionality).

This is a general syntax for defining a class:

class <ClassName>: <class_attribute_name> = <value> def __init__(self,<param1>, <param2>, ...): self.<attr1> = <param1> self.<attr2> = <param2> . . . # As many attributes as needed def <method_name>(self, <param1>, ...): <code> # As many methods as needed

💡 Tip: untilrefers to an instance of the class (an object created using the class's design).

As you can see, a class can have many different elements, so let's analyze them in detail:

class header

The first line of the class definition has theClassKeyword and class name:

class dog:
class house:
class ball:

💡 Tip:If the class inherits attributes and methods from another class, we see the class name in square brackets:

Class poodle (dog):
Truck class (vehicle):
Class mother (family member):

In Python, we write the class name in camel case (also known as pascal case), where each word starts with a capital letter. For example:Family member

__inside side__and instance attributes

We'll use the class to create objects in Python in the same way we build real houses from blueprints.

Objects have attributes that we define in the class. We usually initialize these attributes in__inside side__. This is a method that runs when we create an instance of the class.

This is the general syntax:

def __init__(self, <parameter1>, <parameter2>, ...): self.<attribute1> = <parameter1> # instance attribute self.<attribute2> = <parameter2> # instance attribute . . . # As many instance attributes as needed

We provide as many parameters as needed to customize the attribute values ​​of the object being created.

Here is an example of adogclass with this method:

Classe Dog: def __init__(self, name, age): self.name = nome self.age = idade

💡Principal:Note the leading and trailing double underscores in the name__inside side__.

How to create an instance

To create an instance ofdog, we need to provide the name and age of the dog instance to assign these values ​​to the attributes:

my_dog = Dog("Daughter-in-law", 10)

Great. Now we have our instance ready to be used in the program.

Some classes don't need arguments to create an instance. In this case, we just write empty square brackets. For example:

Klasse Circle: def __init__(self): self.radius = 1

To create an instance:

>>> my_circle = circle()

💡Principal: untilit's like a parameter that works "behind the scenes", so even if you see it in the method definition, you shouldn't consider it when passing the arguments.

indisputably standard

We can also assign default values ​​to attributes and allow the user to customize the value.

In this case, we would write<attribute>=<value>in the parameter list.

This is an example:

Klasse Circle: def __init__(self, radius=1): self.radius = radius

Now we can create aKreisInstance with default radius value by omitting the value, or customize it by passing a value:

# Default value >>> my_circle1 = Circle() # Custom value >>> my_circle2 = Circle(5)

How to get an instance attribute

To access an instance attribute, we use this syntax:

<object variable>.<attribute>

For example:

# class definition>>> class Dog: def __init__(self, name, age): self.name = name self.age = age# create instance >>> my_dog = Dog("Nora", 10)# get attribute> > > my_dog.name'Nora'>>> my_dog.age10

How to update an instance attribute

To update an instance attribute, we use this syntax:

<object variable>.<attribute> = <new_value>

For example:

>>> class Dog: def __init__(self, name, age): self.name = nome self.age = alter >>> my_dog = Dog("Nora", 10)>>> my_dog.name'Nora'# Update das Attribut >>> mein_hund.name = "Norita">>> mein_hund.name'Norita'

How to remove an instance attribute

To remove an instance attribute, we use this syntax:

del <object variable>.<attribute>

For example:

>>> class Dog: def __init__(self, name, age): self.name = nome self.age = alter >>> my_dog = Dog("Nora", 10)>>> my_dog.name'Nora'# Delete this attribute>>> del my_dog.name>>> my_dog.nameTraceback (letzter Aufruf zuletzt): File "<pyshell#77>", linha 1, in <module> my_dog.nameAttributeError: 'Dog' object has no attribute ' Name '

How to delete an instance

Similarly, we can delete an instance withvon:

>>> class Dog: def __init__(self, name, age): self.name = name self.age = alter >>> my_dog = Dog("Nora", 10)>>> my_dog.name'Nora'# Delete the instance >>> del my_dog >>> my_dogTraceback (letzter Aufruf zuletzt): File "<pyshell#79>", line 1, in <module> my_dogNameError: name 'my_dog' is not defined

Public vs non-public attributes in Python

In Python, we don't have access modifiers to functionally restrict access to instance attributes, so we rely on naming conventions to indicate this.

For example, by adding a leading underscore, we can signal to other developers that an attribute should not be public.

For example:

Class dog: def __init__(self, name, age): self.name = name # public attribute self._age = age # non-public attribute

The Python documentation mentions:

Only use a leading underscore for non-public methods and instance variables.

Always decide whether a class's methods and instance variables (collectively: "attributes") should be public or non-public. When in doubt, don't vote publicly; It's easier to make it public later than it is to make a public attribute non-public.

Non-public attributes are those that are not intended to be used by third parties; They do not guarantee that non-public attributes will not be changed or even removed. -Those ones

However, as the documentation also mentions:

We don't use the term "private" here because no attribute is really private in Python (without a generally unnecessary amount of work). -Those ones

💡 Tip:Technically, we can still access and modify the attribute if we add the leading underscore to its name, but we shouldn't.

Python class attributes

Class attributes are shared by all instances of the class. They all have access to this attribute and are also affected by any changes made to these attributes.

class dog: # class attributes kingdom="animalia" species="canis lupus" def __init__(self,name,age): self.name = name self.age = age

💡 Tip:usually they are written before that__inside side__Method.

How to get a class attribute

To get the value of a class attribute, we use this syntax:

<class name>.<attribute>

For example:

>>> Class Dog: Kingdom="Animalia" def __init__(self,name,age): self.name = Nome self.age = Age >>> Dog.kingdom'Animalia'

💡 Tip:You can also use this syntax inside the class.

How to update a class attribute

To update a class attribute, we use this syntax:

<class name>.<attribute> = <value>

For example:

>>> Dog Class: Kingdom = "Animalia" def __init__(self, name, age): self.name = Name self.age = Age >>> Dog.kingdom'Animalia' >>> Dog.kingdom = "New Kingdom ">>> Dog.kingdom 'New Kingdom'

How to delete a class attribute

we usevonto delete a class attribute. For example:

>>> Klasse Hund: Kingdom = "Animalia" def __init__(self, name, age): self.name = name self.age = age>>> Dog.kingdom'Animalia' # Delete class attribute>>> del Dog. Kingdom>>> Dog.kingdomTraceback (letzter Aufruf zuletzt): File "<pyshell#88>", line 1, in <module> Dog.kingdomAttributeError: object of type 'Dog' has no attribute 'kingdom'

How to define methods

Methods represent the functionality of instances of the class.

💡 Tip:Instance methods can operate on the attributes of the instance that the method calls when we writeself.<Atributo>in the method definition.

This is the basic syntax of a method in a class. They are usually at the bottom__inside side__:

class <Klassenname>: # Klassenattribute # __init__ def <method_name>(self, <param1>, ...): <code>

They can have zero, one, or more parameters as needed (just like functions!), but instance methods must always have auntilas the first parameter.

For example, here's aProductionMethod without parameters (in addition tountil):

class Hund: def __init__(self, name, age): self.name = nome self.age = alter def bark(self): print(f"woof-woof. Ich bin {self.name}")

To call this method we use this syntax:

<object variable>.<method>(<arguments>)

For example:

# Criar instância>>> my_dog = Dog("Nora", 10)# Call method>>> my_dog.bark()woof-woof. eu sou nora

here we have oneplayerclass with aincrement_speedMethod with one parameter:

classe Player: def __init__(self, name): self.name = nome self.speed = 50 def increment_speed(self, valor): self.speed += valor

To invoke the method:

# Create instance >>> my_player = Player("Nora")# Check the initial speed to see the change>>> my_player.speed50# Increment speed>>> my_player.increment_speed(5)# Confirm change >>> my_player. Speed55

💡Principal:To add more parameters, just separate them with a comma. It is recommended to add a space after the comma.

Properties, Getters, and Setters in Python

Getters and setters are methods we can define to get and set the value of an instance attribute, respectively. They function as an intermediary to "protect" attributes from direct changes.

In Python, we generally use properties instead of getters and setters. Let's see how we can use them.

To define a property, we write a method with this syntax:

@propertydef <property_name>(self): retorna self.<attribute>

This method acts as a getter, so it will be called when we try to access the attribute's value.

Now we might want to define a setter as well:

@<property_name>.setterdef <property_name>(self, <param>): self.<attribute> = <param>

And a deleter to delete the attribute:

@<property_name>.deleterdef <property_name>(self): del self.<atributo>

💡 Tip:You can write any code inside these methods to get, set, and clear an attribute. It is recommended to keep them as simple as possible.

This is an example:

Classe Hund: def __init__(self, name): self._name = name @property def name(self): return self._name @name.setter def name(self, new_name): self._name = new_name @name.deleter def nome(selbst): del self._name

If we add descriptive print statements, we can see that they are called when we perform their operation:

>>> class Dog: def __init__(self, name): self._name = name @property def name(self): print("Calling getter") return self._name @name.setter def name(self, new_name): print("Calling setter") self._name = neuer_name @name.deleter def name(self): print("Calling deleter") del self._name >>> my_dog = Dog("Nora")>>> my_dog.nameCalling getter'Nora'>>> mein_hund.name = "Norita"Calling setter>>> my_dog.nameCalling getter'Norita'>>> del my_dog.nameCalling deleter

🔹 How to work with files in Python

Working with files is very important for creating powerful programs. Let's see how you can do this in Python.

How to read files in Python

In Python it is recommended to use acomInstruction for working with files because it only opens them when we need them and automatically closes them when the process is finished.

To read a file we use this syntax:

mit open("<file_path>") as <file_var>: <code>

We can also indicate that we want to open the file in read mode with a"r":

mit open("<file_path>", "r") als <file_var>: <code>

However, this is already the default way to open a file, so we can omit it as in the first example.

This is an example:

with open("famous_quotes.txt") as file: for line in file: print(line)

or...

with open("famous_quotes.txt", "r") as file: for line in file: print(line)

💡 Tip:that's right! We can iterate through the lines of the file using a for loop. The file path can be relative to the running Python script or an absolute path.

How to write to a file in Python

There are two ways to write to a file. You can replace the entire content of the file before adding new content or appending to existing content.

mit open("<file_path>", "w") als <file_var>: <code>

To fully replace the content, we use the"W"mode, then we pass that string as the second argumentopen mind(). we call them.write()method on the file object passing the content we want to write as an argument.

For example:

words = ["Amazing", "Green", "Python", "Code"]with open("famous_quotes.txt", "w") als Datei: für Wort in Worten: file.write(word + "\n" )

When running the program, a new file will be created if it does not already exist in the path we specified.

This will be the content of the file:

AmazingGreenPythonCode

How to append to a file in Python

However, if you want to append the content, you must use the"an"Way:

mit open("<file_path>", "a") als <file_var>: <code>

For example:

words = ["Amazing", "Green", "Python", "Code"]with open("famous_quotes.txt", "a") als Datei: für Wort in Worten: file.write(word + "\n" )

This small change keeps the file's existing content and adds the new content at the end.

If we run the program again, these strings will be added to the end of the file:

AmazingGreenPythonCodeAmazingGreenPythonCode

How to Delete a File in Python

To delete a file with our script, we can use theosModule. It is recommended to check if the file exists before calling with a conditionextinguish()Function of this module:

import osif os.path.exists("<file_path>"): os.remove("<file_path>")else: <code>

For example:

import osif os.path.exists("famous_quotes.txt"): os.remove("famous_quotes.txt")else: print("This file does not exist")

You may have noticed the first line that saysimport-us. This is an import statement. Let's see why they're useful and how you can work with them.

🔸 Import statements to Python

As your program grows in size and complexity, it's a good idea to organize your code into multiple files. But we need to find a way to combine these files for the program to work properly, and that's what the import statements do.

By writing an import statement, we can import a module (a file that contains Python definitions and instructions) into another file.

These are different alternatives for import statements:

First alternative:

import <Modulname>

For example:

import math

💡Principal:mathis an integrated Python module.

When we use this import statement, we need to add the module name before the name of the function or element we refer to in our code:

>>> Import math >>> math.sqrt(25)5.0

In our code, we explicitly mention the module the element belongs to.

Second alternative:

import <module> as <new_name>

For example:

import math as m

In our code, we can use the new name we gave it instead of the module's original name:

>>> Import math as m >>> m.sqrt(25)5.0

Third alternative:

from <module name> import <element>

For example:

math import sqrt

With this import statement, we can call the function directly without specifying the module name:

>>> from math import sqrt>>> sqrt(25)5.0

Fourth alternative:

from <module name> import <element> as <new_name>

For example:

aus math import sqrt als square_root

With this import statement we can assign a new name to the element imported from the module:

>>> de math import sqrt as square_root >>> square_root(25)5.0

Fifth alternative:

import from <module name> *

This statement imports all module elements, and you can reference them directly by name without specifying the module name.

For example:

>>> from math import *>>> sqrt(25)5.0>>> fatorial(5)120>>> floor(4.6)4>>> ggT(5, 8)1

💡Principal:This type of import statement can make it more difficult for us to know which elements belong in which module, especially when we are importing elements from multiple modules.

MarPython code style guide:

Wildcard-Importar(from <module> import *) should be avoided as it does not make it clear what names are in the namespace, confusing readers and many automated tools.

🔹 List and dictionary comprehension in Python

A really cool Python feature to be aware of is list and dictionaries comprehension. This is just a way to make lists and dictionaries more compact.

List comprehension in Python

The syntax used to define list comprehensions generally follows one of four patterns:

[<value_to_include> to <var> in <sequence>]
[<value_to_include> to <var1> in <sequence1> to <var2> in <sequence2>]
[<value_to_include> to <var> in <sequence> if <condition>]
[<value> to <var1> in <sequence1> to <var2> in <sequence2> if <condition>]

💡 Tip:You should only use them if they don't make your code difficult to read and understand.

Here we have some examples:

>>> [i to i in the interval (4, 15)][4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]>>> [chr(i) to i in o range(67, 80)]['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M ' , 'N', 'O']>>> [i**3 for i in the interval (2, 5)][8, 27, 64]>>> [i + j for i in the interval ( 5, 8 ) for j in the range (3, 6)][8, 9, 10, 9, 10, 11, 10, 11, 12]>>> [k to k in the range (3, 35) if k % 2 == 0 ][4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34]>>> [i * j for i in interval (2, 6 ) for j in the range (3, 7) if i % j == 0][9, 16, 25]

List comprehensions versus generator expressions in Python

List comprehensions are defined with square brackets[]. This differs from generator expressions, which are defined with parentheses(). They look alike but are very different. Let's see why.

  • list comprehensionGenerate the entire sequence at once and store it in memory.
  • generator expressionsIssue items one at a time as they are requested.

We can verify this withsystemModule. In the example below you can see that their size in memory is quite different:

>>> import sys >>> sys.getsizeof([i for i in range(500)])2132>>> sys.getsizeof((i for i in range(500)))56

We can use generator expressions to iterate through a for loop and get the elements one by one. But if we need to store the items in a list, we must use list comprehension.

Dictionary understanding in Python

Now let's dive into understanding the dictionary. The basic syntax we need to use to define a dictionary comprehension is:

{<key_value>: <value> para <var> in <sequence>}
{<key_value>: <value> for <var> in <sequence> if <condition>}

Here are some examples of dictionary comprehension:

>>> {num: num**3 for num in range(3, 15)}{3:27, 4:64, 5:125, 6:216, 7:343, 8:512, 9:729, 10 : 1000, 11:1331, 12:1728, 13:2197, 14:2744}>>> {x: x + y for x not interval (4, 8) for y not interval (3, 7)} {4: 10, 5:11, 6:12, 7:13}

This is an example with a condition in which we take an existing dictionary and create a new dictionary with only students who obtained a minimum score of 60 points:

>>> grades = {"Nora": 78, "Gino": 100, "Talina": 56, "Elizabeth": 45, "Lulu": 67}>>> aprovad_alunos = {student: grade for (student, grade ) in grades.items() wenn Grade >= 60}>>> aprovad_students{'Nora': 78, 'Gino': 100, 'Lulu': 67}

EUYes reallyI hope you enjoyed this article and found it helpful.Now you know how to write and work with the most important elements of Python.

Subscribe to my YouTube channeland keep following meTwitter to find more guides and coding tips. Discover my online coursePython Tutorials for Beginners: Solve 100+ Coding Challenges

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

PROPAGANDA

Python Code Samples - Sample Script Coding Tutorial for Beginners (3)
Estefânia Cassingena Navone

Developer, technical writer and content creator @freeCodeCamp. I manage the YouTube channel freeCodeCamp.org Español.

If you've read this far, tweet the author to show you care.

Learn to program for free. freeCodeCamp's open source curriculum has helped over 40,000 people find developer jobs.Starting

PROPAGANDA

Top Articles
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated: 02/04/2023

Views: 6507

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.