You are reading the article How To Use Else Statement With Loops In Python? updated in December 2023 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How To Use Else Statement With Loops In Python?
In this article, we will show you how to use else statements with loops in python.
Many of us are confused by the term else because else in an if-else condition makes sense, but an else for a loop? Weird! Python provides you with an additional feature with its loops.
Else with the loop is used with both the while and for loops. The else block is run at the end of the loop, which means that it is executed when the specified loop condition is false.
Syntaxfor loop with optional else clause
for variable_name in iterable: #stmts in the loop . . . else: #stmts in else clause . . Syntaxfor loop with optional else clause
while condition: #stmts in the loop . . . else: #stmts in else clause . . Using else statement with for loop in pythonIn other languages, the else functionality is only provided in if-else pairs. But Python allows us to implement the else functionality with for loops as well.
The else functionality is available for use only when the loop terminates normally. In case of forceful termination of the loop else statement is overlooked by the interpreter and hence its execution is skipped.
.
NOTE: When the loop is not terminated by a break statement, the else block immediately after for/while is executed.
Method 1: For-Else Construct with normal termination (without break statement) ExampleThe following program shows how to use the else statement with for loop −
(
i
)
else
:
(
“ForLoop-else statement successfully executed”
)
OutputOn executing, the above program will generate the following output −
T P ForLoop-else statement successfully executed Method 2: For-Else Construct with forceful termination (with break statement) ExampleThe following program shows how else conditions work in case of a break statement −
(
i
)
break
else
:
(
“Loop-else statement successfully executed”
)
OutputOn executing, the above program will generate the following output −
TExplanation
This type of else is only useful if there is an if condition inside the loop that is dependent on the loop variable in some way.
In Method 1, the loop else statement is executed since the for loop terminates normally after iterating over the list[‘T’,’P’]. However, in Method 2, the loop-else statement is not executed since the loop is forcedly stopped using jump statements such as break.
These Methods clearly show that when the loop is forcedly terminated, the loop-else expression is not executed.
Now consider an example in which the loop-else statement is performed in some conditions but not in others.
Method 3: For-Else Construct with break statement and if conditions ExampleThe following program shows how else conditions works in case of break statement and conditional statements −
def
positive_or_negative
(
)
:
for
i
in
[
5
,
6
,
7
]
:
(
“Positive number”
)
else
:
(
“Negative number”
)
break
else
:
(
“Loop-else Executed”
)
positive_or_negative
(
)
OutputOn executing, the above program will generate the following output −
Positive number Positive number Positive number Loop-else Executed Using else statement with while loop in python Else-While without break statementAlgorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task −
Initialized k value with 0.
Using a while loop to traverse until the specified condition is true(until k<8).
Incrementing the k value by 1, since we don’t want to execute the while loop infinite times.
Print k value.
Else block gets executed when the condition fails/becomes false i.e when the k value becomes 8.
ExampleThe following program demonstrates the use of the else statement in the while loop −
while
k
<
8
:
k
+=
1
(
“k =”
,
k
)
else
:
(
“This is an else block”
)
OutputOn executing, the above program will generate the following output −
k = 1 k = 2 k = 3 k = 4 k = 5 k = 6 k = 7 k = 8 This is an else block Using Else statement in While loop with a break statement ExampleThe following program shows how else conditions work in case of break statements of while loop −
def
hasEvenNumber
(
l
)
:
n
=
len
(
l
)
i
=
0
while
i
<
n
:
if
l
[
i
]
%
2
==
0
:
(
“The input list contains an even number”
)
break
i
+=
1
else
:
(
“The input list doesn’t contain an even number”
)
(
“For Input list 1:”
)
hasEvenNumber
(
[
3
,
9
,
4
,
5
]
)
(
“For Input list 2:”
)
hasEvenNumber
(
[
7
,
3
,
5
,
1
]
)
OutputOn executing, the above program will generate the following output −
For Input list 1: The input list contains an even number For Input list 2: The input list doesn't contain an even number ConclusionThis article taught us how to use Python’s else statements in for and while loops. Additionally, we learned how the break statement behaves in the event of an else statement.
You're reading How To Use Else Statement With Loops In Python?
How To Use Pprint In Python?
Introduction
Improve your Python output with the power of pprint! Properly formatted and visually appealing output can greatly enhance your code debugging experience. This article introduces pprint, a Python library that serves as a Data Pretty Printer. Whether you’re dealing with JSON files or working with dictionaries, pprint can help you handle large amounts of data more effectively. Say goodbye to messy outputs and confusing structures. Best of all, pprint is an inbuilt Python library, so no separate installation is required. Let’s dive in and make your outputs shine!
This article was published as a part of the Data Science Blogathon.
What is pprint()?It stands for “Pretty Print”, and is one of the native Python libraries that allows you to customize your outputs with its numerous parameters and flags for its single class pprint(). Here is the official documentation to list all of its properties and usage.
pprint() ParametersThe library contains just a single class, called pprint(). There are in total six parameters that can be used with this class. Here is a short description of the parameters along with their default values:
indent: The number of spaces to indent each line, this value can help when specific formatting is needed. Default value = 1
width: Maximum characters that can be in a single line. If the number of words exceeds this limit, the remaining text will be wrapped on the lines below. Default value = 80
depth: The number of depth levels to be shown while using nested data types. By default, it shows all the data, but if specified, the data beyond the depth level is shown as a series of dots ( . . . ). Default value = None
stream: This is used to specify an output stream and is mainly used to pretty print a file. Its default behavior is to use sys.stdout. Default value = None
compact: This is a boolean argument. If set to True, it will consolidate complex data structures into single lines, within the specified width. If the value is the default (ie. False) all the items will be formatted on separate lines. Default value = False
sort_dicts: This is also a boolean argument. While printing dictionaries with pprint(), it prints the key-value pair sorted according to the key name alphabetically. When set to false, the key, value pairs will be displayed according to their order of insertion. Default value = True
Now enough with the technical stuff, let’s jump into the programming part!
Basics of pprint()First, we import the pprint module at the beginning of our notebook.
import pprintNow you can either use the pprint() method or instantiate your pprint object with PrettyPrinter().
Now let us create a sample dictionary to demonstrate some of the arguments of the class pprint().
sample_dict = { 'name': 'Sion', 'age': 21, 'message': 'Thank you for reading this article!', 'topic':'Python Libraries' }If we simply print out this dictionary using print, what we get is:
{'name': 'Sion', 'age': 21, 'message': 'Thank you for reading this article!', 'topic': 'Python Libraries'}Now that doesn’t look much appealing, does it? But still one might argue that this output format is okay since you can clearly see which value belongs to which key, but what happens if these values are extremely long, and nested. Or if the volume of our key-value pairs is much much more? That’s when it all goes downhill. It will become very very difficult to read, but worry not, print to the rescue:
pprint.pprint(sample_dict)Firstly, all the pairs have their separate row, which increases the readability tenfold. Also if you look closely, all the elements are automatically sorted according to the keys.
The pprintpp ModuleAlso Read: How to Read Common File Formats in Python – CSV, Excel, JSON, and more!
Text WrappingImage Source: Elle
Most people might know the basics that I showed above. Now let’s use some of the other parameters to further customize our outputs.
Another basic usage is text wrapping. Suppose you are not satisfied by just printing the key-value pairs on separate lines, but want to have the text wrapped when the length of the line exceeds a certain amount. For this, we can use the width parameter.
pprint.pprint(sample_dict, width = 30)Apart from this, we can use the indent parameter to add indentation in front of each row for better readability.
pprint.pprint(sample_dict, width = 30, indent = 10)Here is an example for the usage of compact and width parameters:
import pprint stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] stuff.insert(0, stuff[:]) pp = pprint.PrettyPrinter(indent=4) pp.pprint(stuff) pp = pprint.PrettyPrinter(width=41, compact=True) pp.pprint(stuff) Deep Nested ObjectsImage Source: Missouri Dept. of Conservation
Sometimes while working with highly nested objects, we just want to view just the outer values and are not interested in the deeper levels. For example, if we have a nested tuple like this:
sample_tuple = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',))))))))Now if we use print or print, the outputs will be almost similar:
print(sample_tuple) > ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))) pp.pprint(sample_tuple)However, if the depth parameter is specified, anything deeper than that will be truncated:
pprint.pprint(sample_tuple, depth=2) pprint.pprint(sample_tuple, depth=1) p = pprint.PrettyPrinter(depth=6) p.pprint(sample_tuple) pprint() vs PrettyPrinter()The difference between these two is that the pprint() method uses the default arguments and settings of the libraries, which you can change like we previously saw, but these changes are temporary.
With PrettyPrinter(), you can create a class, with your own specifications and override the default settings to create permanent class objects which retain their forms and values all over your project.
import pprint coordinates = [ { "name": "Location 1", "gps": (29.008966, 111.573724) }, { "name": "Location 2", "gps": (40.1632626, 44.2935926) }, { "name": "Location 3", "gps": (29.476705, 121.869339) } ] pprint.pprint(coordinates, depth=1) > [{...}, {...}, {...}] pprint.pprint(coordinates)As you can see, the arguments supplied were just temporary. Conversely, these settings are stored with PrettyPrinter(), and you can use them wherever in the code you want, without any change in functionality:
import pprint my_printer = pprint.PrettyPrinter(depth=1) coordinates = [ { "name": "Location 1", "gps": (29.008966, 111.573724) }, { "name": "Location 2", "gps": (40.1632626, 44.2935926) }, { "name": "Location 3", "gps": (29.476705, 121.869339) } ] my_printer.pprint(coordinates) > [{...}, {...}, {...}] Conclusion Frequently Asked QuestionsQ1. What is Pprint used for?
A. Pprint (pretty print) is a Python module used for formatting complex data structures more readably and organized, especially when printing them to the console or writing to a file.
Q2. What is the difference between print and Pprint?
A. The main difference between print and Pprint is that Pprint is designed to format complex data structures such as dictionaries and lists, preserving their structure and providing indentation. In contrast, print is used for simple output of values or strings.
Q3. Is Pprint standard in Python?
A. Pprint is not a standard built-in module in Python, but it is included in the Python Standard Library, meaning it is available by default in most Python installations.
Q4. Is Pprint native to Python?
A. Yes, Pprint is native to Python as it is included in the Python Standard Library, allowing developers to utilize its functionality without needing external dependencies or installations.
ReferencesThe media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.
Related
How To Use Vba On Error Statement In Excel?
VBA On Error Statements
VBA On Error is an easy method for handling unexpected exceptions in Excel chúng tôi is known that we cannot write code without any error. Sometimes writing big code may give us an error even at the time of compiling. To avoid this kind of situation, we add an Error Message which, instead of giving us the right answer or error code it will show us the message with the error code. That would look like we got the output of our calculation, but it is the error code that will get imprinted.
Watch our Demo Courses and Videos
Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.
How to Use Excel VBA On Error Statements in Excel?There are 3 ways of Error in VBA. Let’s understand different ways with some examples.
Example #1The first error type is a Code compilation error which comes when a code is undeclared or impossible variables. To understand more, we will use a simple mathematical expression of the divide. For this, go to the Insert menu of VBA and select Module as shown below.
Now open Subcategory and add any name as we are using On Error, so we have named it as same.
Sub
OnError()End Sub
Now define any 2 or 3 Integers. Here we have taking X and Y as Integers.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
End Sub
Now, as discussed above, we will calculate division mathematical expression. For X, we will put a character in Numerator and divide it 0. And Y will be 20/2, which is complete numbers.
Sub
OnError()Dim
XAs Integer
, YAs Integer
X = Test / 0 Y = 20 / 2End Sub
Now to overrule this error, we will add one line On Error Resume Next before we write the mathematical code. It will jump the error code, but we will not able to see the outcome of the second mathematical code. This only hides the error message of various codes lines, as shown below. Now try to run the code as well.
Sub
OnError()Dim
XAs Integer
, YAs Integer
On Error Resume Next
X = Test / 0 Y = 20 / 2 MsgBox X MsgBox YEnd Sub
Now to overrule this error, we will add one line On Error Resume Next before we write the mathematical code. It will jump the error code, but we will not able to see the outcome of the second mathematical code. This only hides the error message of various codes lines, as shown below. Now try to run the code as well.
Example #2In this example, we will consider that mathematical division which gives infinite result, but in coding, it will #DIV/0 result. To demonstrate this, we will consider one more integer Z along with X and Y in a subcategory, as shown below.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
End Sub
Now frame all the integers X, Y, and Z with a mathematical expression of divide and to print it use MsgBox function in VBA of each integer’s result.
Below for Integer X, we have divided 10 by 0, 20 by 2 and 30 by 4.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox ZEnd Sub
Now run the code using the F5 key or manually, as shown below.
As we can see in the above screenshot, Run-time error 11, which means the error is related to the number. Now to overcome this, add one line On Error Resume Next before mathematical expression as shown below.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
On Error Resume Next
X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox ZEnd Sub
Example #3
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
End Sub
Now also consider the same mathematical division which we have seen in the above example.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox ZEnd Sub
If we run the code, we will get the same error message of Run-time error 11.
Now to overrule this error, use text On Error GoTo with the word “ “Result to skip the error message and get the output which works fine, as shown below.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
On Error GoTo
ZResult: X = 10 / 0 Y = 20 / 2 ZResult: Z = 30 / 4 MsgBox X MsgBox Y MsgBox ZEnd Sub
Now run the code again. We will get the same result as the previous example.
On Error GoTo ZResult helps us to directly jump of mentioned result point integer as we did for integer Z.
Example #4In the third type of error, when we run the code and VBA is not able to understand the line of code. This can be done with the help of code On Error Resume Next along with MsgBox Err.Number. Consider the same data as used in the above examples. We will again see the same 3 integers X, Y, and Z, as shown below.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
End Sub
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox ZEnd Sub
Now, if we run the complete code, then we will get an error message of mathematical error Run time error 11.
Now to overrule this error, we will use On Error Resume Next.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
On Error Resume Next
X = 10 / 0 Y = 20 / 2 Z = 30 / 4 MsgBox X MsgBox Y MsgBox ZEnd Sub
And run the code. This will give a use result on a valid mathematical line, as shown below.
Now further add ZResult code line before Z integer division mathematical expression and add MsgBox Err.Number code line at the end of code as shown below.
Sub
OnError()Dim
XAs Integer
, YAs Integer
, ZAs Integer
On Error Resume Next
X = 10 / 0 Y = 20 / 2 ZResult: Z = 30 / 4 MsgBox X MsgBox Y MsgBox Z MsgBox Err.NumberEnd Sub
Now run the code by using the F5 key or by pressing the play button, as shown below.
As we can see in the above screenshots. The first message box has 0, which is overruling of incorrect mathematical expression. 2nd and 3rd have a division result of Y and Z integers. And last message box has run time error code 11, which is probably the error code of X integer’s division expressions.
Pros of VBA On Error
We can calculate any mathematical formula even if it is incorrect.
For bigger coding structures where there are chances of having an error, using these methods may give correct result even among the line of codes.
This gives a better result as compared to the result obtained from normal excel calculations.
Things to Remember
Always save the file in a Macro-Enabled Excel file so that we can use created VBA code many and multiple times.
Always compile the written code before implementing with any excel requirement.
You can download this VBA On Error Excel Template here – VBA On Error Excel Template.
Recommended ArticlesThis has been a guide to Excel VBA On Error. Here we discussed how to use VBA On Error Statement along with some practical examples and a downloadable excel template. You can also go through our other suggested articles–
How To Use For In Statement To Loop Through An Array In Javascript
We use the chúng tôi statement of JavaScript for looping over enumerable properties of an array or object. It is a variety of for loops. Unlike other loop constructs in JavaScript, the chúng tôi loop doesn’t have to bother about the number of iterations. This is because the iteration size is fixed based on the enumerable properties of the object or the number of elements in the array.
The “for…in” statement in JavaScriptA chúng tôi loop iterates over all the enumerable properties of an object. All the properties that are assigned using a simple assignment operator or by default initializer are considered enumerable properties.
Syntax for(var num in numbers){ }This creates a variable num that iterates over all the elements in the array numbers. This num takes on the index of the elements stored in the numbers array one by one.
Let’s see the working of chúng tôi loop with an example.
Example 1Here we will create an array of strings and then iterate over it using chúng tôi loop. Let’s look at the code for same.
var
arr
=
[
“xyz”
,
“abc”
,
“pqr”
]
;
var
text
=
“”
;
for
(
var
str
in
arr
)
{
text
+=
arr
[
str
]
+
“,”
;
}
document
.
getElementById
(
“result”
)
.
innerHTML
=
text
;
In the above code, the str takes on values 0,1 and 2 respectively which is used for retrieving the elements of the array.
The chúng tôi loop though usable, works pretty well with objects rather than arrays. This is because the loop variable takes on the value of keys one by one making the iteration of the object pretty easy.
Syntax for(var num of numbers){ }This creates a variable num that iterates over all the elements in the array numbers. This num takes on the value of the elements stored in the numbers array one by one.
Here’s an example of how to use chúng tôi loop with objects in JavaScript.
Example 2Here we will create an array of elements containing different data types. we will use the chúng tôi loop to iterate over that array.
var
arr
=
[
“Jane Doe”
,
2
,
59.57
]
;
for
(
var
ele
of
arr
)
{
}
document
.
getElementById
(
“result”
)
.
innerHTML
=
text
;
In the above code, as is visible in the output as well, the variable ele takes on the value of the elements present in the array.
We can also use the Array.prototype.forEach() method for traversing the array. The argument of forEach() is a function that is executed for all the elements of the array.
Syntax const arr = ["Jane Doe", 2, 59.57] arr.forEach(function fun(ele){ }Note that the “prototype” is replaced with the array’s name, which is arr in this case. The function fun has one argument ele which takes on the values of the elements stored in the array arr one by one.
Here’s an example of how to use the forEach() method with arrays in JavaScript.
Example 3Here we will create an array of elements containing different data types. we will use the forEach() method to iterate over that array.
Let’s look at the code for the same.
var
arr
=
[
“Jane Doe”
,
2
,
59.57
]
;
arr
.
forEach
(
function
fun
(
ele
)
{
}
)
document
.
getElementById
(
“result”
)
.
innerHTML
=
text
;
In the above code, as is visible in the output as well, the variable ele takes on the value of the elements present in the array.
ConclusionThe chúng tôi chúng tôi and forEach() constructs make our life easier by providing much-needed variations of the conventional for a loop.
What Is A Break Statement In Java And How To Use It?
This article will help you understand what the break statement in Java Programming language is.
Break StatementSometimes, it is needed to stop a look suddenly when a condition is satisfied. This can be done with the help of break statement.
A break statement is used for unusual termination of a block. As soon as you apply a break statement, the control exits from the block (A set of statements under curly braces).
Syntax for (condition){ execution continues if (another condition is true){ break; } Line 1; Line 2;Given below are some examples where Break statement is used.
Example 1 − Break Statement with Loop public class BreakExample1 { public static void main(String[] args){ int i; for (i = 0; i <= 10; i++) { System.out.println(i); if (i == 3){ break; } System.out.println("Output 1"); } System.out.println("Output 2"); } } Output 0 Output 1 1 Output 1 2 Output 1 3 Output 2 Example 2 − Break Statement with Inner Loop public class BreakExample2 { public static void main(String[] args) { int i,j; for (i = 0; i <= 5; i++) { for (j = 0; j <= 5; j++){ if (i == 3 && j == 3) { break; } System.out.println(i + " " + j); } System.out.println(); } } } Output 0 0 0 1 0 2 0 3 0 4 0 5 1 0 1 1 1 2 1 3 1 4 1 5 2 0 2 1 2 2 2 3 2 4 2 5 3 0 3 1 3 2 4 0 4 1 4 2 4 3 4 4 4 5 5 0 5 1 5 2 5 3 5 4 5 5 Example 3 − Break Statement with Labelled For Loop public class BreakExample3 { public static void main(String[] args) { Label1: for (int i = 0; i <= 5; i++) { Label2: for (int j = 0; j <= 5; j++) { if (i == 3 && j == 3) { break Label1; } System.out.println(i + " " + j); } System.out.println(); } } } Output 0 0 0 1 0 2 0 3 0 4 0 5 1 0 1 1 1 2 1 3 1 4 1 5 2 0 2 1 2 2 2 3 2 4 2 5 3 0 3 1 3 2 Example 4 − Break Statement in While Loop public class BreakExample4 { public static void main(String[] args) { int i = 0; while(i <= 10) { if (i == 5){ break; } System.out.println(i); i++; } } } Output 0 1 2 3 4 Example 5 − Break Statement in Do-while Loop public class BreakExample5 { public static void main(String[] args) { int i = 0; do {// start of do-while block if (i == 5){ break; } System.out.println(i); i++; } while(i <= 10); } } Output 0 1 2 3 4 Example 6 − Break Statement in Switch Case import java.util.*; public class BreakExample6 { public static void main (String[] args) { Scanner in = new Scanner(System.in); int i; System.out.println("Is 5 Greater than 3"); System.out.println("Option 1: Yes"); System.out.println("Option 2: No"); System.out.println("Enter Choice"); i = in.nextInt(); switch(i) { case 1: System.out.println("Correct Choice"); break; case 2: System.out.println("Incorrect Choice"); break; default: System.out.println("Invalid Choice"); } } } Output Is 5 Greater than 3 Option 1: Yes Option 2: No Enter Choice 1 Correct ChoiceI hope you have understood what the Break Statement in Java is. Thanks for reading the article.
Mysql Select Statement With Examples
What is SELECT query in MySQL?
SELECT QUERY is used to fetch the data from the MySQL database. Databases store data for later retrieval. The purpose of MySQL Select is to return from the database tables, one or more rows that match a given criteria. Select query can be used in scripting language like PHP, Ruby, or you can execute it via the command prompt.
SQL SELECT statement syntax
It is the most frequently used SQL command and has the following general syntax
HERE
SELECT is the SQL keyword that lets the database know that you want to retrieve data.
FROM tableName is mandatory and must contain at least one table, multiple tables must be separated using commas or joined using the JOIN keyword.
WHERE condition is optional, it can be used to specify criteria in the result set returned from the query.
GROUP BY is used to put together records that have the same field values.
HAVING condition is used to specify criteria when working using the GROUP BY keyword.
ORDER BY is used to specify the sort order of the result set.
*
The Star symbol is used to select all the columns in table. An example of a simple SELECT statement looks like the one shown below.
SELECT * FROM `members`;
The above statement selects all the fields from the members table. The semi-colon is a statement terminate. It’s not mandatory but is considered a good practice to end your statements like that.
Practical examplesYou can learn to import the .sql file into MySQL WorkBench
The Examples are performed on the following two tables
Table 1: members table
membership_ number full_names gender date_of_ birth physical_ address postal_ address contct_ number email
1 Janet Jones Female 21-07-1980 First Street Plot No 4 Private Bag 0759 253 542 [email protected]
2 Janet Smith Jones Female 23-06-1980 Melrose 123 NULL NULL
3 Robert Phil Male 12-07-1989 3rd Street 34 NULL 12345
4 Gloria Williams Female 14-02-1984 2nd Street 23 NULL NULL NULL
Table 2: movies table
movie_id title director year_released category_id
1 Pirates of the Caribean 4 Rob Marshall 2011 1
2 Forgetting Sarah Marshal Nicholas Stoller 2008 2
3 X-Men NULL 2008 NULL
4 Code Name Black Edgar Jimz 2010 NULL
5 Daddy’s Little Girls NULL 2007 8
6 Angels and Demons NULL 2007 6
7 Davinci Code NULL 2007 6
9 Honey mooners John Schultz 2005 8
16 67% Guilty NULL 2012 NULL
Getting members listing
Let’s suppose that we want to get a list of all the registered library members from our database, we would use the script shown below to do that.
SELECT * FROM `members`;Executing the above script in MySQL workbench produces the following results.
membership_ number full_names gender date_of_ birth physical_ address postal_ address contct_ number email
1 Janet Jones Female 21-07-1980 First Street Plot No 4 Private Bag 0759 253 542 [email protected]
2 Janet Smith Jones Female 23-06-1980 Melrose 123 NULL NULL
3 Robert Phil Male 12-07-1989 3rd Street 34 NULL 12345
4 Gloria Williams Female 14-02-1984 2nd Street 23 NULL NULL NULL
Our above query has returned all the rows and columns from the members table.
Let’s say we are only interested in getting only the full_names, gender, physical_address and email fields only. The following script would help us to achieve this.
SELECT `full_names`,`gender`,`physical_address`, `email` FROM `members`;Executing the above script in MySQL workbench produces the following results.
full_names gender physical_address email
Janet Jones Female First Street Plot No 4 [email protected]
Janet Smith Jones Female Melrose 123
Robert Phil Male 3rd Street 34
Gloria Williams Female 2nd Street 23 NULL
Getting movies listing
Remember in our above discussion that we mention expressions been used in SELECT statements. Let’s say we want to get a list of movie from our database. We want to have the movie title and the name of the movie director in one field. The name of the movie director should be in brackets. We also want to get the year that the movie was released. The following script helps us do that.
SELECT Concat(`title`, ' (', `director`, ')') , `year_released` FROM `movies`;HERE
The Concat () MySQL function is used join the columns values together.
The line “Concat (`title`, ‘ (‘, `director`, ‘)’) gets the title, adds an opening bracket followed by the name of the director then adds the closing bracket.
String portions are separated using commas in the Concat () function.
Executing the above script in MySQL workbench produces the following result set.
Concat(`title`, ‘ (‘, `director`, ‘)’) year_released
Pirates of the Caribean 4 ( Rob Marshall) 2011
Forgetting Sarah Marshal (Nicholas Stoller) 2008
NULL 2008
Code Name Black (Edgar Jimz) 2010
NULL 2007
NULL 2007
NULL 2007
Honey mooners (John Schultz) 2005
NULL 2012
Alias field names
The above example returned the Concatenation code as the field name for our results. Suppose we want to use a more descriptive field name in our result set. We would use the column alias name to achieve that. The following is the basic syntax for the column alias name
HERE
“[AS]” is the optional keyword before the alias name that denotes the expression, value or field name will be returned as.
“`alias_name`” is the alias name that we want to return in our result set as the field name.
The above query with a more meaningful column name
SELECT Concat(`title`, ' (', `director`, ')') AS 'Concat', `year_released` FROM `movies`;We get the following result
Concat year_released
Pirates of the Caribean 4 ( Rob Marshall) 2011
Forgetting Sarah Marshal (Nicholas Stoller) 2008
NULL 2008
Code Name Black (Edgar Jimz) 2010
NULL 2007
NULL 2007
NULL 2007
Honey mooners (John Schultz) 2005
NULL 2012
Getting members listing showing the year of birth
Suppose we want to get a list of all the members showing the membership number, full names and year of birth, we can use the LEFT string function to extract the year of birth from the date of birth field. The script shown below helps us to do that.
SELECT `membership_number`,`full_names`,LEFT(`date_of_birth`,4) AS `year_of_birth` FROM members;HERE
“LEFT(`date_of_birth`,4)” the LEFT string function accepts the date of birth as the parameter and only returns 4 characters from the left.
“AS `year_of_birth`” is the column alias name that will be returned in our results. Note the AS keyword is optional, you can leave it out and the query will still work.
Executing the above query in MySQL workbench against the myflixdb gives us the results shown below.
membership_number full_names year_of_birth
1 Janet Jones 1980
2 Janet Smith Jones 1980
3 Robert Phil 1989
4 Gloria Williams 1984
SQL using MySQL WorkbenchWe are now going to use MySQL workbench to generate the script that will display all the field names from our categories table.
2. MySQL workbench will automatically create a SQL query and paste in the editor.
3. Query Results will be show
Notice that we didn’t write the SELECT statement ourselves. MySQL workbench generated it for us.
Why use the SELECT SQL command when we have MySQL Workbench?Now, you might be thinking why learn the SQL SELECT command to query data from the database when you can simply use a tool such as MySQL workbench’s to get the same results without knowledge of the SQL language. Of course that is possible, but learning how to use the SELECT command gives you more flexibility and control over your SQL SELECT statements.
MySQL workbench falls in the category of “Query by Example” QBE tools. It’s intended to help generate SQL statements faster to increase the user productivity.
Learning the SQL SELECT command can enable you to create complex queries that cannot be easily generated using Query by Example utilities such as MySQL workbench.
To improve productivity you can generate the code using MySQL workbench then customize it to meet your requirements. This can only happen if you understand how the SQL statements work!
Summary
The SQL SELECT keyword is used to query data from the database and it’s the most commonly used command.
The simplest form has the syntax “SELECT * FROM tableName;”
Expressions can also be used in the select statement . Example “SELECT quantity + price FROM Sales”
The SQL SELECT command can also have other optional parameters such as WHERE, GROUP BY, HAVING, ORDER BY. They will be discussed later.
MySQL workbench can help develop SQL statements, execute them and produce the output result in the same window.
Update the detailed information about How To Use Else Statement With Loops In Python? on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!