Python For Beginners In Just One Day
If you work in the IT business, you've undoubtedly heard of Python. In recent years, Python's popularity has skyrocketed, and everyone is talking about it. As a consequence, regardless of your position, you are likely aware of what it is. Have no anxiety, we will cover everything. This one-day workshop will teach novices Python.
So, what exactly is Python?
Python, as you are probably aware, is a programming language. Python, on the other hand, is one of the most adaptable programming languages.
Python's primary advantage is its ease of use. In reality, writing Python code is a breeze. Obviously, this has an impact on Python's performance in comparison to other languages, but it isn't a problem for non-CPU-intensive activities. Aside from that, you can send Python commands to your computer while you're on the go. You can save Python code in files and run it later, or you can create an entire application. Python's adaptability allows it to be used for virtually any purpose. You can write a simple script or a complex application.
Python is also compatible with the operating systems Linux, Windows, and Mac. It is also Android-compatible! It is open source and works with a variety of programming languages. Its community is so large that you will receive all of the assistance you require.
Python's extensive feature set makes it an excellent choice for network automation. Python makes it easier to write code that automates the configuration of network equipment such as switches and routers.
Python for Beginners in a Single Day
The Primary Objective
Python is popular due to its ease of use. The question is, how hard is Python? When will I be able to begin writing code? We believe you can start in one day, as the title suggests. Obviously, this does not imply that you will be able to master Python in a single day; it will take time. You will gain the knowledge required to comprehend intermediate and advanced concepts. Most importantly, after reading this book, you will be able to write core Python programs.
Table of Contents
Here’s what we are going to cover today:
- What will I be able to accomplish now that I've read this guide?
- Starting with Python Installing Python 3
- Python 3 Installation on Linux
- Python 3.x and Python 2.7
- The Python Console
- Creating and Running Python Scripts
- Get cracking with Python for Beginners
- The “magic” Python Machine
- The Variable
- Variable Types
- Conditional Expressions
- The Selection Statements
- Something more about Python Syntax
- Looping Statements
- Collections
- Conclusion
What will I be able to accomplish now that I've read this guide?[ps2id id='What will I be able to accomplish now that I've read this guide?' target=''/]
Understanding the fundamentals of Python coding is extremely beneficial. You will be able to write scripts that... after completing this lesson.
Data sets are analyzed and modified using tables.
Locate a specific value in a set of data.
carries out some mathematical calculations
Take the user through a procedure (e.g. guided input)
This is an excellent starting point. You will also learn how to use files and load and save data in subsequent sessions. You'll be able to handle Excel files or images and automate activities on them with a little more knowledge!
Starting with Python Installing Python 3[ps2id id='Starting with Python Installing Python 3' target=''/]
If you want to learn Python for Beginners in 1 Day, you have probably never written Python code before. As a result, it is prudent to begin on a positive note. We will also install the most recent Python version, so you won't have to worry about script portability or compatibility.
Because Python is pre-installed on the vast majority of Linux distributions, this step is likely unnecessary. If your distribution is extremely light, you may need to install it. It is only available for Windows.
Python 3 Installation on Linux[ps2id id='Python 3 Installation on Linux' target=''/]
Python 3 installation on Linux is incredibly simple, requiring just one command. Download it using your package manager, such as Aptitude or Yum. On Ubuntu-based systems, for example, you may run this command.
sudo apt-get python3
Note that some versions of Linux may have Python 2.7 (simply
python
) installed, but not Python 3. Just to be sure, try to install it anyway.
Installing Python 3 on Windows
Python is not pre-installed on Windows, so you will need to download it. Go to the Python project's download page, which will detect that you are using Windows. It will recommend that you download the most recent Python 3 or Python 2 version (2.7). Simply download Python 3.x, as shown in the screenshot.
Download Python for Windows (version 3). (version 3).
This will result in the download of an executable installer. Run it with administrator access and leave all settings alone. This will adequately configure Python on your PC.
Read More: How to Download WhatsApp Status Videos: WhatsApp Status Images and Videos from Internet
Python 3.x and Python 2.7 are both supported.[ps2id id='Python 3.x and Python 2.7 are both supported.' target=''/]
Before we begin our "python for beginners" trip, we must first realize why there are two separate Python versions. Python 2.7 programs are not always compatible with Python 3 and must be rebuilt.
Python 2 witnessed a huge jump in Python's growth, as well as notable advances. But, as with all wonderful things, it has to come to an end. To continue evolving and progressing ahead, the Python team adopted a completely new base, Python 3. Python 2's final version (Python 2.7) was developed alongside Python 3, although this was only temporary. Python 2.7 will be termed "end of life" in January 2020. There will be no further updates or security fixes. Simply use Python 3.
As a result, with our Python for Beginners course, we meant to help you on that road. In reality, you won't have to worry about anything if you start employing Python 3 right now. You won't have to depend on modules that haven't yet been ported to Python 3, nor will you be constrained to Python 2. You will just be beginning started in the new era.
Python's Console[ps2id id='Python's Console' target=''/]
The Python Console is the ideal location to start studying Python. This is basically a tool for fast doing Python commands. In other words, you input a Python command and hit enter. The console will run it and report the result (or an error if the command is incorrect) (or an error if the command is invalid).
The Python console may be quickly started from the Prompt. Simply start the Terminal program on Linux. Simply start Windows' command prompt.
Windows Command Prompt
It is simple to access the command prompt on Windows. To begin, tap the Windows key and R at the same time to start the Run utility. Enter cmd here and hit enter. The command prompt will appear quickly.
How to start the Command Prompt or Windows.
From there, we will utilize the Python console. Just continue reading.
Launching the Python Console
Simply put python at the box and press enter. If you're using Python 3 on Linux, use python3 instead. The prompt will launch the console and show the Python version presently in use. Then you'll see three angle brackets, which you may use to insert Python commands.
An example of Python 3.6 console.
Python for Beginners in the Console
You can quickly write something that Python understands in the Python console. For instance, try typing a number and pressing enter. Python will print the same number once more. The reason for this is straightforward: Python will attempt to find the value of the expression you typed. Thus, if you type a number – a very simple expression – Python will respond with the number's value.
>>> 5
5
Of course, Python can evaluate mathematical operations like in the example below.
>>> 5 + 4
9
And even use parenthesis…
>>> (5 + 4) * 2 - 1
17
Like with any programming language, use only curved brackets in mathematical expressions. Squared and curly brackets have a different meaning in Python, as we will see later. For example, this mathematical expression…
Will translate to
((4*2)+1)*8
in Python. If you are not much into math, don’t worry about that right now.
Python Console can also work with pieces of texts, if you include them in quotes. For example, you can repeat a piece of text several times, like in the example below.
>>> "Hello " * 5 + "World!"
'Hello Hello Hello Hello Hello World!'
Python Scripting and Execution
Python is a sophisticated programming language that improves with each line of code you write. In practice, sending an encrypted file over the Internet requires more code than simply saying "Hello World." Actually, you don't want to type the entire code every time, but rather save it for later use. That is not possible in the Python Console, which is designed for use in real time.
What you can and should do is create a Python script. Simply copy and paste some Python code into Notepad (or, even better, Notepad++) and save it as a Python file. After that, you can run your Python file whenever you want. Your code will be finished and ready to go.
Create Your First Python Script[ps2id id='Create Your First Python Script' target=''/]
You've most likely heard about Notepad++. It is much superior than Notepad for script building since it colors the text to indicate Python syntax. We discussed all of the reasons why you should use Notepad++ as well as where you can acquire it. If you don't believe you have time, just use Notepad.
Python evaluates the expression you type into the Python Console and shows the result on the screen. When writing a script, you must explicitly tell Python when you want it to print anything on the screen. Here's an example of a script that doesn't work:
"Hello, World!"
If this had been ran on the console, the message Hello, World! would have shown. When creating a file, this is not the case. Instead, we have the right version, which includes the print command, which instructs Python to show the text. We utilize the print function to do this.
print("Hello, World!")
Thus, write
print("Hello, World!")
in notepad and then save the file with the Python extension, which is .py. If you use .txt, it won’t work. To do that, when saving, write .py at the end of the name of the file. However, you must change the Save as format from TXT to “All files”. Here we have an example in the screenshot below.
Saving a Python Script.
Now we need to execute this script
Executing a Python Script (from a file)
In this Python for Beginners lesson, we'll run Python programs from files. As a result, you must comprehend how to carry them out. Simply return to the prompt to complete this task.
If you have the Python console still open, close it by typing
exit()
. This special function can terminate a Python script, including the console itself. Now, use the cd command to navigate to the location of your script. For example, my script is in C:\Users\aless\Desktop, so I am going to type cd "C:\Users\aless\Desktop"
and press enter. This will position the prompt to the new location (cd stands for Change Directory).
At this point, I can write
python myscript.py
to run the Python script. Of course, you need to specify whatever the name of your file was. Here’s what will happen.
C:\Users\aless\Desktop>python myscript.py Hello, world!
Now we are all set to create and run complex scripts! Our real Python for Beginners tutorial can start!
Get cracking with Python for Beginners[ps2id id='Get cracking with Python for Beginners' target=''/]
The “magic” Python Machine[ps2id id='The “magic” Python Machine' target=''/]
Before you begin, take a time to consider a Python script. Consider a script to be a magical machine that accepts input and returns enhanced data. A Python script, like a factory, takes some input and generates something completely different.
A quick info on the Syntax
We'll go over Python syntax in more detail later, but for now, remember this:
Writing an instruction every line is critical in Python. It is the only method Python knows where one instruction stops and the next one begins.
The Variable[ps2id id='The Variable' target=''/]
Take your time reading now. Variable is a concept common by all programming languages that, if understood, may be applied to any programming language.
A variable is a kind of container or placeholder. You write code that use placeholders rather than values. When you run the code, you assign these placeholders a value and perform actions on them.
A variable is a memory location in which data may be stored. But, because this is a Python for Beginners course, we don't have to worry about it, do we? Variables may be seen as boxes because we conceive of them as containers.
As you can see, this code takes the variable named
input
and multiplies it by 5, storing this result in a variable named temp
. Then, it adds 2 to this value, and store this result in a final_result
. Presumably, it will print out the variable final_result
later on in the code.
Using Variables
To make the concept of Variable clearer, we can give you an example of Python code that uses variables. Below, a common example of code that inserts a variable in a phrase.
name = "John"
salutation = "Hello"
print(salutation + ", " + name + ".")
With these values, this script will write to the screen “Hello, John.”. The same string can give different results if you change the name and/or the salutation.
Getting variable values at Runtime
The runtime is the point at which your script is being executed. If you understand the notion of variables, you realize that the script below makes no sense. You're using variables because their values may vary depending on input data, but what's the purpose if you hardcode their values in the script? None, you are correct. You should load variable values from a file or ask the user.
To ask Console Input, use the
input()
function. With this function, you have to specify a some text used to ask the user for a variable. So, here we have a more meaningful example.
name = input("What is your name? ")
salutation = input("What salutation would you like? ")
print(salutation + ", " + name + ".")
This is what it will look like if we run this script.
What is your given name? Albert
Which greeting do you prefer? Hello and good morning.
Good day, Albert.
In the first two lines, we have provided both
Albert
and Good Morning
and pressed Enter.
Naming variables
When naming a variable, you may use capital and lowercase characters, as well as underscores and numbers. Other characters are not allowed, including spaces. Of course, Python keywords like print, and, or, and not are not permitted.
However, follow Python's best practices: variable names should only include lowercase characters, underscores, and integers if absolutely essential. The only exception is that capital letters may be used to form an acronym. Make names that are also self-explanatory: you want to remember what a variable will contain.
Read More: Subnetting fundamentals: What is a Subnet?
Variable Types[ps2id id='Variable Types' target=''/]
Python is a programming language with limited type support. This means that the variables are not type-bound. In other words, you may put a number in a variable and then add text to it. After a while, you may even return to something more complex, such as a file handler. Even because variables may store anything, you must take care while dealing with other variables.
A variable may be classified as simple or complicated. We'll look at complicated types later; for now, just concentrate on basic kinds:
- String – a piece of text
- Number – I think anybody gets this
- Boolean – a special variable that can be either
True
orFalse
, useful for flags
No matter the type, a variable can be valued to
None
, which indicates that it has no content.
Be careful with variables
Now, the fun part is being careful. If you have a string that contains something that could look like a number, Python won’t care. For Python, it is going to be a string. So, here’s what happens:
>>> "5" * 4
'5555'
As you can see, Python didn’t check inside the quotes. It assumed “oh, this must be text” and treated it like that. If you want to convert it to a number, you can use the
int()
function if the number is an integer (no decimals). So here we have a working example.
>>> int("5") * 4
20
Of course, in case we pass a string which cannot be converted in a number, this will result in an error.
Remember: strings must be enclosed in quotes
'
or double quotes "
.
Types and the Console
All of this is critical because, unless you convert them, Console input variables will be strings. How should this be done? It is incredibly easy, and reading the following script will make you wonder, "Oh, why didn't I think of it on my own?"
variable = int(input("Tell me a number: "))
The true meaning of “=”
The equal sign is a strong instruction for assigning a value to a variable. When using it, keep in mind that it will always perform what is on the right first. This makes perfect sense. If you want to change the value of a variable, you must first compute it.
If you use static assignment, this isn't anything to think about. However, if you ask the user to enter input via the console, you should keep this in mind. Python, in reality, processes instructions from the top down. The input function will halt execution until the user enters some data and presses enter. This may not be an issue for novice scripts. Even though this is a tutorial for "python for beginners," we want you to see the big picture, so simply know it.
More on the top down – swapping two variables
Take a look at the following code.
a = 5
b = 8
# Swap
a = b
b = a
Awesome, isn’t it? Well, sadly – no. Even if this code is simple and beautiful, it won’t work. This is true because, as always instructions are executed from the top down. Therefore, the first line assigns to
a
the value of b
. Thus, at this point both a
and b
are valued 8. When you execute the last instruction, you assign the new value of a
(8) to b
. As a result, you end up with both variables with the value of b
, which is useless. You need to rely on a temporary variable.
a = 5
b = 8
# Swap
# This to make sure we don't lose the value of a
temp = a
a = b
# Recovering the value of a
b = temp
Conditional Expressions[ps2id id='Conditional Expressions' target=''/]
Doing thins in order is beneficial, believe me. However, it will not answer any issues other than mathematical ones. We need to delve a little deeper, and conditional expressions will help us achieve so.
A conditional expression is one that, when evaluated, returns either True or False.
We'll be using them a lot in our scripts, but we can test them using the console. So, simply restart the console!
The simplest expressions
As always in this python for beginners tutorial, we start from the simplest route. The simplest expressions are comparisons: they compare two items. Are they equal? Fine, the expression will be
True
, otherwise, it won’t.
>>> "John" == "Ben"
False
>>> "John" == "John"
True
As you can see, to compare two items we put an operator in the middle. Here we all the common operators in Python.
==
translates to “equals“, we couldn’t use a single=
because that symbol is used for variable assignment!=
translates to “not equals”, the opposite of==
>
stands for greater than, and it returns True in case the first item is greater than the second<
stands for smaller than, and it returns True in case the first item is smaller than the second>=
and<=
are respectively greater or equal than and smaller or equal than
Of course, besides
==
, those operators make sense with numbers only (at least at a beginner level). To that, we can add the is None
operator, that returns true in case a variable has no value.
Combining expressions
Using a single expression might not be enough. You might need to create a condition that evaluates multiple variables at once, in a specific order. You can use the following logical operators to join together multiple conditions.
and
returnsTrue
if both conditions are trueor
returnsTrue
if at least one condition is truenot
returns the opposite value of the condition written afterwards
Use parenthesis as needed to evaluate some conditions before some others. Here we have a few examples.
>>> 5 > 6 or 1 >= 0
True
>>> 5 > 6 and 1 >= 0
False
>>> 5 > 6
False
>>> not 5 > 6
True
>>> name = "John"
>>> surname = "Doe"
>>> (name == "John" and surname == "Doe") or (name == "Walter" and surname == "White")
True
>>> (name == "John" and surname == "White") or (name == "Walter" and surname == "Doe")
False
Tip: as you can see, you can define variables on the go in the console too.
The Selection Statements[ps2id id='The Selection Statements' target=''/]
A selection statement (or conditional statement) is a piece of code that may be executed, or may be not, according to input that. Specifically, based on the input data, Python will select to do something or something else.
It sounds a lot like “if this… then that”, and it is exactly that. We have three major keywords to use:
if
, elif
and else
.
The “if” statement
if <condition>:
<instruction to execute if True>
...
<this will be executed no matter what>
This is extremely simple. If the condition is written after the if is true, Python will execute the instructions inside the if. Otherwise, it won’t. What are the instructions inside the if construct? The ones that are tabulated inside. Remember this, as Python is entirely based on tabulation. Take a look at the following example.
title = input("What is your title? ")
name = input("What is your name? ")
if title == "Dr.":
print("Welcome home, Doctor.")
print("Good morning, " + name + ".")
In this case, the instruction
print("Welcome home, Doctor")
is inside the if. All other instructions are outside. If you want to add more instructions inside the if
, just add them with the same tabulation.
The “elif” statement
if <condition 1>:
<instruction to execute if condition 1 is True>
...
elif <condition 2>:
<instruction to execute if condition 1 is False AND condition 2 is True>
...
The
elif
statement is simple. You can use it in conjunction with if, and you can concatenate multiple of them. In case the first if
(and the previous elifs, if any) returned false, the condition in this elif
will be evaluated. In case it’s true, the code inside will be executed. Take a look at this example.
title = input("What is your title? ")
name = input("What is your name? ")
if title == "Dr.":
print("Welcome home, Doctor.")
elif title == "Mr.":
print("It is a pleasure to have you back home, Sir.")
elif title == "Mrs.":
print("Glad to see you home, milady")
print("Good morning, " + name + ".")
Of course, you cannot use the elif construct alone.
The “else” statement
if <condtion>:
<do that if true>
else:
<do that if not true>
This statement is the last in the selection statements belt. Its operation is simple and natural: it acts like a catch-all expressions, to be executed if no if or elif construct were true. Of course, the content of the else statement will be executed only in case no if/elif in the same group was executed. Here we have our complete example.
title = input("What is your title? ")
name = input("What is your name? ")
if title == "Dr.":
print("Welcome home, Doctor.")
elif title == "Mr.":
print("It is a pleasure to have you back home, Sir " + name + ".")
elif title == "Mrs.":
print("Glad to see you home, milady " + name ".")
else:
print("Dear " + name + ", I guess I didn't get your title right.")
Something more about Python Syntax[ps2id id='Something more about Python Syntax' target=''/]
Many programming languages use semi-colons and parentheses to separate sets of instructions. Python doesn’t, it uses colons and indents. That’s for a reason: it forces you to write code with indentation, which is much easier to read. You need to remember two things:
- A colon at the end of the line means that an indented block of at least one line is expected to start from the next line. As you can see, if, elif and else all ends with a colon. This is because they need some extra instructions afterward in order to work.
- A set of python code with the same indent level is a block of code, which will be executed sequentially
There’s more about Python Syntax, but not for this Python for Beginners course. However, one thing you should know are comments. A comment is a note left in the code for other programmers to read (or even for yourself). Python will simply skip it, as the computer doesn’t need it.
In Python, you write
#
and then everything from that to the end of the line is a comment. Here we have an example.
name = input("What is your name?" ) # Here we ask for the name
salutation = input("What salutation would you like?" ) # Here we ask for a salutation
# Below we print the phrase adapted to the user
print(salutation + ", " + name + ".")
Loop statements[ps2id id='Loop statements' target=''/]
A loop is a repetition of something, isn’t it? If you are going to do the same set of operations over a large set of variables, loops are the way to go. We have two key loops in Python, the
while
and the for
.
If you do something wrong, your script may be stuck in an endless loop. To terminate the execution, hold Ctrl+C for a few seconds.
Looping with “while”
while <condtion>:
<execute something>
This loop is quite basic, and very versatile. Python evaluates the condition, and if it is True it executes the code inside. After that, it evaluates the condition again. Only when the condition is false, it will stop executing the code inside the loop. Here we have an example.
correct_password = "supersecret"
password = input("Please insert your password: ")
while password != correct_password:
password = input("Wrong password. Insert correct password: ")
print("Welcome, you are authenticated.")
As you can see, this script will ask for a password. The
while
instruction will evaluate if it is correct by comparing it with the correct_password
variable. In case it is not correct, it will start asking for the password again, until the user inserts the correct password. Of course, this is not a great security mechanism, but it explains the concept of loop.
The “for” loop
This special loop allows you to work on a set of values, known as collections. We will see that later when talking about lists. For now, just think you can use it to repeat an instruction N times.
times = int(input("How many times? "))
for i in range(times):
print("Time #" + str(i))
This script will repeat the instructions in the block for the times specified. Note the keyword
i
. That’s a variable, and you could use whatever the name you want. Every time the loop executes the block of code, it will increment the value of i
, that will start from 0
and end at times-1
. So, the output will be this:
How many times? 4
Time #0
Time #1
Time #2
Time #3
Read More: The best VoIP service in 2021, Recreate a conventional office phone at home: Best VoIP Providers in the United States in 2022
Collections[ps2id id='Collections' target=''/]
Without collections, your script would not advance. Even if you are a novice, you should be acquainted with them. This is why we include collections in our Python for Beginners course.
What exactly is a collection?[ps2id id='What exactly is a collection?' target=''/]
Here's a wonderful definition.
A collection is a complex type with several values.
A collection, in other words, is a kind of sophisticated variable. It is composed of several sorts, fundamental types, and even collections. Everything may seem a bit too abstract at this point. It isn't, and the two types of collections we'll encounter will show you why.
Lists[ps2id id='Lists' target=''/]
A list is the most basic kind of collection. It's a list of things, as you would expect. You might, for example, mention your pets. Python lists are surrounded in square brackets, with a command between each item. For example, if I had three pets called Bobby, Pluto, and Bertha, this would be a list of their names.
["Bobby", "Pluto", "Bertha"]
Of course, you can assign a list to a variable. Furthermore, you can populate lists dynamically.
Populating a list at runtime with “while”
Here’s what you need to do.
my_pets = []
more_pets = True
while more_pets:
add_pet = input("Would you like to add a pet? [y/N]" )
if add_pet == "y":
pet_name = input("Insert your pet's name: ")
my_pets.append(pet_name)
elif add_pet == "N":
print("You have added " + str(len(my_pets)) + ".")
more_pets == False
else:
print("Please write 'y' or 'N'.")
print(my_pets)
In the first line, we init the value of my_pets to an empty list. Therefore, we are starting the script with no pets. Then, we run a loop that asks every time to the user if he wants to add a pet. In case the user says so, we ask for the name. And this is where the magic happens.
By using the function
append()
of our list, we add the name as a last element to the list. One creat thing of Python lists, in fact, is that they can grow dynamically. You can simply add items as you wish, and you don’t need to define a size beforehand like in other languages.
If look close enough, in the
elif
statement, we used the len()
function. This returns the number of items currently in the list. Try to run this script on your own!
Looping though list items with “for”
As said before, the “for” loop is great when working on lists. In fact, it gives you an easy way to process each item in a list. For example, you can attach this code to the script we just created for adding pets.
for pet in my_pets:
print("I have a pet named " + pet + ".")
This simple snippet will loop through the list
my_pet
. It will start taking the first item in the list and putting its value into the pet
variable. Then, in the next cycle (after the print
statement), it will do the same with the second item. The for
loop will repeat this process until, eventually, all items are processed. Pretty much awesome, isn’t it?
Direct access to list items
If you know the locations of the items in a list, you can access them directly. Keep in mind that the initial position is always 0 and never 1. We now have the syntax.
first_pet = my_pets[0]
fourth_pet = my_pets[3]
If the list does not include an item at that place, an error will be returned, and the program will fail if the error is not handled. There is nothing to be concerned about in a python for beginners lesson.
With this approach, you are copying the variable from an item of the list to a variable. Thus, you are not removing it from the list.
A list of everything
A list may be made up of almost anything, not simply strings or integers. You may even mix and match various sorts. As a result, the list below is correct for Python.
["Pasta", "Pizza", ["Ribs", "Potatoes"], None, -1, "Water", False]
As you can see, the first two elements are strings, followed by a list, a None, an integer, another string, and a bool. Python is quite content with this.
Dictionaries[ps2id id='Dictionaries' target=''/]
Dictionaries and records may be compared. They indicate an entity that is not a list of components and cannot be defined by a single basic variable.
Consider how you may depict the concept of Contact Information. You want to know the kind of contact information (e.g., phone, mobile, e-mail), the value (e.g., the e-mail address itself), and the time at which you may contact them. This is when dictionaries come in handy. They are defined by surrounding them in curly brackets. Create key-value pairs within the brackets, with each pair separated by a comma. The key indicates what this is about (for example, the kind), and the value indicates the value of this key (for example, "mobile phone"). Each key is separated from its value by a colon. Here is one example.
"type" : "mobile phone",
"value": "+1 555 800 300 200",
"time range": "8:00am - 5:00pm"
Accessing the keys of a dictionary directly
Once you have a dictionary defined in a variable with
var = ...
, you can access its keys directly. You do that by referencing the variable followed by the key name between square brackets. Thus, if we stick to the example above, we can do something like this.
print(var["type"])
And this will print “mobile phone” to the screen. You can of course use this syntax not only to get the value, but the set the value as well. Furthermore, you can use the same syntax to define a new key on the fly.
var["key that did not exist before"] = "Yay!"
To make tables, combine lists and dictionaries.[ps2id id='To make tables, combine lists and dictionaries.' target=''/]
Tables are a wonderful way to display a broad variety of information. A table is made up of columns that are followed by rows that all have the same fields (one per column). Python allows you to create custom fields that are not shared by all rows but are unique to some of them. A list of dictionaries is the best approach to represent a table, regardless of what you do or how you do it. In the following example, we fill the contact list before allowing the user to search.
The big example that combines everything
# Start with no contacts
contacts = []
# Will loop until user explicitly interrupts it
loop_again = True
while loop_again:
print("1. Add contact")
print("2. Search for type")
print("3. Exit")
choice = input("What would you like to do? [1/2/3] ")
# Compare string, not number
if choice == "1":
# Adding a contact
# Creating a temporary variable
contact =
contact["type"] = input("Insert contact type: ")
contact["value"] = input("Value for this contact: ")
contact["hours"] = input("Insert availability hours: ")
# Add to the list of contacts
contacts.append(contact)
print("Contact added")
elif choice == "2":
# Searching contact
search_for = input("What would you like to search for? ")
# If not valid key, ask again
while search_for not in ["type", "value", "hours"]:
search_for = input("Please insert either type, value or hours: ")
search_value = input("What are you looking for exactly? ")
# We start without having a match
match = False
# Scan all contacts
for contact in contacts:
if contact[search_for] == search_value:
print(contact)
# We found it, so we set match to True
match = True
if match == False:
print("Sorry, no matches found")
elif choice == "3":
# We exit
loop_again = False
else:
print("Please write either 1, 2 or 3")
Conclusion[ps2id id='Conclusion' target=''/]
We got you up and running with Python and – hopefully – programming in this massive essay. Despite this, our Python knowledge is inadequate and, at times, ineffective. However, we now have a tool to help us improve our Python abilities, and we will be able to finish complicated jobs in no time.
We can now do rudimentary elaborations on data sets, however these data sets are restricted since we must manually enter data. In the next post, we'll begin working with files to make something helpful, such as a script that processes a matrix in an Excel-like fashion.
Then, we'll start adding additional Python tools and methods to your toolkit, so you'll be working with advanced concepts like decorators and custom iterators in no time. But that's all I have for now. A little practice goes a long way, and your brain will appreciate it!
Please, as always, share your comments on this topic. What motivates you to learn Python? What would you want to read in more depth? What are the difficulties you face when learning? Simply leave a comment to let me know!
Read More: Need an Hosting for WordPress? The Best WordPress Hosting Sites Providers in 2022
https://www.techguruhub.net/python-for-beginners-just-one-day/?feed_id=114207&_unique_id=641c888a701c2
Comments
Post a Comment