Posted on Leave a comment

Python String Formatting: How to Become a String Wizard with the Format Specification Mini-Language

Python provides fantastic string formatting options, but what if you need greater control over how values are presented? That’s where format specifiers come in. 

This article starts with a brief overview of the different string formatting approaches. We’ll then dive straight into some examples to whet your appetite for using Python’s Format Specification Mini-Language in your own projects.

But before all that—let’s play with string formatting yourself in the interactive Python shell:

Exercise: Create another variable tax and calculate the tax amount to be paid on your income (30%). Now, add both values income and tax in the string—by using the format specifier %s!

Don’t worry if you struggle with this exercise. After reading this tutorial, you won’t! Let’s learn everything you need to know to get started with string formatting in Python.

String Formatting Options

Python’s string formatting tools have evolved considerably over the years. 

The oldest approach is to use the % operator:

>>> number = 1 + 2
>>> 'The magic number is %s' % number 'The magic number is 3'

(The above code snippet already includes a kind of format specifier. More on that later…)

The str.format() method was then added:

>>> 'The magic number is {}'.format(number) 'The magic number is 3'

Most recently, formatted string literals (otherwise known as f-strings) were introduced. F-strings are easier to use and lead to cleaner code, because their syntax enables the value of an expression to be placed directly inside a string:

>>> f'The magic number is {number}' 'The magic number is 3'

Other options include creating template strings by importing the Template class from Python’s string module, or manually formatting strings (which we’ll touch on in the next section).

If this is all fairly new to you and some more detail would be helpful before moving on, an in-depth explanation of the main string formatting approaches can be found here.

Format Specifiers

With that quick summary out of the way, let’s move on to the real focus of this post – explaining how format specifiers can help you control the presentation of values in strings.

F-strings are the clearest and fastest approach to string formatting, so I will be using them to illustrate the use of format specifiers throughout the rest of this article. Please bear in mind though, that specifiers can also be used with the str.format() method. Also, strings using the old % operator actually require a kind of format specification – for example, in the %s example shown in the previous section the letter s is known as a conversion type and it indicates that the standard string representation of the object should be used. 

So, what exactly are format specifiers and what options do they provide?

Simply put, format specifiers allow you to tell Python how you would like expressions embedded in strings to be displayed.

Percentage Format and Other Types

For example, if you want a value to be displayed as a percentage you can specify that in the following way:

>>> asia_population = 4_647_000_000
>>> world_population = 7_807_000_000
>>> percent = asia_population / world_population
>>> f'Proportion of global population living in Asia: {percent:.0%}' 'Proportion of global population living in Asia: 60%'

What’s going on here? How has this formatting been achieved?

Well the first thing to note is the colon : directly after the variable percent embedded in the f-string. This colon tells Python that what follows is a format specifier which should be applied to that expression’s value.

The % symbol defines that the value should be treated as a percentage, and the .0 indicates the level of precision which should be used to display it. In this case the percentage has been rounded up to a whole number, but if .1 had been specified instead the value would have been rounded to one decimal place and displayed as 59.5%; using .2 would have resulted in 59.52% and so on.

If no format specifier had been included with the expression at all the value would have been displayed as 0.5952350454720123, which is far too precise!

(The % symbol applied in this context should not be confused with the % operator used in old-style string formatting syntax.)

Percentage is just the tip of the iceberg as far as type values are concerned, there are a range of other types that can be applied to integer and float values.

For example, you can display integers in binary, octal or hex formats using the b, o and x type values respectively:

>>> binary, octal, hexadecimal = [90, 90, 90]
>>> f'{binary:b} - {octal:o} - {hexadecimal:x}' '1011010 - 132 - 5a'


For a full list of options see the link to the relevant area of the official Python documentation in the Further Reading section at the end of the article.

A close up of a reptile Description automatically generated

Width Format, Alignment and Fill

Another handy format specification feature is the ability to define the minimum width that values should take up when they’re displayed in strings.

To illustrate how this works, if you were to print the elements of the list shown below in columns without format specification, you would get the following result:

>>> python, java, p_num, j_num = ["Python Users", "Java Users", 8.2, 7.5]
>>> print(f"|{python}|{java}|\n|{p_num}|{j_num}|")
|Python Users|Java Users|
|8.2|7.5|

Not great, but with the inclusion of some width values matters start to improve:

>>> print(f"|{python:16}|{java:16}|\n|{p_num:16}|{j_num:16}|")
|Python Users |Java Users |
| 8.2| 7.5|

As you can see, width is specified by adding a number after the colon.

The new output is better, but it seems a bit strange that the titles are aligned to the left while the numbers are aligned to the right. What could be causing this?

Well, it’s actually to do with Python’s default approach for different data types. String values are aligned to the left as standard, while numeric values are aligned to the right. (This might seem slightly odd, but it’s consistent with the approach taken by Microsoft Excel and other spreadsheet packages.)

Fortunately, you don’t have to settle for the default settings. If you want to change this behavior you can use one of the alignment options. For example, focusing on the first column only now for the sake of simplicity, if we want to align the number to the left this can be done by adding the < symbol before the p_num variable’s width value:

>>> print(f"|{python:16}|\n|{p_num:<16}|")
|Python Users |
|8.2 |

And the reverse can just as easily be achieved by adding a > symbol in front of the width specifier associated with the title value:

>>> print(f"|{python:>16}|\n|{p_num:16}|")
| Python Users|
| 8.2|

But what if you want the rows to be centered? Luckily, Python’s got you covered on that front too. All you need to do is use the ^ symbol instead:

>>> print(f"|{python:^16}|\n|{p_num:^16}|")
| Python Users |
| 8.2 |

Python’s default fill character is a space, and that’s what has so far been used when expanding the width of our values. We can use almost any character we like though. It just needs to be placed in front of the alignment option. For example, this is what the output looks like when an underscore is used to fill the additional space in the title row of our column:

>>> print(f"|{python:_^16}|\n|{p_num:^16}|")
|__Python Users__|
| 8.2 |

It’s worth noting that the same output can be achieved manually by using the str() function along with the appropriate string method (in this case str.center()):

>>> print("|", python.center(16, "_"), "|\n|", str(p_num).center(16), "|", sep="")
|__Python Users__|
| 8.2 |

But the f-string approach is much more succinct and considerably faster to evaluate at run time.

Of course, outputting data formatted into rows and columns is just one example of how specifying width, alignment and fill characters can be used.

Also, in reality if you are looking to output a table of information you aren’t likely to be using a single print() statement. You will probably have several rows and columns to display, which may be constructed with a loop or comprehension, perhaps using str.join() to insert separators etc.

However, regardless of the application, in most instances using f-strings with format specifiers instead of taking a manual approach will result in more readable and efficient code.

A picture containing camera Description automatically generated

24-Hour Clock Display

As another example, let’s say we want to calculate what the time of day will be after a given number of hours and minutes has elapsed (starting at midnight):

>>> hours = 54
>>> minutes = 128
>>> quotient, minute = divmod(minutes, 60)
>>> hour = (hours + quotient) % 24
>>> f'{hour}:{minute}' '8:8'

So far so good. Our program is correctly telling us that after 54 hours and 128 minute the time of day will be 8 minutes past 8 in the morning, but the problem is that it’s not very easy to read. Confusion could arise about whether it’s actually 8 o’clock in the morning or evening and having a single digit to represent the number of minutes just looks odd.

To fix this we need to insert leading zeros when the hour or minute value is a single digit, which can be achieved using something called sign-aware zero padding. This sounds pretty complicated, but in essence we just need to use a 0 instead of one of the alignment values we saw earlier when defining the f-string, along with a width value of 2:

>>> f'{hour:02}:{minute:02}' '08:08'

Hey presto! The time is now in a clear 24-hour clock format. This approach will work perfectly for times with double-digit hours and minutes as well, because the width value is a maximum and the zero padding will not be used if the value of either expression occupies the entire space:

>>> hours = 47
>>> minutes = 59
...
>>> f'{hour:02}:{minute:02}' '23:59'
A picture of stars in the sky Description automatically generated

Grouping Options

The longer numbers get the harder they can be to read without thousand separators, and if you need to insert them this can be done using a grouping option:

>>> proxima_centauri = 40208000000000
>>> f'The closest star to our own is {proxima_centauri:,} km away.' 'The closest star to our own is 40,208,000,000,000 km away.'

You can also use an underscore as the separator if you prefer:

>>> f'The closest star to our own is {proxima_centauri:_} km away.' 'The closest star to our own is 40_208_000_000_000 km away.'


Putting It All Together

You probably won’t need to use a wide variety of format specification values with a single expression that often, but if you do want to put several together the order is important.

Staying with the astronomical theme, for demonstration purposes we’ll now show the distance between the Sun and Neptune in millions of kilometers:

>>> neptune = "Neptune"
>>> n_dist = 4_498_252_900 / 1_000_000
>>> print(f"|{neptune:^15}|\n|{n_dist:~^15,.1f}|")
| Neptune |
|~~~~4,498.3~~~~|

As you can see, reading from right to left we need to place the n_dist format specification values in the following order:

  1. Type  – f defines that the value should be displayed using fixed-point notation
  2. Precision – .1 indicates that a single decimal place should be used 
  3. Grouping – , denotes that a comma should be used as the thousand separator
  4. Width – 15 is set as the minimum number of characters
  5. Align – ^ defines that the value should be centered
  6. Fill – ~ indicates that a tilde should occupy any unused space

In general, format values that are not required can simply be omitted. However, if a fill value is specified without a corresponding alignment option a ValueError will be raised.

Final Thoughts and Further Reading

The examples shown in this article have been greatly simplified to demonstrate features in a straightforward way, but I hope they have provided some food for thought, enabling you to envisage ways that the Format Specification Mini-Language could be applied in real world projects.

Basic columns have been used to demonstrate aspects of format specification, and displaying tabular information as part of a Command Line Application is one example of the ways this kind of formatting could be employed. 

If you want to work with and display larger volumes of data in table format though, you would do well to check out the excellent tools provided by the pandas library, which you can read about in these Finxter articles.

Also, if you would like to see the full list of available format specification values they can be found in this section of the official Python documentation.

The best way to really get the hang of how format specifiers work is to do some experimenting with them yourself. Give it a try – I’m sure you’ll have some fun along the way!

Posted on Leave a comment

How To Ask Users For Input Until They Provide a Valid Input?

To accept valid inputs from the user either use a While Loop With Custom Validations or use the PyInputPlus module to avoid tedious validation definitions. Some other methods may also fascinate you which have been discussed below.

Problem: Given a user input; accept the input only if it is valid otherwise ask the user to re-enter the input in the correct format.

Any user input must be validated before being processed, without proper validation of user input the code is most certainly going to have errors or bugs. The values that you want a user to enter and the values that they provide as an input can be completely different. For example, you want a user to enter their age as a positive valid numerical value, in this case, your code should not accept any invalid input like a negative number or words. 

#note:  In Python 2.7, raw_input() is used to get a user input whereas in python 3 and above input() is used to get user input. input() always converts the user input into a string, so you need to typecast it into another data type if you want to use the input in another format.

Example:

age = int(input("What is your age: "))
if age >= 18: print("You are an Adult!")
else: print("You are not an Adult!")

Output:

What is your age: 25
You are an Adult!

However, the code does not work when the user enters invalid input. (This is what we want to avoid. Instead of an error, we want the user to re-enter a valid input.)

What is your age: twenty five
Traceback (most recent call last): File "C:/Users/Shubham-PC/PycharmProjects/pythonProject/main.py", line 1, in <module> age = int(input("What is your age: "))
ValueError: invalid literal for int() with base 10: 'twenty five'

Now that we have an overview of our problem, let us dive straight into the solutions.

Let’s get a quick overview of the first two solutions discussed in this article:

Method 1: Implement Input Validation Using While Loop And Exception Handling

The easiest solution is to accept user input in a while loop within a try statement and use continue when the user enters invalid input and break statement to come out of the loop once the user enters a valid or correct input value. 

Let us have a look at the following code to understand this concept:

Exercise: Run the code and try to break it by using wrong inputs. What happens?

Here’s the code to copy&paste:

while True: try: age = int(input("What is your age: ")) except ValueError: print("Please Enter a valid age.") continue else: if age > 0: break else: print("Age should be greater than 0!")
if age >= 18: print("You are an adult!")
else: print("You are not an adult!")

Output:

What is your age: twenty five
Please Enter a valid age.
What is your age: -25
Age should be greater than 0!
What is your age: 25
You are an adult!

Method 2: Using Python’s PyInputPlus module

Another way of managing user inputs is by using the PyInputPlus module which contains functions for accepting specific data inputs from the user like numbers, dates, email addresses, etc. You can read more about this module in the official documentation here.

Using the PyInputPlus module function we can ensure that the user input is valid because if a user enters invalid input, PyInputPlus will prompt the user to re-enter a valid input. Let us have a look at the code given below to get a better grip on the usage of PyInputPlus for validating user input.  

Disclaimer: PyInputPlus is not a part of Python’s standard library. Thus you have to install it separately using Pip.

import pyinputplus as pyip # User is prompted to enter the age and the min argument ensures minimum age is 1
age = pyip.inputInt(prompt="Please enter your age: ", min=1)
if age >= 18: print("You are an Adult!")
else: print("You are not an Adult!")

Output:

Please enter your age: -1
Number must be at minimum 1.
Please enter your age: twenty five 'twenty five' is not an integer.
Please enter your age: 25
You are an Adult!

Method 3: Implementing Recursion

Another way of prompting the user to enter a valid input every time the user enters an invalid value is to make use of recursion. Recursion allows you to avoid the use of a loop. However, this method works fine most of the time unless the user enters the invalid data too many times. In that case, the code will terminate with a RuntimeError: maximum recursion depth exceeded.

def valid_input(): try: age = int(input("Enter your Age: ")) except ValueError: print("Please Enter a valid age. The Age must be a numerical value!") return valid_input() if age <= 0: print("Your Age must be a positive numerical value!") return valid_input() else: return age x = valid_input()
if x >= 18: print("You are an Adult!")
else: print("You are not an Adult!")

Output:

Enter your Age: -1
Your Age must be a positive numerical value!
Enter your Age: twenty five
Please Enter a valid age. The Age must be a numerical value!
Enter your Age: 25
You are an Adult!

Method 4: A Quick Hack Using Lambda Function

Though this method might not be the best in terms of code complexities, however, it might come in handy in situations where you want to use a function once and then throw it away after the purpose is served. Also, this method displays how long pieces of codes can be minimized, hence this method makes a worthy entry into the list of our proposed solutions.

valid = lambda age: (age.isdigit() and int(age) > 0 and ( (int(age) >= 18 and "You are an Adult!") or "You are not an Adult")) or \ valid(input( "Invalid input.Please make sure your Age is a valid numerical vaule!\nPlease enter your age: "))
print(valid(input("Please enter your age: ")))

Output:

Please enter your age: -1
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: 0
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: twenty five
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: 25
You are an Adult!

Conclusion

Thus proper validation of user input is of utmost importance for a bug-free code and the methods suggested above might prove to be instrumental in achieving our cause. I prefer the use of PyInputPlus module since defining custom validations might get tedious in case of complex requirements. Also, the use of recursive methods must be avoided unless you are sure about your requirements since they require more memory space and often throw Stack Overflow Exceptions when operations are too large. 

I hope you found this article helpful and it helps you to accept valid user inputs with ease. Stay tuned for more interesting stuff in the future!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Bootstrap Contact Form with JavaScript Validation and PHP

Last modified on September 7th, 2020.

Bootstrap is the most popular solution to design an optimum, intuitive, mobile-ready UI components. It is easy to integrate the Bootstrap library for the application interface.

Often, many of my readers ask for a Bootstrap contact form code. So I thought of creating a basic example for a Bootstrap enabled PHP contact form.

Bootstrap provides in-built features to take care of UI responsiveness, form validation, and more. I used its SVG icon library to display the contact form fields with suitable icons.

A Bootstrap contact form looks enriched. UI attracts people and enables them to use it with ease. Also, the developers’ effort is reduced by using the Bootstrap framework.

I have created a secure feature-packed responsive contact form – Iris. This is one of the best and sleek contact form component you can ever get.

What is inside?

  1. Contact form with vs without Bootstrap
  2. Majority of  the contact form fields
  3. About this example
  4. File Structure
  5. Slim UI layout with the Bootstrap contact from
  6. Contact form validation with plain JavaScript
  7. Processing contact form data in PHP code
  8. Bootstrap contact form UI output

A contact form collects a different type of user details like name, message and more. There are various popular templates for contact forms.

I have created various PHP contact form examples. And those form templates uses my own custom CSS.

Though it is straight forward to go with custom CSS, designing with Bootstrap gives irrefutable offer.

Bootstrap provides full-fledged styles to create various types of form layout. It includes more of element-specific, attribute-specific forms styles.

With a Bootstrap contact form, the responsiveness, the cross-browser compatibilities are an easy deal.

If you already use the Bootstrap framework, then also it would be natural not to choose the custom CSS UI option.

For a simple example to prepend icons to form inputs without Bootstrap needs a bunch of CSS and media queries. But, with Bootstrap it has input-group selector to achieve this.

In case if you want to render a thin, primitive contact form, then custom CSS is preferable.

Most of the contact forms have the name, email, subject, message fields. Some times it varies based on the applications’ purpose.

For example, site-admin may merge the user feedbacks and inquiries entry points. In such cases, the contact form may have a radio option group to choose between feedback and inquiry.

Sometimes, people may collect phone numbers with country code. Also, it may have checkbox options to receive GDPR consent as per the European legislation.

In a way, contact forms become complex in positioning fields, giving fluidity and more aspects.

Bootstrap supports a variety of layout options to create even a more complex form. Based on the complexity of the contact form layout, the Bootstrap is even dependable.

About this example

This example uses rebooted form styles with classes to create a Bootstrap contact form. It makes this form UI responsive and consistent in all browsers and viewports.

It includes a default contact form having vertically stacked form controls. Each form-control has a prepended icon suitable to the contact input. I downloaded the Bootstrap SVG icon library to have such icons.

The form validation with a plain JavaScript simplifies the effort of loading any external libraries.

In PHP, it handles the posted data for sending them via a contact email. Also, it stores the data into a database table if any. It is optional and can disable in code.

This code uses a simple PHP mail() function for sending the emails. In a previous example, I have added how to send email using Gmail SMTP. Replace the simple mail() function with the one using PhpMailer via Gmail SMTP.

File Structure

The contact form code is a small integrative component of an application. This example contains a very minimal code of having a Bootstrap contact form.

The vendor directory includes the Bootstrap CSS and icon library.

The bootstrap-contact-form.phpfile contains the contact form HTML template. The landing page renders the contact form by including this template.

Bootstrap Contact Form File Structure

This section shows the Bootstrap contact form HTML code. This HTML shows a default vertically stacked contact form fields.

The Bootstrap form grid styles and CSS provides options to display a horizontal form.

In the below HTML, each form element is in a form-group container. It groups the form element label, form controls, validation and help-text properly.

The Email field has a help text that displays a note spaced as text-muted.

The input-group specific styles help to display icon-prepended form controls. These icons are from the Bootstrap SVG icon library.

bootstrap-contact-form.php

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Bootstrap Contact Form</title>
<link rel="stylesheet" href="./vendor/bootstrap/css/bootstrap.min.css">
</head>
<body class="bg-light"> <div class="container"> <div class="row py-4"> <div class="col"> <h2>Bootstrap Contact Form</h2> </div> </div> <form name="frmContact" id="frmContact" method="post" action="" enctype="multipart/form-data" novalidate> <div class="row"> <div class="form-group col-md-4"> <label>Name</label> <span id="userName-info" class="invalid-feedback"></span> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><?php require __DIR__ . '/vendor/bootstrap/bootstrap-icons/person.svg';?></span> </div> <input type="text" class="form-control" name="userName" id="userName" required> </div> </div> </div> <div class="row"> <div class="form-group col-md-4"> <label>Email</label> <span id="userEmail-info" class="invalid-feedback"></span> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><?php require __DIR__ . '/vendor/bootstrap/bootstrap-icons/envelope.svg';?></span> </div> <input type="email" name="userEmail" id="userEmail" class="form-control" required> </div> <small id="emailHelp" class="form-text text-muted">Your email will not be shared.</small> </div> </div> <div class="row"> <div class="form-group col-md-8"> <label>Subject</label> <span id="subject-info" class="invalid-feedback"></span> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><?php require __DIR__ . '/vendor/bootstrap/bootstrap-icons/question.svg';?></span> </div> <input type="text" name="subject" id="subject" class="form-control" required> </div> </div> </div> <div class="row"> <div class="form-group col-md-8"> <label>Message</label> <span id="content-info" class=" invalid-feedback"></span> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><?php require __DIR__ . '/vendor/bootstrap/bootstrap-icons/pencil.svg';?></span> </div> <textarea class="form-control" rows="5" name="message" id="message" required></textarea> </div> </div> </div> <div class="row"> <div class="col"> <input type="submit" name="send" class="btn btn-primary" value="Send Message" /> </div> </div>
<?php
if (! empty($displayMessage)) { ?> <div class="row"> <div class="col-md-8"> <div id="statusMessage" class="alert alert-success mt-3" role="alert"><?php echo $displayMessage; ?> </div> </div> </div>
<?php
}
?> </form> </div> <script type="text/javascript" src="./js/validation.js"></script>
</body>
</html> 

The above HTML template imports the Bootstrap CSS from the vendor location.

After submitting the contact details, users will receive an acknowledgment message. The bootstrap success alert box displays a positive response on successful mail sending.

All the fields are mandatory in this Bootstrap contact form example.

The js/validation.js file has the validation script. On the window load event, this script sets the submit event listener to check the form validity.

Once it found invalid form fields, it will prevent the form to submit. Added to that it will add Bootstrap custom validation styles to highlight the invalid fields.

It adds the .was-validated class to the parent form element. It highlights the form fields with respect to the :valid and :invalid pseudo-classes.

Apart from the red-bordered invalid field highlighting, the script displays a text-based error message. The setValidationResponse() checks the form data and insert the error message into the target.

This custom function invokes markAsValid() and markAsInvalid() to show the error messages. These functions set the element’s display property and the innerText.

js/validation.js

(function() { 'use strict'; window.addEventListener('load', function() { var form = document.getElementById('frmContact'); form.addEventListener('submit', function(event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); setValidationResponse(); } form.classList.add('was-validated'); }, false); }, false);
})(); function setValidationResponse() { var emailRegex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; var userName = document.getElementById("userName").value; var userEmail = document.getElementById("userEmail").value; var subject = document.getElementById("subject").value; var content = document.getElementById("message").value; if (userName == "") { markAsInvalid("userName", "required"); } else { markAsValid("userName"); } if (userEmail == "") { markAsInvalid("userEmail", "required"); } else if(!emailRegex.test(userEmail)) { markAsInvalid("userEmail", "invalid"); } else { markAsValid("userEmail"); } if (subject == "") { markAsInvalid("subject", "required"); } else { markAsValid("subject"); } if (content == "") { markAsInvalid("content", "required"); } else { markAsValid("content"); }
} function markAsValid(id) { document.getElementById(id+"-info").style.display = "none";
} function markAsInvalid(id, feedback) { document.getElementById(id+"-info").style.display = "inline"; document.getElementById(id+"-info").innerText = feedback;
}

This section is something common in all of my contact forms example. But, this is important for which we have started.

In this example, it has support to store the contact form data into a database. But, it is optional and configurable in the coding.

The PHP code has a variable $isDatabase which may have a boolean true to enable the database.

structure.sql

--
-- Database: `bootstrap_contact_form`
-- -- -------------------------------------------------------- --
-- Table structure for table `tbl_contact`
-- CREATE TABLE `tbl_contact` ( `id` int(11) NOT NULL, `user_name` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `subject` varchar(255) NOT NULL, `message` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1; --
-- Indexes for dumped tables
-- --
-- Indexes for table `tbl_contact`
--
ALTER TABLE `tbl_contact` ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `tbl_contact`
--
ALTER TABLE `tbl_contact` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

The below code shows the backend logic created in PHP for handling the posted data. This code has the default PHP mail() function to send the contact details.

index.php

<?php
use Phppot\DataSource; if (! empty($_POST["send"])) { $name = $_POST["userName"]; $email = $_POST["userEmail"]; $subject = $_POST["subject"]; $message = $_POST["message"]; $isDatabase = false; if ($isDatabase) { require_once __DIR__ . "/lib/DataSource.php"; $ds = new DataSource(); $query = "INSERT INTO tbl_contact (user_name, user_email, subject, message) VALUES (?, ?, ?, ?)"; $paramType = "ssss"; $paramArray = array( $name, $email, $subject, $message ); $ds->insert($query, $paramType, $paramArray); } $toEmail = "phppot@example.com"; $mailHeaders = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: ' . $name . '<' . $email . ">\r\n" . 'X-Mailer: PHP/' . phpversion(); $mailHeaders = "From: " . $name . "<" . $email . ">\r\n"; // if lines are larger than 70 chars, then should be wrapped $message = wordwrap($message, 70, "\r\n"); // your PHP setup should have configuration to send mail $isValidMail = mail($toEmail, $subject, $message, $mailHeaders); if ($isValidMail) { $displayMessage = "Message sent. Thank you."; }
}
require_once __DIR__ . "/bootstrap-contact-form.php"; 

After setting $isDatabase to true, configure the database details in this class to connect the database for the contact form action.

lib/DataSource.php

<?php
/** * Copyright (C) Phppot * * Distributed under 'The MIT License (MIT)' * In essense, you can do commercial use, modify, distribute and private use. * Though not mandatory, you are requested to attribute Phppot URL in your code or website. */
namespace Phppot; /** * Generic datasource class for handling DB operations. * Uses MySqli and PreparedStatements. * * @version 2.6 - recordCount function added */
class DataSource
{ const HOST = 'localhost'; const USERNAME = 'root'; const PASSWORD = 'test'; const DATABASENAME = 'bootstrap_contact_form'; private $conn; /** * PHP implicitly takes care of cleanup for default connection types. * So no need to worry about closing the connection. * * Singletons not required in PHP as there is no * concept of shared memory. * Every object lives only for a request. * * Keeping things simple and that works! */ function __construct() { $this->conn = $this->getConnection(); } /** * If connection object is needed use this method and get access to it. * Otherwise, use the below methods for insert / update / etc. * * @return \mysqli */ public function getConnection() { $conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME); if (mysqli_connect_errno()) { trigger_error("Problem with connecting to database."); } $conn->set_charset("utf8"); return $conn; } /** * To get database results * * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function select($query, $paramType = "", $paramArray = array()) { $stmt = $this->conn->prepare($query); if (! empty($paramType) && ! empty($paramArray)) { $this->bindQueryParams($stmt, $paramType, $paramArray); } $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $resultset[] = $row; } } if (! empty($resultset)) { return $resultset; } } /** * To insert * * @param string $query * @param string $paramType * @param array $paramArray * @return int */ public function insert($query, $paramType, $paramArray) { $stmt = $this->conn->prepare($query); $this->bindQueryParams($stmt, $paramType, $paramArray); $stmt->execute(); $insertId = $stmt->insert_id; return $insertId; } /** * To execute query * * @param string $query * @param string $paramType * @param array $paramArray */ public function execute($query, $paramType = "", $paramArray = array()) { $stmt = $this->conn->prepare($query); if (! empty($paramType) && ! empty($paramArray)) { $this->bindQueryParams($stmt, $paramType, $paramArray); } $stmt->execute(); } /** * 1. * Prepares parameter binding * 2. Bind prameters to the sql statement * * @param string $stmt * @param string $paramType * @param array $paramArray */ public function bindQueryParams($stmt, $paramType, $paramArray = array()) { $paramValueReference[] = & $paramType; for ($i = 0; $i < count($paramArray); $i ++) { $paramValueReference[] = & $paramArray[$i]; } call_user_func_array(array( $stmt, 'bind_param' ), $paramValueReference); } /** * To get database results * * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function getRecordCount($query, $paramType = "", $paramArray = array()) { $stmt = $this->conn->prepare($query); if (! empty($paramType) && ! empty($paramArray)) { $this->bindQueryParams($stmt, $paramType, $paramArray); } $stmt->execute(); $stmt->store_result(); $recordCount = $stmt->num_rows; return $recordCount; }
} 

This screenshot shows the Bootstrap contact form example output. It displays the valid fields in green and the invalid fields in red.

This indication will notify the user on clicking the “Send Email” submit button.

Bootstrap Contact Form Output

On successful mail sending, a success response will send to the user as shown below.

Contact Form Success Response
Download

↑ Back to Top

Posted on Leave a comment

Python One Line Append

Do you want to one-linerize the append() method in Python? I feel you—writing short and concise one-liners can be an addiction! 🙂

This article will teach you all the ways to append one or more elements to a list in a single line of Python code!

Python List Append

Let’s quickly recap the append method that allows you add an arbitrary element to a given list.

How can you add an elements to a given list? Use the append() method in Python.

Definition and Usage

The list.append(x) method—as the name suggests—appends element x to the end of the list.

Here’s a short example:

>>> l = []
>>> l.append(42)
>>> l
[42]
>>> l.append(21)
>>> l
[42, 21]

In the first line of the example, you create the list l. You then append the integer element 42 to the end of the list. The result is the list with one element [42]. Finally, you append the integer element 21 to the end of that list which results in the list with two elements [42, 21].

Syntax

You can call this method on each list object in Python. Here’s the syntax:

list.append(element)

Arguments

Argument Description
element The object you want to append to the list.

Related articles:

Python One Line List Append

Problem: How can you create a list and append an element to a list using only one line of Python code?

You may find this challenging because you must accomplish two things in one line: (1) creating the list and (2) appending an element to it.

Solution: We use the standard technique to one-linerize each “flat” multi-line code snippet: with the semicolon as a separator between the expressions.

a = [1, 2, 3]; a.append(42); print(a)

This way, we accomplish three things in a single line of Python code:

  • Creating the list [1, 2, 3] and assigning it to the variable a.
  • Appending the element 42 to the list referred to by a.
  • Printing the list to the shell.

Related Article: Python One Line to Multiple Lines

Python One Line For Append

Problem: How can we append multiple elements to a list in a for loop but using only a single line of Python code?

Example: Say, you want to filter a list of words against another list and store the resulting words in a new list using the append() method in a for loop.

# FINXTER TUTORIAL:
# How to filter a list of words? words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = [] for word in words: if word not in stop_words: filtered_words.append(word) print(filtered_words)
# ['hi', 'hello', 'Python']

You first create a list of words to be filtered and stored in an initially empty list filtered_words. Second, you create a set of stop words against you want to check the words in the list. Note that it’s far more efficient to use the set data structure for this because checking membership in sets is much faster than checking membership in lists. See this tutorial for a full guide on Python sets.

You now iterate over all elements in the list words and add them to the filtered_words list if they are not in the set stop_words.

Solution: You can one-linerize this filtering process using the following code:

filtered_words = [word for word in words if word not in stop_words]

The solution uses list comprehension to, essentially, create a single-line for loop.

Here’s the complete code that solves the problem using the one-liner filtering method:

# FINXTER TUTORIAL:
# How to filter a list of words? words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = [word for word in words if word not in stop_words] print(filtered_words)
# ['hi', 'hello', 'Python']

Here’s a short tutorial on filtering in case you need more explanations:

Related Article: How to Filter a List in Python?

Python One Line If Append

In the previous example, you’ve already seen how to use the if statement in the list comprehension statement to append more elements to a list if they full-fill a given condition.

How can you filter a list in Python using an arbitrary condition? The most Pythonic and most performant way is to use list comprehension [x for x in list if condition] to filter all elements from a list.

Try It Yourself:

The most Pythonic way of filtering a list—in my opinion—is the list comprehension statement [x for x in list if condition]. You can replace condition with any function of x you would like to use as a filtering condition.

For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement [x for x in list if x<10] to create a new list with all list elements that are smaller than 10.

Here are three examples of filtering a list:

  • Get elements smaller than eight: [x for x in lst if x<8].
  • Get even elements: [x for x in lst if x%2==0].
  • Get odd elements: [x for x in lst if x%2].
lst = [8, 2, 6, 4, 3, 1] # Filter all elements <8
small = [x for x in lst if x<8]
print(small) # Filter all even elements
even = [x for x in lst if x%2==0]
print(even) # Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)

The output is:

# Elements <8
[2, 6, 4, 3, 1] # Even Elements
[8, 2, 6, 4] # Odd Elements
[3, 1]

This is the most efficient way of filtering a list and it’s also the most Pythonic one. If you look for alternatives though, keep reading because I’ll explain to you each and every nuance of filtering lists in Python in this comprehensive guide.

Python Append One Line to File

Problem: Given a string and a filename. How to write the string into the file with filename using only a single line of Python code?

Example: You have filename 'hello.txt' and you want to write string 'hello world!' into the file.

hi = 'hello world!'
file = 'hello.txt' # Write hi in file '''
# File: 'hello.txt':
hello world! '''

How to achieve this? In this tutorial, you’ll learn four ways of doing it in a single line of code!

Here’s a quick overview in our interactive Python shell:

Exercise: Run the code and check the file 'hello.txt'. How many 'hello worlds!' are there in the file? Change the code so that only one 'hello world!' is in the file!

The most straightforward way is to use the with statement in a single line (without line break).

hi = 'hello world!'
file = 'hello.txt' # Method 1: 'with' statement
with open(file, 'a') as f: f.write(hi) '''
# File: 'hello.txt':
hello world! '''

You use the following steps:

  • The with environment makes sure that there are no side-effects such as open files.
  • The open(file, 'a') statement opens the file with filename file and appends the text you write to the contents of the file. You can also use open(file, 'w') to overwrite the existing file content.
  • The new file returned by the open() statement is named f.
  • In the with body, you use the statement f.write(string) to write string into the file f. In our example, the string is 'hello world!'.

Of course, a prettier way to write this in two lines would be to use proper indentation:

with open(file, 'a') as f: f.write(hi)

This is the most well-known way to write a string into a file. The big advantage is that you don’t have to close the file—the with environment does it for you! That’s why many coders consider this to be the most Pythonic way.

You can find more ways on my detailed blog article.

Related Article: Python One-Liner: Write String to File

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

Python One Line Array

This article answers a number of questions how to accomplish different things with a Python array in one line. By studying these questions, you’ll become a better coder. So, let’s roll up your sleeves and get started! 🙂

Python One Line Print Array

If you just want to know the best way to print an array (list) in Python, here’s the short answer:

  • Pass a list as an input to the print() function in Python.
  • Use the asterisk operator * in front of the list to “unpack” the list into the print function.
  • Use the sep argument to define how to separate two list elements visually.

Here’s the code:

# Create the Python List
lst = [1, 2, 3, 4, 5] # Use three underscores as separator
print(*lst, sep='___')
# 1___2___3___4___5 # Use an arrow as separator
print(*lst, sep='-->')
# 1-->2-->3-->4-->5

Try It Yourself in Our Interactive Code Shell:

This is the best and most Pythonic way to print a Python array list. If you still want to learn about alternatives—and improve your Python skills in the process of doing so—read the following tutorial!

Related Article: Print a Python List Beautifully [Click & Run Code]

Python If Else One Line Array

The most basic ternary operator x if c else y returns expression x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative expression y.

Here’s a minimal example:

var = 21 if 3<2 else 42
# var == 42

While you read through the article to boost your one-liner power, you can listen to my detailed video explanation:

Related Article: If-Then-Else in One Line Python [Video + Interactive Code Shell]

Python One Line For Loop Array

How to Write a For Loop in a Single Line of Python Code?

There are two ways of writing a one-liner for loop:

  • Method 1: If the loop body consists of one statement, simply write this statement into the same line: for i in range(10): print(i). This prints the first 10 numbers to the shell (from 0 to 9).
  • Method 2: If the purpose of the loop is to create a list, use list comprehension instead: squares = [i**2 for i in range(10)]. The code squares the first ten numbers and stores them in the array list squares.

Let’s have a look at both variants in more detail in the following article:

Related article: Python One Line For Loop [A Simple Tutorial]

Python Iterate Array One Line

How to iterate over an array in a single line of code?

Say, you’ve given an array (list) lst and you want to iterate over all values and do something with them. You can accomplish this using list comprehension:

lst = [1, 2, 3]
squares = [i**2 for i in lst]
print(squares)
# [1, 4, 9]

You iterate over all values in the array lst and calculate their square numbers. The result is stored in a new array list squares.

You can even print all the squared array values in a single line by creating a dummy array of None values using the print() function in the expression part of the list comprehension statement:

[print(i**2) for i in lst] '''
1
4
9 '''

Related article: List Comprehension Full Introduction

Python Fill Array One Line

Do you want to fill or initialize an array with n values using only a single line of Python code?

To fill an array with an integer value, use the list multiplication feature:

array = [0] * 10
print(array)
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

This creates an array of ten elements filled with the value 0. You can also fill the array with other elements by replacing the 0 with the desired element—for example, [None] * 10 creates a list of ten None elements.

Python Initialize Array One Line

There are many ways of creating an array (list) in Python. Let’s get a quick overview in the following table:

Code Description
[] Square bracket: Initializes an empty list with zero elements. You can add elements later.
[x1, x2, x3, … ] List display: Initializes an empty list with elements x1, x2, x3, … For example, [1, 2, 3] creates a list with three integers 1, 2, and 3.
[expr1, expr2, ... ] List display with expressions: Initializes a list with the result of the expressions expr1, expr2, … For example, [1+1, 2-1] creates the list [2, 1].
[expr for var in iter] List comprehension: applies the expression expr to each element in an iterable.
list(iterable) List constructor that takes an iterable as input and returns a new list.
[x1, x2, ...] * n List multiplication creates a list of n concatenations of the list object. For example [1, 2] * 2 == [1, 2, 1, 2].

You can play with some examples in our interactive Python shell:

Exercise: Use list comprehension to create a list of square numbers.

Let’s dive into some more specific ways to create various forms of lists in Python.

Related Article: How to Create a Python List?

Python Filter Array One Line

How can you filter an array in Python using an arbitrary condition?

The most Pythonic way of filtering an array is the list comprehension statement [x for x in list if condition]. You can replace condition with any function of x you would like to use as a filtering criterion.

For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement [x for x in list if x<10] to create a new list with all list elements that are smaller than 10.

Here are three examples of filtering a list:

  • Get elements smaller than eight: [x for x in lst if x<8].
  • Get even elements: [x for x in lst if x%2==0].
  • Get odd elements: [x for x in lst if x%2].
lst = [8, 2, 6, 4, 3, 1] # Filter all elements <8
small = [x for x in lst if x<8]
print(small) # Filter all even elements
even = [x for x in lst if x%2==0]
print(even) # Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)

The output is:

# Elements <8
[2, 6, 4, 3, 1] # Even Elements
[8, 2, 6, 4] # Odd Elements
[3, 1]

This is the most efficient way of filtering an array and it’s also the most Pythonic one.

Related Article: How to Filter a List in Python?

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

Top 20 Laws for Freelance Web Developers

Last modified on August 30th, 2020.

I got an email from a freelance developer friend. I have a list of associates with whom I collaborate (I get their help) when I am overloaded. The email had two inevitable questions,

  1. How do you ensure that you get the full payment?
  2. How did you create such a testimonial page? Is it fake?

My testimonials

First let me write a short note on my testimonials page. You can easily identify that all the testimonials listed are true.

  • Live link to client’s website.
  • Logo, company name, address, client’s name, designation.

All the above are public information and can be verified within minutes. There are more that twenty five testimonials listed and cannot be faked.

Project success

Okay let us get back to the two questions. With a decade of freelancing experience, I have come up with twenty laws for freelance web developers. If you follow that, a project will be a success. 

When I say “project success” it means, client is happy. Everything else is a derivative of that. You get full payment, a good testimonial, repeat order, possible new reference and all the good things will happen as a by product.

The Laws

  1. All projects are not doable
  2. Empty your cup
  3. Write the requirements
  4. Be explicit with freelance terms
  5. Commit to milestones, dates and a plan
  6. Never work without an advance payment
  7. Create UI mockups
  8. Be reachable and receptive
  9. Initiate communication
  10. Show the progress and get feedback
  11. Give suggestions and add value
  12. When it is out of scope, call it out
  13. Do not discuss subsequent phases in between
  14. Absorb up to 20% variation in effort
  15. Document the source code
  16. Do not be ad-hoc, have policies and principles
  17. Holding a deliverable is not a solution
  18. When client says ‘not working’, it’s not working!
  19. Freelancer’s support is essential
  20. Request for a testimonial

freelance web developer laws

1. All projects are not doable

Do not accept everything that comes your way. Play to your strength. You may have to spend time without projects, even then you should be ready to say no.

There are various reasons to not accept a project.

  • As a web developer we have numerous tech stack options, plugins, extensions. You may not have knowledge or experience with the tech stack the client wishes. A freelance project is not a platform for you to experiment and learn.
  • A client does not know what he needs.
  • You do not have the required domain expertise.
  • You do not know how to achieve what he asks for. 
  • You are already occupied. Trying to accept projects in parallel will not allow you to focus.
  • Do not accept if you have to work for free or under-billed. Always conduct yourself as a professional business.
  • When you do not have access to the actual person giving the order. You can be sub-contracted, but you should have access to the person who gives the requirements. When there are multiple middle men passing requirements to you, things will get lost in the transfer. Unless you directly talk to the person who drives the requirements, you will not get a good hang of it.

Unless you are able to estimate the work and arrive at a detailed work break down structure, do not accept it.

Sometimes a long-term client may bring a project on an alien territory to you. He may try to persuade you, because he is comfortable working with you. If you accept and fail, you will loose. Better explain him why you do not want to take the project and it will add to your respect. 

2. Empty your cup

Every project is a new beginning. As you keep on delivering project, there is a possibility to become complacent. That will lead you to underestimate a project. 

Start as if it is your first freelance web project. Learning is critical a freelance web developer. Most of the times, you will be sitting alone coding from your attic.

There is no team to discuss, share and learn. It is all dependent on your thought process. If you start fresh, you will be receptive (law no. 12). 

3. Write the requirements

Spend more time on requirements phase. As a freelance web developer you will not be billing the time spent on proposal process. Requirements analysis and elaboration is the most critical phase in a software development life cycle. Even critical than the design phase.

Unless you know what you are building where you will be headed. As a web developer, you will be dealing with intangible things. So it is important to get the detailed requirements upfront. 

If you are working based on fixed rate, then waterfall method of development is best suited. You need to fix every inch of the requirement before start.

If you are working based on time and material (hour based billing), then agile iterative development methodology is fine. It is suitable for projects, where the requirement has to evolve over a period as you build. 

In both the cases, write the requirements. Ask the client to write a document and email to you. You analyze and elaborate it. Write it as a document and circulate back for feedback. Iterate the process and arrive at a final document. have the conversation recorded via email as it will help you later to recollect. 

Telephonic conversations has to be converted to a document. At the end of the phase, there should be a requirements document as detailed as possible. 

4. Be explicit with freelance terms

Do not assume things. In particular when it comes to money, do not assume. There are numerous ways the freelance developer world works. 

Explain the terms is detail and get the acknowledgement. Do not shy away from it. Discuss the percentage breakup, schedule, milestone, billing rate, fixed or hourly etc and the mode of payment.

Understand the emphasize is on money. It will also help to plan his budget allocation and be prepared for payment. Never ask for ad-hoc payments. Stick to the agreed schedule and payment mode.

5. Commit to milestones, dates and a plan

Before the project is agreed, the plan should be in place. It should have detailed work break down structure with milestones. The plan should be approved.

You should initiate this process even if the client does not insists on a plan. You should voluntarily commit to it. If you do not do so, it will allow for micro management and ad-hoc reporting.

Client will be guessing the progress and will be on his toes. It will subject you to pressure. Working without a shared plan will never be an advantage for you.

6. Never work without an advance payment

This is not to be on the safer side. This is for a commitment. This is a business. The client has to get involved from day one. He needs to invest on it. You will be investing your time and building the product and for his part he needs to invest the money. It is mutual.

Beginner freelancers fear for everything. If I ask for advance and the client says no to the project, I will loose an opportunity. Working without a commitment is even worser. 

Next, how much to ask is the question. In the freelance web developer world, it is customary to ask for 50% advance payment for smaller (less than 1000 USD) projects. For projects larger than that, the payment can be in three or four parts. Can be even tied to milestones (law no. 5). But whatsoever, there should be an advance to start the project.

7. Create UI mockups

A freelance web developer will always have an urge to commit a project, take advance and jump coding immediately. All these needs to happen immediately. There will be fear of losing the order. But you have to resist that urge.

The more the time you spend on requirements, it will save you later. Remember money is not the only objective. You should retain him for a repeat order, you need to get a testimonial from him, you need to get order references from him.

If all these have to happen, then do not rush into the project. The success is more essential than getting the final payment. Success encompasses more things than the final payment. 

Client’s happiness directly relates to the success. A freelance web developer needs to step into his shoes. Should make all the effort to understand his objective. 

A web developer’s key tool to obtain that objective is UI mockup. You need to invest on a fancy tool, monthly subscription etc. My go to tool is the good old pen and paper, sometimes color pencils will add jazz. 

Just draw, write to create a rough sketch of how you envision the application. Take a snapshot and share with the client. Get his concurrence. Do not over work it. Remember you will be doing this in the proposal stage and the time spent is not billed. All you need to do is covey your idea of the understanding to the client. 

A freelance web developer’s success depends on the strong grip on the project. The first step towards that is the UI mockups. 

8. Be reachable and receptive

Establish a proper communication channel with the client. Along with the quote, share the ways using which the client can reach you. Give multiple possible channels,

  1. Email
  2. Project collaboration tools
  3. IM
  4. Telephone

A freelance web developer is like a juggler. If you loose balance at any point, the whole act will come down. For you to maintain the balance, the client should be comfortable.

Be easily reachable. Clearly convey the client that you prefer email as the communication mode. Attend to emails at least twice a day. Communication channel preference should be in the above order for comfortable execution.

IM and telephone should be the last choice in the list. It never helps. As a freelance web developer, I work with global clients. Imagine a client calling you at midnight and asking for a modification.

When the client writes, it will give clarity to his thoughts. So written communication should be encouraged. You should show that you are listening. In an email, never put any points under the carpet. Whether you agree or not, respond to everything. 

If you are not able to reply immediately, just acknowledge and get back with details later. Your immediate response says that you are receptive.

9. Initiate communication

Do not be casual and wait for client to talk to you. Every mail, ping, call should emanate from the freelance developer and not the client. This will give a comfort to the client. This will assure the client that you are taking care of the project and it is in trusted hands.

Initiating the conversation for a doubt from your side is usual. Every freelance developer does it. But the emphasise is on initiation to inform that the milestone is getting delayed, or you are not able to achieve a feature that you agreed. It might be a bad news, but have the courage to initiate communication. 

10. Show the progress and get feedback

As a freelance web developer you might follow multiple different models for development. In agile development methodology, it is imperative the way it works is by iteration and sprints. You show the progress, get feedback, iterate and keep developing.

A freelance developer has a mindset to get into a cocoon. Nature of the work style drives into it. You keep on developing yourself, there is no team, no one around you to ensure that you are on the right track. Here comes the client. Whatever model you choose, establish a schedule.

Do not be ad-hoc to show the progress. Before you write the first line of code, in fact at the proposal itself lay out a plan. What are all the dates you are going to show the progress should be transparently conveyed to the client. It will drive your progress. More than that, it will avoid rework.

Whenever you get feedback, give priority for the feedback. Not the regular planned tasks. Adjust the plan and covey the client. Always feedback goes first, it should not be accumulated.

11. Give suggestions and add value

A freelance web developer is an expert. The client does it for the first or second time. But you are doing it for the hundredth time. It should reflect in the work.

You are not a data entry operator, you are a developer. Lot more is expected from you. You should contribute in all aspects from design to implementation to training. 

The client will have a narrowed down objective. He just focuses on only one thing, just the UI. You know the engine better. What component to use, how to modularize, how to make things interact, there are numerous aspects. 

Sometimes enthusiastic clients take things outside the track and it might derail the stability of the software. That’s where you step-in. Say no, be steadfast and more important you have to explain and make the client understand. After all he is the one investing.

There might be some intricate things, as an experienced person only you will know. Explain it to the client, add value to his investment. Those will not go free and you will be rewarded.

12. When it is out of scope, call it out

As per law 10, you are supposed to get feedback in regular interval. This opens up other possibility, scope creep. Every feedback has to be organized into bullet points.

Feedbacks should be encouraged to be communicated in written form. If it comes in paragraphs break it down to points. That will reveal hidden gems. Client may not be doing it intentionally. He wants to get a product of his dream. 

So he will be thinking about only what he wants. A freelance developer is doing business. Profitability is important. By informing the client that this is out of scope you are also helping him. Scope creep, will take you down. If you go down, the project goes down and so the client.

Explain it, give reference from the requirements document. Do not say no! A scope creep is an opportunity for a freelance web developer. Do not take it negatively and jump on the client. Explain him politely and increase the scope of the project and so the bill.

13. Do not discuss subsequent phases in between

If an out of scope item is minor that can be informed to the client, reestimate the project, schedule and cost. Sometimes, the out scope item can be a module. If in proportion it is 50% of the current size or more than that, then it should be carved out as a separate phase.

Do not mix it with the current scope of work. Tell the client that you will definitely work on it. But will be taken as next phase. Let us document it and move forward with the current scope of items. Let us finish the planned work and then take this as a next project.

Re estimate and re scheduling can be done once or twice. If you keep on repeating it, then the client will get a feeling that things are dragged. It will feel like when this thing will end. So it is all in perception.

14. Absorb up to 20% variation in effort

If you are billing by hourly (time and material), then this is not an issue. To be safe on this, people advice to always go for hourly billing and avoid fixed rate. Not necessarily. 

If you are good in your territory, then fixed rate is fine. Client’s prefer that. If you are skilled enough to arrive at a good estimate, then why not? Go for fixed billing.

Freelance web development is a haunting story, most of the time. Despite you follow all these laws, expect unexpected turns. A freelance web developer has to swim in uncharted territories at times.

This may result in effort variation, remember plus or minus both. Sometimes you loose and sometimes you win. In any case, up to 20% variation is fine. 

In situations beyond that, explain the client. Attribute proper reasons, give reference and evidences. It is your responsibility as a freelance developer to convince. Web development keeps on changing. A freelance developer needs to keep up the pace. Otherwise you will be in this situation quite often.

15. Document the source code

Developer’s responsibility is to ensure that the project is a success. In the success durability is also a critical element. A freelance developer is not expected to launch and run away (see law 19). 

A web application should have a life of minimum five years. Without any maintenance project should run. But when there is a necessity, it should be doable easily. Either you or some other freelance developer might work on it in the future.

The comments you are going to add now will be of great help later. Freelance web development should not be seen as a one time job. If you do not add code comments, the same project may be freelanced to you later and the web application will come back and haunt you.

There are so many literature around the web explaining the goodness of source code comments.

16. Do not be ad-hoc, have policies and principles

As a freelance web developer, you need to draw your own rules. How do you arrive that? Is there any web developer template available? There is none. If you find something, do not follow it blindly.

Every freelance developer is a unique breed. Every web development project has unique challenges. You handle it in your own style. You have to arrive at your own rules. 

But you cannot live without rules. For example, let us take non disclosure agreement (NDA). There are numerous template NDA littered all over the web. As a freelance developer you will come across many. Over a period build document for your own. Incorporate the best and keep updating it. 

Hourly billing, fixed rate, what is your style. If fixed rate, do not keep it volatile. Which UI web component you will use? Which web responsive framework will you use? Right from money to tech stack, a freelance developer should have written everything. This is what you will follow, this what you will use.

What is your free support duration? These are all questions that are thrown at a freelance developer quite often. You should have readymade fixed answers for these. You should have freelance policy document. 

17. Holding a deliverable is not a solution

The rope is holding you back. Did you see the movie “The Dark Knight Rises”? The scene where the batman tries to get out of the well (prison pit). It neatly sums up what fear does to you.

You are not exchanging illegal things. Holding a deliverable makes the client feel untrusted. Business requires trust from both the sides. If you have followed all the laws till now, the client will be more than happy to pay you.

You need not hold the deliverable and ask for money. It feels like threatening. You are a web developer. If you are confident that you have done a good job, do not tie the deliverable to the payment. They should be independent of each other.

No client will burn the bridge. If you do a good job and you make the client feel it, then he will pay you. Sometimes even more than what you agreed for. I have got paid extra many times.

The client will need you in the future in two cases. He may require you for maintenance or enhancement for the application you have built. He may also require you for new projects. So he will not attempt to run away.

To get the full payment, to get a testimonial, or for any similar objective, do not hold the deliverable. Your fear will make things worse. Be good and focus on client’s objective, then you will get everything.

18. When client says ‘not working’, it’s not working!

You have delivered the project and the job is over. But, the client says it is not working. Never ever reply saying, “it is working for me!”. When he says, he means it.

If it is a web application, ask for access. First have intention to identify what is happening. Then think about how to help solve the issue.

How you respond to the call is important. Instead of saying working for me think about understanding the issue. Nobody cares about whether it works for you or in your environment. It needs to work in the production and work for the investor. Only then the developer job is complete. 

19. Freelancer’s support is essential

Freelancer should always provide a support period. The terms may vary, but you should always provide support.

The terms of support should be discussed and conveyed at the proposal stage itself. For example, a freelancer can give six months of free support. Then what comes under free needs to be described. 

Support is essential for the durability of the web application. For maintenance and enhancements will always be there. The client will bank on you as a first choice. You should be available for that.

Repeat work has higher priority than new job. Free support has higher priority than repeat work. That’s how it goes in the freelance world. That’s how you ensure project success.

20. Request for a testimonial

“The crying baby gets the milk”, you should ask for it and there is nothing wrong in it. There are two main purposes to ask for a testimonial.

  1. To use it in your showcase
  2. To ensure that whether you have done a good job.

A freelancer’s worth is determined by the testimonials he has. It is your pride. It is far better and more important than a portfolio.

The words in the testimonial will teach you your strengths and weaknesses. Sometimes the client will not give you one. Don’t pester. Instead ask for what help should be done to make the project success.

Go the extra mile and make it a success. Then ensure that you get a testimonial.

↑ Back to Top

Posted on Leave a comment

How To Display The Latest Python News On Your Webpage?

To display the latest Python news on your website, you can use the embed feature in your WordPress editor….

Problem: How To Display The Latest Python News On Your Webpage?

Example:

Given a dictionary:

d = {'a': 42, 'b': 21}

We want to obtain the sum of all values in the dictionary:

42+21=63

Method 1: Extract Values and Use sum() Functions

fjfjk

print(42)

fdskalfjlk

Method 2: Extract Values and Use sum() Functions

fjfjk

print(42)

fdskalfjlk

Method 3: Extract Values and Use sum() Functions

fjfjk

print(42)

fdskalfjlk

Method 4: Extract Values and Use sum() Functions

fjfjk

print(42)

fdskalfjlk

Conclusion / Summary

alksjdflkasj

Posted on Leave a comment

Pretty Print JSON [Python One-Liner]

Problem: Given a JSON object. How to pretty print it from the shell/terminal/command line using a Python one-liner?

Minimal Example: You have given the following JSON object:

{"Alice": "24", "Bob": "28"}

And you want to get the following print output:

{ "Alice": "24", "Bob": "28"
}

How to accomplish this using a Python one-liner?

Method 0: Python Program + json.dump

The default way to accomplish this in a Python script is to import the json library to solve the issue:

Exercise: Execute the script. What’s the output? Now change the number of indentation spaces to 2!

However, what if you want to run this from your operating system terminal as a one-liner command? Let’s dive into the four best ways!

Method 1: Terminal / Shell / Command Line with Echo + Pipe + json.tool

The echo command prints the JSON to the standard output. This is then piped as standard input to the json.tool program that pretty prints the JSON object to the standard output:

echo '{"Alice": "24", "Bob": "28"}' | python -m json.tool

The output is the prettier:

{ "Alice": "24", "Bob": "28"
}

The pipe operator | redirects the output to the standard input of the Python script.

Method 2: Use a File as Input with json.tool

An alternative is the simple:

python -m json.tool file.json

This method is best if you have stored your JSON object in the file.json file. If the file contains the same data, the output is the same, too:

{ "Alice": "24", "Bob": "28"
}

Method 3: Use Web Resource with json.tool

If your JSON file resides on a given URL https://example.com, you’ll best use the following one-liner:

curl https://example.com/ | python -m json.tool

Again, assuming the same JSON object residing on the server, the output is the same:

{ "Alice": "24", "Bob": "28"
}

Method 4: Use jq

This is the simplest way but it assumes that you have the jq program installed on your machine. You can download jq here and also read about the excellent quick-start resources here.

Let’s dive into the code you can run in your shell:

jq <<< '{ "foo": "lorem", "bar": "ipsum" }'
{ "bar": "ipsum", "foo": "lorem"
}

The <<< operator passes the string on the right to the standard input of the command on the left. You can learn more about this special pipe operator in this SO thread.

While this method is not a Python script, it still works beautifully when executed from a Linux or MacOS shell or the Windows Powershell / command line.

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Posted on Leave a comment

ASP.NET Core updates in .NET 5 Preview 8

Daniel Roth

Daniel

.NET 5 Preview 8 is now available and is ready for evaluation. Here’s what’s new in this release:

  • Azure Active Directory authentication with Microsoft.Identity.Web
  • CSS isolation for Blazor components
  • Lazy loading in Blazor WebAssembly
  • Updated Blazor WebAssembly globalization support
  • New InputRadio Blazor component
  • Set UI focus in Blazor apps
  • Influencing the HTML head in Blazor apps
  • IAsyncDisposable for Blazor components
  • Control Blazor component instantiation
  • Protected browser storage
  • Model binding and validation with C# 9 record types
  • Improvements to DynamicRouteValueTransformer
  • Auto refresh with dotnet watch
  • Console Logger Formatter
  • JSON Console Logger

See the .NET 5 release notes for additional details and known issues.

Get started

To get started with ASP.NET Core in .NET 5 Preview 8 install the .NET 5 SDK.

You need to use Visual Studio 2019 16.8 Preview 2 or newer to use .NET 5 Preview 8. .NET 5 is also supported with the latest preview of Visual Studio for Mac. To use .NET 5 with Visual Studio Code, install the latest version of the C# extension.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET 5 Preview 7 to .NET 5 Preview 8:

  • Update all Microsoft.AspNetCore.* package references to 5.0.0-preview.8.*.
  • Update all Microsoft.Extensions.* package references to 5.0.0-preview.8.*.
  • Update System.Net.Http.Json package references to 5.0.0-preview.8.*.

That’s it! You should be all ready to go.

See also the full list of breaking changes in ASP.NET Core for .NET 5.

What’s new?

Azure Active Directory authentication with Microsoft.Identity.Web

The ASP.NET Core project templates now integrate with Microsoft.Identity.Web to handle authentication with Azure Activity Directory (Azure AD). The Microsoft.Identity.Web package provides a better experience for authentication through Azure AD as well as an easier way to access Azure resources on behalf of your users, including Microsoft Graph. Check out the Microsoft.Identity.Web sample that take you from a simple login through multi-tenancy, using Azure APIs, using Microsoft Graph, and protecting your own APIs. Microsoft.Identity.Web will be generally available alongside .NET 5.

CSS isolation for Blazor components

Blazor now supports defining CSS styles that are scoped to a given component. Component specific CSS styles make it easier to reason about the styles in your app and to avoid unintentional side effects from global styles. You define component specific styles in a .razor.css file the matches the name of the .razor file for the component.

For example, let’s say you have a component MyComponent.razor file that looks like this:

MyComponent.razor

<h1>My Component</h1> <ul class="cool-list"> <li>Item1</li> <li>Item2</li>
</ul>

You can then define a MyComponent.razor.css with the styles for MyComponent:

MyComponent.razor.css

h1 { font-family: 'Comic Sans MS'
} .cool-list li { color: red;
}

The styles in MyComponent.razor.css will only get applied to the rendered output of MyComponent; the h1 elements rendered by other components, for example, are not affected.

To write a selector in component specific styles that affects child components, use the ::deep combinator.

.parent ::deep .child { color: red;
}

By using the ::deep combinator, only the .parent class selector is scoped to the component; the .child class selector is not scoped, and will match content from child components.

Blazor achieves CSS isolation by rewriting the CSS selectors as part of the build so that they only match markup rendered by the component. Blazor then bundles together the rewritten CSS files and makes the bundle available to the app as a static web asset at the path _framework/scoped.styles.css.

While Blazor doesn’t natively support CSS preprocessors like Sass or Less, you can still use CSS preprocessors to generate component specific styles before they are rewritten as part of the building the project.

Lazy loading in Blazor WebAssembly

Lazy loading enables you to improve the load time of your Blazor WebAssembly app by deferring the download of specific app dependencies until they are required. Lazy loading may be helpful if your Blazor WebAssembly app has large dependencies that are only used for specific parts of the app.

To delay the loading of an assembly, you add it to the BlazorWebAssemblyLazyLoad item group in your project file:

Assemblies marked for lazy loading must be explicitly loaded by the app before they are used. To lazy load assemblies at runtime, use the LazyAssemblyLoader service:

@inject LazyAssemblyLoader LazyAssemblyLoader @code { var assemblies = await LazyAssemblyLoader.LoadAssembliesAsync(new string[] { "Lib1.dll" });
}

To lazy load assemblies for a specific page, use the OnNavigateAsync event on the Router component. The OnNavigateAsync event is fired on every page navigation and can be used to lazy load assemblies for a particular route. You can also lazily load the entire page for a route by passing any lazy loaded assemblies as additional assemblies to the Router.

The following examples demonstrates using the LazyAssemblyLoader service to lazy load a specific dependency (Lib1.dll) when the user navigates to /page1. The lazy loaded assembly is then added to the additional assemblies list passed to the Router component, so that it can discover any routable components in that assembly.

@using System.Reflection
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader LazyAssemblyLoader <Router AppAssembly="typeof(Program).Assembly" AdditionalAssemblies="lazyLoadedAssemblies" OnNavigateAsync="@OnNavigateAsync"> <Navigating> <div> <p>Loading the requested page...</p> </div> </Navigating> <Found Context="routeData"> <RouteView RouteData="@routeData" DefaultLayout="typeof(MainLayout)" /> </Found> <NotFound> <LayoutView Layout="typeof(MainLayout)"> <p>Sorry, there is nothing at this address.</p> </LayoutView> </NotFound>
</Router> @code { private List<Assembly> lazyLoadedAssemblies = new List<Assembly>(); private async Task OnNavigateAsync(NavigationContext args) { if (args.Path.EndsWith("/page1")) { var assemblies = await LazyAssemblyLoader.LoadAssembliesAsync(new string[] { "Lib1.dll" }); lazyLoadedAssemblies.AddRange(assemblies); } }
}

Updated Blazor WebAssembly globalization support

.NET 5 Preview 8 reintroduces globalization support for Blazor WebAssembly based on International Components for Unicode (ICU). Part of introducing the ICU data and logic is optimizing these payloads for download size. This work is not fully completed yet. We expect to reduce the size of the ICU data in future .NET 5 preview updates.

New InputRadio Blazor component

Blazor in .NET 5 now includes built-in InputRadio and InputRadioGroup components. These components simplify data binding to radio button groups with integrated validation alongside the other Blazor form input components.

Opinion about blazor:
<InputRadioGroup @bind-Value="survey.OpinionAboutBlazor"> @foreach (var opinion in opinions) { <div class="form-check"> <InputRadio class="form-check-input" id="@opinion.id" Value="@opinion.id" /> <label class="form-check-label" for="@opinion.id">@opinion.label</label> </div> }
</InputRadioGroup>

Set UI focus in Blazor apps

Blazor now has a FocusAsync convenience method on ElementReference for setting the UI focus on that element.

<button @onclick="() => textInput.FocusAsync()">Set focus</button>
<input @ref="textInput"/>

IAsyncDisposable support for Blazor components

Blazor components now support the IAsyncDisposable interface for the asynchronous release of allocated resources.

Control Blazor component instantiation

You can now control how Blazor components are instantiated by providing your own IComponentActivator service implementation.

Thank you Mladen Macanović for this Blazor feature contribution!

Influencing the HTML head in Blazor apps

Use the new Title, Link, and Meta components to programmatically set the title of a page and dynamically add link and meta tags to the HTML head in a Blazor app.

To use the new Title, Link, and Meta components:

  1. Add a package reference to the Microsoft.AspNetCore.Components.Web.Extensions package.
  2. Include a script reference to _content/Microsoft.AspNetCore.Components.Web.Extensions/headManager.js.
  3. Add a @using directive for Microsoft.AspNetCore.Components.Web.Extensions.Head.

The following example programmatically sets the page title to show the number of unread user notifications, and updates the page icon a as well:

@if (unreadNotificationsCount > 0)
{ var title = $"Notifications ({unreadNotificationsCount})"; <Title Value="title"></Title> <Link rel="icon" href="icon-unread.ico" />
}

Protected browser storage

In Blazor Server apps, you may want to persist app state in local or session storage so that the app can rehydrate it later if needed. When storing app state in the user’s browser, you also need to ensure that it hasn’t been tampered with.

Blazor in .NET 5 helps solve this problem by providing two new services: ProtectedLocalStorage and ProtectedSessionStorage. These services help you store state in local and session storage respectively, and they take care of protecting the stored data using the ASP.NET Core data protection APIs.

To use the new protected browser storage services:

  1. Add a package reference to Microsoft.AspNetCore.Components.Web.Extensions.
  2. Configure the services by calling services.AddProtectedBrowserStorage() from Startup.ConfigureServcies.
  3. Inject either ProtectedLocalStorage and ProtectedSessionStorage into your component implementation:

    @inject ProtectedLocalStorage ProtectedLocalStorage
    @inject ProtectedSessionStorage ProtectedSessionStorage
    
  4. Use the desired service to get, set, and delete state asynchronously:

    private async Task IncrementCount()
    {
    await ProtectedLocalStorage.SetAsync("count", ++currentCount);
    }
    

Model binding and validation with C# 9 record types

You can now use C# 9 record types with model binding in an MVC controller or a Razor Page. Record types are a great way to model data being transmitted over the wire.

For example, the PersonController below uses the Person record type with model binding and form validation:

“`C# public record Person([Required] string Name, [Range(0, 150)] int Age);

public class PersonController { public IActionResult Index() => View();

[HttpPost] public IActionResult Index(Person person) { // … } }

<br />*Person/Index.cshtml* ```razor
@model Person Name: <input asp-for="Model.Name" />
<span asp-validation-for="Model.Name" /> Age: <input asp-for="Model.Age" />
<span asp-validation-for="Model.Age" />

Improvements to DynamicRouteValueTransformer

ASP.NET Core in .NET Core 3.1 introduced DynamicRouteValueTransformer as a way to use use a custom endpoint to dynamically select an MVC controller action or a razor page. In .NET 5 Preview 8 you can now pass state to your DynamicRouteValueTransformer and filter the set of endpoints chosen.

Auto refresh with dotnet watch

In .NET 5, running dotnet watch on an ASP.NET Core project will now both launch the default browser and auto refresh the browser as you make changes to your code. This means you can open an ASP.NET Core project in your favorite text editor, run dotnet watch run once, and then focus on your code changes while the tooling handles rebuilding, restarting, and reloading your app. We expect to bring the auto refresh functionality to Visual Studio in the future as well.

Console Logger Formatter

We’ve made improvements to the console log provider in the Microsoft.Extensions.Logging library. Developers can now implement a custom ConsoleFormatter to exercise complete control over formatting and colorization of the console output. The formatter APIs allow for rich formatting by implementing a subset of the VT-100 (supported by most modern terminals) escape sequences. The console logger can parse out escape sequences on unsupported terminals allowing you to author a single formatter for all terminals.

JSON Console Logger

In addition to support for custom formatters, we’ve also added a built-in JSON formatter that emits structured JSON logs to the console. You can switch from the default simple logger to JSON, add to following snippet to your Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
+ .ConfigureLogging(logging =>
+ {
+ logging.AddJsonConsole(options =>
+ {
+ options.JsonWriterOptions = new JsonWriterOptions() { Indented = true };
+ });
+ }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

Once enabled, log messages emitted to the console are now JSON formatted.

{ "EventId": 0, "LogLevel": "Information", "Category": "Microsoft.Hosting.Lifetime", "Message": "Now listening on: https://localhost:5001", "State": { "Message": "Now listening on: https://localhost:5001", "address": "https://localhost:5001", "{OriginalFormat}": "Now listening on: {address}" }
}

Give feedback

We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Posted on Leave a comment

How to Print Without Newline in Python—A Simple Illustrated Guide

Summary: To print without the newline character in Python 3, set the end argument in the print() function to the empty string or the single whitespace character. This ensures that there won’t be a newline in the standard output after each execution of print(). Alternatively, unpack the iterable into the print() function to avoid the use of multiple print() statements: print(*iter).

Print Without Newline Python (End Argument)

Let’s go over this problem and these two solutions step-by-step.

Problem: How to use the print() function without printing an implicit newline character to the Python shell?

Example: Say, you want to use the print() function within a for loop—but you don’t want to see multiple newlines between the printed output:

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

The default standard output is the following:

1
2
3
4

But you want to get the following output in a single line of Python code.

1 2 3 4

How to accomplish this in Python 3?

Solution: I’ll give you the quick solution in an interactive Python shell here:

By reading on, you’ll understand how this works and become a better coder in the process.

Let’s have a quick recap of the Python print() function!

Python Print Function – Quick Start Guide

There are two little-used arguments of the print function in Python.

  • The argument sep indicates the separator which is printed between the objects.
  • The argument end defines what comes at the end of each line.

Related Article: Python Print Function [And Its SECRET Separator & End Arguments]

Consider the following example:

a = 'hello'
b = 'world' print(a, b, sep=' Python ', end='!')

Try it yourself in our interactive code shell:

Exercise: Click “Run” to execute the shell and see the output. What has changed?

Solution 1: End Argument of Print Function

Having studied this short guide, you can now see how to solve the problem:

To print the output of the for loop to a single line, you need to define the end argument of the print function to be something different than the default newline character. In our example, we want to use the empty space after each string we pass into the print() function. Here’s how you accomplish this:

for i in range(1,5): print(i, end=' ')

The shell output concentrates on a single line:

1 2 3 4 

By defining the end argument, you can customize the output to your problem.

Solution 2: Unpacking

However, there’s an even more advanced solution that’s more concise and more Pythonic. It makes use of the unpacking feature in Python.

print(*range(1,5))
# 1 2 3 4

The asterisk prefix * before the range(1,5) unpacks all values in the range iterable into the print function. This way, it becomes similar to the function execution print(1, 2, 3, 4) with comma-separated arguments. You can use an arbitrary number of arguments in the print() function.

Per default, Python will print these arguments with an empty space in between. If you want to customize this separator string, you can use the sep argument as you’ve learned above.

How to Print a List?

Do you want to print a list to the shell? Just follow these simple steps:

  • Pass a list as an input to the print() function in Python.
  • Use the asterisk operator * in front of the list to “unpack” the list into the print function.
  • Use the sep argument to define how to separate two list elements visually.

Here’s the code:

# Create the Python List
lst = [1, 2, 3, 4, 5] # Use three underscores as separator
print(*lst, sep='___')
# 1___2___3___4___5 # Use an arrow as separator
print(*lst, sep='-->')
# 1-->2-->3-->4-->5

Try It Yourself in Our Interactive Code Shell:

This is the best and most Pythonic way to print a Python list. If you still want to learn about alternatives—and improve your Python skills in the process of doing so—read the following tutorial!

Related Article: Print a Python List Beautifully [Click & Run Code]

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!