Search

Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML. Why PHP? The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script). PHP course is easy to learn for any newcomer, but also offers advanced programming features. Using PHP with a database system PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL. This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database. Listed below are some examples where PHP and MySQL can be used together: • Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website. • Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages. • Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page. Setting up the MySQL database The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database. Database administration can be done using PHP scripts or using a program like PHPMyAdmin. The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script: CREATE TABLE tablename { Fields } Where the Fields are coded as fieldname type(length) extra_info Example: first varchar(15) NOT NULL The following command is used in the PHP script to connect to the MySQL database: mysql_connect(localhost,$username,$password); where: • localhost is the server address on which the web site is running, • $username is the user name for the database access • $password is the password for the database access Executing PHP commands After configuring and connecting to the MySQL database, you can start executing PHP commands on the server. Following are the 2 methods of executing a PHP command: • Entering the command in PHP using the following syntax: Mysql_query($query) This form of command can be used to repeat the command simply by changing the variable. • Defining the command as a variable. The result of the operation will be assigned to the variable. Data input and output Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page. Following is an example of an HTML page with textboxes that can be used to enter data in a form: Alternatively, you can use variables to input information into the database. Example: $first=$_POST[‘first’]; $last=$_POST[‘last’]; $phone=$_POST[‘phone’]; $mobile=$_POST[‘mobile’]; $fax=$_POST[‘fax’]; $email=$_POST[’email’]; $web=$_POST[‘web’]; … $query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”; mysql_query($query); This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP. To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable. $query=”SELECT * FROM contacts”; $result=mysql_query($query); PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link. yourpage.php?user=david (to show David’s page) yourpage.php?user=tom (to show Tom’s page)
Rated 4.5/5 based on 9 customer reviews

Web Development Using PHP And MySQL

3K
Web Development Using PHP And MySQL

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create dynamic web pages that can interact with databases. It is a widely-used open source language that is specifically used for web application development and can be embedded within HTML.

Why PHP?

The distinguishing feature of PHP is that the scripting code is executed on the server, which generates HTML that is sent back to the client. The client receives the result of executing the script without knowing the underlying code. Developers can configure the web server to process all the HTML files (containing the PHP script).

PHP course is easy to learn for any newcomer, but also offers advanced programming features.

Using PHP with a database system

PHP, as a scripting language, is popular among web developers because of its ability to interact with database systems including Oracle and MySQL.

This article discusses the use of PHP scripting language with the MySQL database. Any website can require a variety of data or information to display and to retrieve them from the database. This can include display of a simple list to the running of the website based on data stored in the database.

Listed below are some examples where PHP and MySQL can be used together:

• Digital Ad banners, where the PHP script can be used to retrieve a digital banner from the database, which then selects a random banner from its table records and sends it back to the calling script. The PHP script can also maintain a count of banner views and clicks from the website.

• Internet forums or digital boards, which use PHP and MySQL to store and retrieve user messages.

• Website designing, where the design of an entire website can be changed using a couple of PHP scripts, instead of changing and uploading each web page. The PHP script can access the MySQL database to retrieve all information about the web page.

Setting up the MySQL database

The procedure of setting up the MySQL database varies according to the host. Every database would require a user name and password, in order to access the database.

Database administration can be done using PHP scripts or using a program like PHPMyAdmin.

The next step is to create the database tables for storing the website information. Creating a database table using PHPMyAdmin is also simple. Alternatively, one can create and configure the entire database using the following PHP script:

CREATE TABLE tablename {

Fields

}
Where the Fields are coded as fieldname type(length) extra_info

Example: first varchar(15) NOT NULL

The following command is used in the PHP script to connect to the MySQL database:

mysql_connect(localhost,$username,$password);

where:

• localhost is the server address on which the web site is running,

• $username is the user name for the database access

• $password is the password for the database access

Executing PHP commands

After configuring and connecting to the MySQL database, you can start executing PHP commands on the server.

Following are the 2 methods of executing a PHP command:
• Entering the command in PHP using the following syntax:

Mysql_query($query)

This form of command can be used to repeat the command simply by changing the variable.

• Defining the command as a variable. The result of the operation will be assigned to the variable.

Data input and output

Inserting data using PHP is identical to the procedure of data input using HTML pages. The advantage of using PHP is that the script does not need to be changed for each new piece of input data. Users can also input their own data on the web page.

Following is an example of an HTML page with textboxes that can be used to enter data in a form:

Alternatively, you can use variables to input information into the database. Example:

$first=$_POST[‘first’];

$last=$_POST[‘last’];

$phone=$_POST[‘phone’];

$mobile=$_POST[‘mobile’];

$fax=$_POST[‘fax’];

$email=$_POST[’email’];

$web=$_POST[‘web’];

$query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”;

mysql_query($query);

This script is saved in the insert.php file, which can be called from the HTML form. Using this method, data entered in the web page form is stored in the defined variables, which are then passed to the PHP.

To display (or output) the entered data using PHP, you can use the following MySQL command with the result assigned to the variable.

$query=”SELECT * FROM contacts”;

$result=mysql_query($query);

PHP provides 2 submission methods, GET and POST to get the data submitted by the form into your PHP script. GET method displays the variables and the data in the page address, while they are invisible in the POST method. For example, a script can be created that will display different web pages depending on the clicked link.

yourpage.php?user=david (to show David’s page)

yourpage.php?user=tom (to show Tom’s page)

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is a fast growing Management Consulting and Training firm that is a source of Intelligent Information support for businesses and professionals across the globe.


Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

9 comments

Reyes Levar 02 Feb 2017

I was very pleased to find this web-site.I wanted to thanks for your time for this wonderful read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you blog post.

Mahesh 08 Feb 2017

Sir, Very Useful Guide For PHP web development. for The connecting Database and Here are some queries which is very useful to me. Thank You sir.

http://stackoverflow.com.Minilinx.com/Contact 13 Feb 2017

Just want to say your article is as amazing. The clarity in your publish is jhst great and that i can assume yyou are an expert on this subject. Welll along with your permission allow me to take hold of your feed to keep up to date with forthcoming post. Thank you 1,000,000 and please carry oon the gratifying work.

lily 07 Jul 2017

PHP web development very use full for me from develop the web site and same queries very use full thank you sharing this post

deepa 28 Apr 2018

Thanks For Your valuable posting, it was very informative

satya 25 May 2018

Interesting topic, Well explanation. Thanks for sharing this article. Really very useful one for our php developers.

Yamini 04 Jul 2018

Thanks For Your valuable posting, it was very informative.

Udit Khanna 17 Jul 2018

Thanks for sharing such awesome article...

Manish Mehta 17 Jul 2018

It was really helpful. You guys are doing a great job. Keep Sharing!

Suggested Blogs

How to Stand Out in a Python Coding Interview - Functions, Data Structures & Libraries

Any coding interview is a test which primarily focuses on your technical skills and algorithm knowledge. However, if you want to stand out among the hundreds of interviewees, you should know how to use the common functionalities of Python in a convenient manner.The type of interview you might face can be a remote coding challenge, a whiteboard challenge or a full day on-site interview. So if you can prove your coding skills at that moment, the job letter will reach you in no time. You may go through some of the top Python interview questions and answers provided by experts which are divided into three levels- beginner, intermediate and advanced. A thorough practice of these questions and answers on Python will definitely help you achieve your dream job as a Python Developer, Full Stack engineer, and other top profiles.A Python coding interview is basically a technical interview. They are not just about solving problems, they are more about how technically sound you are and how you can write clean productive Python code. This will show your depth of knowledge about Python and how you can use Python’s built-in functions and libraries to implement your code. Go through our Python Tutorials to learn more about  concepts related to Python. Let us look into some of the built-in functions provided by Python and how to select the correct one, learn about the effective use of data structures, how standard libraries in Python can be utilized and so on.How to Select the Correct Built-in Function?Python’s library of built-in functions is small as compared to the standard library. The built-in functions are always available and are not needed to be imported. It is suggested to learn each function before sitting for the interview. Till then, let us learn a few built-in functions and how to use them and also what alternatives can be used.Perform iteration with enumerate() instead of range() Consider a situation during a coding interview: You have a list of elements and you have to iterate over the list with the access to both the indices and values. To differentiate between iteration with enumerate()  and iteration with range(), let us take a look at the classic coding interview question FizzBuzz. It can be solved by iterating over both indices and values. You will be given a list of integers and your task will be as follows:Replace all integers that are evenly distributed by 3 with “fizz”.Replace all integers divisible by 5 with “buzz”.Replace all integers divisible by 3 and 5 with “fizzbuzz”.Developers make use of range() in these situations which can access the elements by index:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i in range(len(list_num)):       if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:           list_num[i] = 'fizzbuzz'       elif list_num[i] % 3 == 0:           list_num[i] = 'fizz'       elif list_num[i] % 5 == 0:           list_num[i] = 'buzz'   >>> list_num ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']Though range() can be used in a lot of iterative methods, it is better to use enumerate() in this case since it can access the element’s index and value at the same time:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i,num in enumerate(list_num):       if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:           list_num[i] = 'fizzbuzz'       elif list_num[i] % 3 == 0:           list_num[i] = 'fizz'       elif list_num[i] % 5 == 0:           list_num[i] = 'buzz' >>> list_num ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']The enumerate() function returns a counter and the element value for each element. The counter is set to 0 by default which is also the element’s index.  However, if you are not willing to start your counter from 0, you can set an offset using the start parameter:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i, num in enumerate(list_num, start=11):       print(i, num) 11 3012 2913 1014 6514 9516 99You can access all of the same elements using the start parameter. However, the count will start from the specified integer value.Using List Comprehensions in place of map() and filter()Python supports list comprehensions which are easier to read and are analogous in functionality as map() and filter(). This is one of the reasons why Guido van Rossum, the creator of Python felt that dropping map() and filter() was quite uncontroversial.An example to show  map() along with this equivalent list comprehension:>>> list_num = [1, 2, 3, 4, 5, 6] >>> def square_num(z): ...    return z*z ... >>> list(map(square_num, list_num)) [1, 4, 9, 16, 25, 36] >>> [square_num(z) for z in numbers] [1, 4, 9, 16, 25, 36]Though map() and list comprehension returns the same values but the list comprehension part is easier to read and understand.An example to show  filter() and its equivalent list comprehension:>>> def odd_num_check(z):       return bool(z % 2)   >>> list(filter(odd_num_check, num_list)) [1, 3, 5] >>> [z for z in numbers if odd_num_check(z)] [1, 3, 5]It is the same with filter()as it was with map(). The return values are the same but the list comprehension is easier to follow.List comprehensions are easier to read and beginners are able to catch it more intuitively.Though other programming language developers might argue to the fact but if you make use of list comprehensions during your coding interview, it is more likely to communicate your knowledge about the common functionalities to the recruiter.Debugging With breakpoint() instead of print() Debugging is an essential part of writing software and it shows your knowledge of Python tools which will be useful in developing quickly in your job in the long run. However, using print() to debug a small problem might be good initially but your code will become clumsy. On the other hand, if you use a debugger like breakpoint(), it will always act faster than print().If you’re using Python 3.7, you can simply call breakpoint() at the point in your code where you want to debug without the need of importing anything:# Complicated Code With Bugs ... ... ... breakpoint()Whenever you call breakpoint(), you will be put into The Python Debugger - pdb. However, if you’re using Python 3.6 or older, you can perform an explicit importing which will be exactly like calling breakpoint():import pdb; pdb.set_trace()In this example, you’re being put into the pdb by the pdb.set_trace().  Since it’s a bit difficult to remember, it is recommended to use breakpoint() whenever a debugger is needed. There are also other debuggers that you can try. Getting used to debuggers before your interview would be a great advantage but you can always come back to pdb since it’s a part of the Python Standard Library and is always available. Formatting Strings with the help of f-StringsIt can be confusing to know what type of string formatting should we use since Python consists of a number of different string formatting techniques. However, it is a good approach and is suggested to use Python’s f-strings during a coding interview for Python 3.6 or greater.Literal String Interpolation or f-strings is a powerful string formatting technique that is more readable, more concise, faster and less prone to error than other formatting techniques. It supports the string formatting mini-language which makes string interpolation simpler. You also have the option of adding new variables and Python expressions and they can be evaluated before run-time:>>> def name_and_age(name, age):       return f"My name is {name} and I'm {age / 10:.5f} years old."   >>> name_and_age("Alex", 21) My name is Alex and I'm 2.10000 years old.The f-string allows you to add the name Alex into the string and his corresponding age with the type of formatting you want in one single operation.Note that it is suggested to use Template Strings if the output consists of user-generated values.Sorting Complex Lists with sorted()There are a lot of interview questions that are mostly based on sorting and it is one of the most important concepts you should be clear about before you sit for a coding interview. However, it is always a better option to use sorted() unless you are asked to make your own sorting algorithm by the interviewer.Example code to illustrate simple uses of sorting like sorting numbers or strings:>>> sorted([6,5,3,7,2,4,1]) [1, 2, 3, 4, 5, 6, 7] >>> sorted(['IronMan', 'Batman', 'Thor', 'CaptainAmerica', 'DoctorStrange'], reverse=False) ['Batman', 'CaptainAmerica', 'DoctorStrange', 'IronMan', 'Thor']sorted() performs sorting in ascending order by default and also when the reverse argument is set to False. If you sorting complex data types, you might want to add a function which allows custom sorting rules:>>> animal_list = [ ...    {'type': 'bear', 'name': 'Stephan', 'age': 9}, ...    {'type': 'elephant', 'name': 'Devory', 'age': 5}, ...    {'type': 'jaguar', 'name': 'Moana', 'age': 7}, ... ] >>> sorted(animal_list, key=lambda animal: animal['age']) [     {'type': 'elephant', 'name': 'Devory', 'age': 5},     {'type': 'jaguar', 'name': 'Moana', 'age': 7},     {'type': 'bear, 'name': 'Stephan, 'age': 9}, ]You can easily sort a list of dictionaries using the lambda keyword. In the example above, the lambda returns each element’s age and the dictionary is sorted in ascending order by age.Effective Use of Data StructuresData Structures are one of the most important concepts you should know before getting into an interview and if you choose the perfect data structure during an interviewing context, it will certainly impact your performance. Python’s standard data structure implementations are incredibly powerful and give a lot of default functionalities which will surely be helpful in coding interviews.Storing Values with SetsMake use of sets instead of lists whenever you want to remove duplicate elements from an existing dataset.Consider a function random_word that always returns a random word from a set of words:>>> import random >>> words = "all the words in the world".split() >>> def random_word():       return random.choice(words)In the example above, you need to call random_word repeatedly to get 1000 random selections and then return a data structure that will contain every unique word.Let us look at three approaches to execute this – two suboptimal approaches and one good approach.Bad Approach An example to store values in a list and then convert into a set:>>> def unique_words():       words = []       for _ in range(1000):           words.append(random_word())       return set(words) >>> unique_words() {'planet', 'earth', 'to', 'words'}In this example, creating a list and then converting it into a set is an unnecessary approach. Interviewers notice this type of design and questions about it generally.Worse ApproachYou can store values into a list to avoid the conversion from list to a set. You can then check for the uniqueness by comparing new values with all current elements in the list:>>> def unique_words():       words = []       for _ in range(1000):     word = unique_words()     if word not in words:     words.append(word)       return words >>> unique_words() {'planet', 'earth', 'to', 'words'}This approach is much worse than the previous one since you have to compare every word to every other word already present in the list. In simple terms, the time complexity is much greater in this case than the earlier example.Good ApproachIn this example, you can skip the lists and use sets altogether from the beginning:>>> def unique_words():       words = set()       for _ in range(1000):           words.add(random_word())       return words >>> unique_words() {'planet', 'earth', 'to', 'words'}This approach differs from the second approach as the storing of elements in this approach allows near-constant-time-checks whether a value is present in the set or not whereas linear time-lookups were required when lists were used. The time complexity for this approach is O(N) which is much better than the second approach whose time complexity grew at the rate of O(N²).Saving Memory with GeneratorsThough lists comprehensions are convenient tools, it may lead to excessive use of memory.Consider a situation where you need to find the sum of the first 1000 squares starting with 1 using list comprehensions:>>> sum([z * z for z in range(1, 1001)])333833500Your solution returns the correct answer by making a list of every perfect square and then sums the values. However, the interviewer asks you to increase the number of perfect squares. Initially, your program might work well but it will gradually slow down and the process will be changed completely.  However, you can resolve this memory issue just by replacing the brackets with parentheses:>>> sum((z * z for z in range(1, 1001)))333833500When you make the change from brackets to parentheses, the list comprehension changes to generator expressions. It returns a generator object. The object calculates the next value only when asked. Generators are mainly used on massive sequences of data and in situations when you want to retrieve data from a sequence but don’t want to access all of it at the same time.Defining Default Values in Dictionaries with .get() and .setdefault()Adding, modifying or retrieving an item from a dictionary is one of the most primitive tasks of programming and it is easy to perform with Python functionalities. However, developers often check explicitly for values even its not necessary.Consider a situation where a dictionary named shepherd exists and you want to get that cowboy’s name by explicitly checking for the key with a conditional:>>> shepherd = {'age': 20, 'sheep': 'yorkie', 'size_of_hat': 'large'} >>> if 'name' in shepherd:       name = shepherd['name']     else:       name = 'The Man with No Name'   >>> nameIn this example, the key name is searched in the dictionary and the corresponding value is returned otherwise a default value is returned.You can use .get() in a single line instead of checking keys explicitly:>>> name = shepherd.get('name', 'The Man with No Name')The get() performs the same operation as the first approach does, but they are now handled automatically. However, .get() function does not help in situations where you need to update the dictionary with a default value while still accessing the same key. In such a case, you again need to use explicit checking:>>> if 'name' not in shepherd:       shepherd['name'] = 'The Man with No Name'   >>> name = shepherd['name']However, Python still offers a more elegant way of performing this approach using .setdefault():>>> name = shepherd.setdefault('name', 'The Man with No Name')The .setdefault() function performs the same operation as the previous approach did. If name exists in shepherd, it returns a value otherwise it sets shepherd[‘name’]  to The Man with No Name and returns a new value.Taking Advantage of the Python Standard LibraryPython’s functionalities are powerful on its own and all the things can be accessed just by using the import statement. If you know how to make good use of the standard library, it will boost your coding interview skills.How to handle missing dictionaries?You can use .get() and .setdefault() when you want to set a default for a single key. However, there will be situations where you will need to set a default value for all possible unset keys, especially during the context of a coding interview.Consider you have a  group of students and your task is to keep track of their grades on assignments. The input value is a tuple with student_name and grade. You want to look upon all the grades for a single student without iterating over the whole list. An example to store grade data using a dictionary:>>> grades_of_students = {} >>> grades = [       ('alex', 89),       ('bob', 95),       ('charles', 81),       ('alex', 94),       ] >>> for name, grade in grades:       if name not in grades_of_student:           grades_of_student[name] = []       grades_of_student[name].append(grade) >>> student_grades{'alex': [89, 94], 'bob': [95], 'charles': [81]}In the example above, you iterate over the list and check if the names are already present in the dictionary or not. If it isn’t, then you add them to the dictionary with an empty list and then append their actual grades to the student’s list of grades.However, the previous approach is good but there is a cleaner approach for such cases using the defaultdict:>>> from collections import defaultdict >>> student_grades = defaultdict(list) >>> for name, grade in grades:       student_grades[name].append(grade)In this approach, a defaultdict is created that uses the list() with no arguments. The list()returns an empty list. defaultdict calls the list() if the name does not exist and then appends the grade.Using the defaultdict, you can handle all the common default values at once and need not worry about default values at the key level. Moreover, it generates a much cleaner application code.How to Count Hashable Objects?Pretend you have a long string of words with no punctuation or capital letters and you are asked to count the number of the appearance of each word. In this case, you can use collections.Counter that uses 0 as the default value for any missing element and makes it easier and cleaner to count the occurrence of different objects:>>> from collections import Counter >>> words = "if I am there but if \ ... he was not there then I was not".split() >>> counts = Counter(words) >>> countsCounter({'if': 2, 'there': 2, 'was': 1, 'not': 2, 'but': 1, ‘I’: 2, ‘am’: 1, }When the list is passed to Counter, it stores each word and also the number of occurrences of that word in the list.If you want to know the two most common words in a list of strings like above, you can use .most_common() which simply returns the n most frequently inputs by count:>>> counts.most_common(2)[('if': 2), ('there': 2), ('not': 2), (‘I’: 2)]How to Access Common String Groups?If you want to check whether ‘A’ > ‘a’ or not, you have to do it using the ASCII chart. The answer will be false since the ASCII value for A is 65 and a is 97, which is clearly greater. However, it would be a difficult task to remember the ASCII code when it comes to lowercase and uppercase ASCII characters and also this method is a bit clumsy. You can use the much easier and convenient constants which are a part of the string module. An example to check whether all the characters in a string are uppercase or not:>>> import string >>> def check_if_upper(word):       for letter in word:           if letter not in string.ascii_uppercase:               return False       return True   >>> check_if_upper('Thanks Alex') False >>> check_if_upper('ROFL') TrueThe function check_if_upper iterates over the letters in words, and checks whether the letters are part of string.ascii_uppercase. It is set to the literal ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.There are a number of string constants that are frequently used for referencing string values that are easy to read and use. Some of which are as follows:string.ascii_lettersstring.ascii_upercasestring.ascii_lowercasestring.ascii_digitsstring.ascii_hexdigitsstring.ascii_octdigitsstring.ascii_punctuationstring.ascii_printablestring.ascii_whitespaceConclusionClearing interview with confidence and panache is a skill. You might be a good programmer but it’s only a small part of the picture. You might fail to clear a few interviews, but if you follow a good process, it will certainly help you in the long run. Being enthusiastic is an important factor that will have a huge impact on your interview results. In addition to that is practice. Practice always helps. Brush up on all the common interview concepts and then head off to practicing different interview questions. Interviewers also help during interviews if you can communicate properly and interact. Ask questions and always talk through a brute-force and optimized solution.Let us now sum up what we have learned in this article so far:To use enumerate() to iterate over both indices and values.To debug problematic code with breakpoint().To format strings effectively with f-strings.To sort lists with custom arguments.To use generators instead of list comprehensions to save memory.To define default values when looking up dictionary keys.To count hashable objects with collections.Counter class.Hope you have learned about most of the powerful Python’s built-in functions, data structures, and standard library packages that will help you in writing better, faster and cleaner code. Though there are a lot of other things to learn about the language, join our Python certification course to gain more skills and knowledge.
Rated 4.5/5 based on 14 customer reviews
5876
How to Stand Out in a Python Coding Interview - Fu...

Any coding interview is a test which primarily foc... Read More

How To Run Your Python Scripts

If you are planning to enter the world of Python programming, the first and the most essential skill you should learn is knowing how to run Python scripts and code. Once you grab a seat in the show, it will be easier for you to understand whether the code will actually work or not.Python, being one of the leading programming languages, has relatively easy syntax which makes it even easier for the ones who are in their initial stage of learning the language. Also, it is the language of choice for working with large datasets and data science projects. Get certified and learn more about Python Programming and apply those skills and knowledge in the real world.What is the difference between Code, Script and Modules?In computing, the code is a language that is converted from a human language into a set of ‘words’ which the computer can understand. It is also referred to as a piece of statements together which forms a program. A simple function or a statement can also be considered a code.On the other hand, a script is a file consisting of a logical sequence of instructions or a batch processing file that is interpreted by another program instead of the computer processor.In simple terms, a script is a simple program, stored in a plain file text which contains Python code. The code can be directly executed by the user. A script is also called a top-level-program-file. A module is an object in Python with random attributes that you can bind and reference.Is Python a Programming Language or a Scripting Language?Basically, all scripting languages are considered to be programming languages. The main difference between the two is that programming languages are compiled, whereas scripting languages are interpreted. Scripting languages are slower than programming languages and usually sit behind them. Since they only run on a subset of the programming language, they have less access to a computer’s local abilities. Python can be called a scripting language as well as a programming language since it works both as a compiler and an interpreter. A standard Python can compile Python code into bytecodes and then interpret it just like Java and C.However, considering the historical relationship between the general purpose programming language and the scripting language, it will be more appropriate to say that Python is a general-purpose programming language which works nicely as a scripting language too.The Python InterpreterThe Interpreter is a layer of software that works as a bridge between the program and the system hardware to keep the code running. A Python interpreter is an application which is responsible for running Python scripts.The Python Interpreter works on the Read-Eval-Print-Loop (REPL) environment.Reads the command.Evaluates the command.Prints the result.Loops back and process gets repeated.The interpreter terminates when we use the exit() or quit() command otherwise the execution keeps on going.A Python Interpreter runs code in two ways— In the form of a script or module.In the form of a piece of code written in an interactive session.Starting the Python InterpreterThe simplest way to start the interpreter is to open the terminal and then use the interpreter from the command-line.To open the command-line interpreter:On Windows, the command-line is called the command prompt or MS-DOS console. A quicker way to access it is to go to Start menu → Run and type cmd.On GNU/Linux, the command-line can be accessed by several applications like xterm, Gnome Terminal or Konsole.On MAC OS X, the system terminal is accessed through Applications → Utilities → Terminal. Running Python Code InteractivelyRunning Python code through an interactive session is an extensively used way. An interactive session is an excellent development tool to venture with the language and allows you to test every piece of Python code on the go.To initiate a Python interactive session, type python in the command-line or terminal and hit the ENTER key from the keyboard.An example of how to do this on Windows:C:\users>python Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>>The >>> on the terminal represents the standard prompt for the interactive mode. If you do not see these characters, you need to re-install Python on your system.The statements you write when working with an interactive session are evaluated and executed immediately:print('HELLO WORLD!') HELLO WORLD! 2 + 3 5 print('Welcome to the world of PYTHON') Welcome to the world of PYTHON The only disadvantage is when you close the interactive session, the code no longer exists.Running Python Scripts by the InterpreterThe term Python Execution Model is given to the entire multi-step process to run Python scripts.At first, the statements or expressions of your script are processed in a sequential manner by the interpreter. Then the code is compiled into a form of instruction set called the bytecode.Basically, the code is converted into a low-level language known as the bytecode. It is an intermediate, machine-independent code which optimizes the process of code execution. So, the interpreter ignores the compilation step when executing the code for the next time.Finally, the interpreter transfers the code for execution.The Python Virtual Machine (PVM) is the ultimate step of the Python interpreter process. It is a part of the Python environment installed in your system. The PVM loads the bytecode in the Python runtime and reads each operation and executes them as indicated. It is the component which actually runs your scripts.Running Python Scripts using Command-LineThe most sought after way of writing a Python program is by using a plain text editor. The code written in the Python interactive session is lost once the session is closed, though it allows the user to write a lot of lines of code. On Windows, the files use the .py extension.  If you are at the beginning of working with Python, you can use editors like Sublime or Notepad++ which are easy-to-use or any other text editors.Now you need to create a test script. In order to do that, open your most suited text editor and write the following code:print('Hello World!')Then save the file in your desktop with the name first_script.py or anything you like. Remember you need to give the .py extension only.Using python commandThe most basic and the easy way to run Python scripts is by using the python command. You need to open a command-line and type the word python followed by the path to your script file, like this:python first_script.py Hello World!Then you hit the ENTER button from the keyboard and that's it. You can see the phrase Hello World! on the screen. Congrats! You just ran your first Python script. However, if you do not get the output, you might want to check your system PATH and the place where you saved your file. If it still doesn’t work, re-install Python in your system and try again.Redirecting outputWindows and Unix-like systems have a process called stream redirection. You can redirect the output of your stream to some other file format instead of the standard system output. It is useful to save the output in a different file for later analysis.An example of how you can do this:python first_script.py > output.txtWhat happens is your Python script is redirected to the output.txt file. If the file doesn’t exist, it is systematically created. However, if it already exists, the contents are replaced.Running modules with the -m optionA module is a file which contains the Python code. It allows you to arrange your Python code in a logical manner. It defines functions, classes, and variables and can also include runnable code.If you want to run a Python module, there are a lot of command-line options which Python offers according to the needs of the user. One of which is the command  python -m . It searches the module name in the sys.path and runs the content as __main__:python -m first_script Hello World!Note that the module-name is a module object and not any string.Using Script FilenameWindows makes use of the system registers and file association to run Python scripts. It determines the program needed to run that particular file. You need to simply enter the file-name containing the code.An example on how to do this using command prompt:C:\Users\Local\Python\Python37> first_script.py Hello World!On GNU/Linux systems, you need to add a line before the text— #!/usr/bin/env python. Python considers this line nothing but the operating system considers it everything. It helps the system to decide what program should it use to run the file.The character combination #! known as hashbang or shebang is what the line starts with, which is then followed by the interpreter path.Finally, to run scripts, assign execution permissions and configure the hashbang line and then simply type the filename in the command line:#Assign the execution permissions chmod +x first_script.py #Run script using its filename ./first_script.py Hello World!However, if it doesn’t work, you might want to check if the script is located in your currentworking directory or not. Otherwise, you can use the path of the file for this method. Running Python Scripts InteractivelyAs we have discussed earlier, running Python scripts in an interactive session is the most common way of writing scripts and also offers a wide range of possibilities.Using importImporting a module means loading its contents so that it can be later accessed and used. It is the most usual way of invoking the import machinery. It is analogous to #include in C or C++. Using import, the Python code in one module gets access to the code in another module. An implementation of the import:import first_script Hello World!You can see its execution only when the module contains calls to functions, methods or other statements which generate visible output.One important thing to note is that the import option works only once per session. This is because these operations are expensive.For this method to work efficiently, you should keep the file containing the Python code in your current working directory and also the file should be in the Python Module Search Path (PMSP). The PMSP is the place where the modules and packages are imported.You can run the code below to know what’s in your current PSMP:import sys for path in sys.path: print(path)\Users\Local\Python37\Lib\idlelib \Users\Local\Python37\python37.zip \Users\Local\Python37\DLLs \Users\Local\Python37\lib \Users\Local\Python37 \Users\Local\Python37\lib\site-packagesYou’ll get the list of directories and .zip files where your modules and packages are imported.Using importlibimportlib is a module which is an implementation of the import statement in the Python code. It contains the import_module whose work is to execute any module or script by imitating the import operation.An example to perform this:import importlib importlib.import_module('first_script') Hello World! importlib.reload() is used to re-import the module since you cannot use import to run it for the second time. Even if you use import after the first time, it will do nothing. importlib.reload() is useful when you want to modify and test your changes without exiting the current session.The following code shows that:import first_script #First import Hello World! import first_script import importlib #Second import does nothing importlib.reload(first_script) Hello World! However, you can only use a module object and not any string as the argument of reload(). If you use a string as an argument, it will show a TypeError as follows:importlib.reload(first_script)Traceback (most recent call last): ... ...   raise TypeError("reload() argument must be a module") TypeError: reload() argument must be a moduleUsing runpy.run_module() and runpy.run_path()The Python Standard Library has a module named runpy. run_module() is a function in runpy whose work is to execute modules without importing them in the first place. The module is located using import and then executed. The first argument of the run_module() must contain a string:import runpy runpy.run_module(mod_name='first_script') Hello World! {'__name__': 'first_script',     ... '_': None}}Similarly, runpy contains another function run_path() which allows you to run a module by providing a location.An example of such is as follows:import runpy runpy.run_path(file_path='first_script.py') Hello World! {'__name__': '',     ... '_': None}}Both the functions return the globals dictionary of the executed module.Using exec()Other than the most commonly used ways to run Python scripts, there are other alternative ways. One such way is by using the built-in function exec(). It is used for the dynamic execution of Python code, be it a string or an object code.An example of exec() is:exec(open('first_script.py').read()) Hello World!Using py_compilepy_compile is a module which behaves like the import statement. It generates two functions— one to generate the bytecode from the source file and another when the source file is invoked as a script.You can compile your Python script using this module:import py_compile py_compile.compile('first_script.py'  '__pycache__\\first_script.cpython-37.pyc' The py_compile generates a new subdirectory named "__pycache__" if it doesn’t already exist. Inside the subdirectory, a Compiled Python File (.pyc) version of the script file is created. When you open the .pyc file, you can see the output of your Python script.Running Python Scripts using an IDE or a Text EditorAn Integrated Development Environment (IDE) is an application that allows a developer to build software within an integrated environment in addition to the required tools.You can use the Python IDLE, a default IDE of the standard Python Distribution to write, debug, modify, and run your modules and scripts. You can use other IDEs like Spyder, PyCharm, Eclipse, and Jupyter Notebook which also allow you to run your scripts inside its environment.You can also use popular text editors like Sublime and Atom to run Python scripts.If you want to run a Python script from your IDE or text editor, you need to create a project first. Once it is created, add your .py file to it or you can just simply create one using the IDE. Finally, run it and you can see the output in your screen.Running Python Scripts from a File ManagerIf you want to run your Python script in a file manager, all you need to do is just double-click on the file icon. This option is mainly used in the production stage after you have released the source code.However, to achieve this, some conditions must be met:On Windows, to run your script by double-clicking on them, you need to save your script file with extension .py for python.exe and .pyw for pythonw.exe.If you are using the command-line for running your script, you might likely come  through a situation where you’ll see a flash of a black window on the screen. To avert this, include a statement at the tail of the script — input(‘Enter’). This will exit the program only when you hit the ENTER key. Note that the input() function will work only if your code is free of errors.On GNU/Linux and other Unix-like systems, your Python script must contain the hashbang line and execution permissions. Otherwise, the double-click trick won’t work in a file manager.Though it is easy to execute a script by just double-clicking on the file, it isn’t considered a feasible option because of the limitations and dependency factors it comes with, like the operating system, the file manager, execution permissions, and also the file associations.So it is suggested to use this option only after the code is debugged and ready to be in the production market.ConclusionWorking with scripts has its own advantages like they are easy to learn and use, faster edit and run, interactivity, functionality and so on. They are also used to automate complex tasks in a simplified manner.In this article, you have learned to run your Python scripts using:The terminal or the command-line of the operating system.The Python Interactive session.Your favorite IDE or text editor.The system file manager.Here, you have gathered the knowledge and skills of how to run your scripts using various techniques.You will feel more comfortable working with larger and more complex Python environments which in turn will enhance the development process and increase efficiency. You can learn more about such techniques as KnowledgeHut offers Python Certification Course.
Rated 4.5/5 based on 19 customer reviews
5935
How To Run Your Python Scripts

If you are planning to enter the world of Python p... Read More

Python Vs Scala

Created by Guido Rossum, Python is an object-oriented, high-level performing programming language which focuses on code readability. Python has several new features like it requires less typing, provides new libraries, fast prototyping, etc. It provides with dynamic typing and dynamic binding options, making it extremely attractive in the field of Rapid Application Development.Designed by Martin Odersky, Scala is also an object-oriented programming language that also supports the functional style of programming, but on a larger scale. It gets its name as a combination of the words ‘scalable’ and ‘language’, where it can scale according to the number of users. With time, it has become one of the most in-demand technologies amongst the developers.Both Python and Scala play very crucial roles in the growth and future of Data Science, Big Data, and Cluster computing. Below are a few major differences between Python and Scala.Major Differences between Python and ScalaSr No. PythonScala1.Python is a dynamically typed language.Scala is a statically typed language.2.Since it is dynamically typed Object Oriented Programming language, objects need not be specified.Since it is statically typed Object Oriented Programming language, the type of variable and objects are needed to be specified.3.Dynamically typed language creates extra work for the interpreter at the run time. It has to decide the type of data at run time.There is no extra work in Scala, as it uses JVM. Hence, it is 10 times faster than Python.4.It decides the type of data at the run time.This isn’t the case for Scala. Hence, Scala should be considered instead of Python when dealing with large data process.5.Python has huge community support.Scala has good community support as well, but it is lesser when compared to Python.6.Testing process and its methodologies are complex in Python because it is a dynamic programming language.Testing is done better in Scala as it is a statically typed language.7.Python supports the forked process, which is a heavyweight process, while it does not support multithreading.Scala has relative cores and a list of asynchronous libraries. Hence, it is a better option for implementing concurrency.8.Python is very popular thanks to its easy and English-like syntax.For scalable and concurrent systems like SoundCloud and Twitter, Scala plays much bigger.9.It is easy to learn and use.It is less difficult to learn than Python.10.Python is slower in terms of performance.Scala is 10 times faster than Python.11.Developers find it easy to code in Python.Scala isn’t easy to master due to its syntactic sugars.12.Whenever any change is made to the existing code, Python becomes prone to bugs.Scala provides an interface to catch the compile-time error.13.Python has proper libraries and tools for data science, machine learning and  Natural Language Processing (NLP).Scala does not have any such tools.14.Python has an interface for various OS system calls and libraries. It has many interpreters as well.Scala is a compiled language and hence, the source codes are compiled before execution.15.Python can be used for small-scale projects.Scala can be used for large-scale projects.16.Python does not provide with scalable feature support.Scala provides scalable feature support.Key differences between Python and ScalaThe key differences between Python and Scala are explained in the points mentioned below:Python language is dynamically typed, while Scala is statically typed.Development is faster, rapid and more productive in Python as it doesn’t need any compilation for most of its cases. While in the case of Scala, the process of compilation is slow. Hence, the development of Scala application takes more time.There are several platforms available for Python, but CPython is most widely used, whereas, applications run in JVM when it comes to Scala.As per task complexities, python has huge libraries, whereas, for Scala, it has small libraries.Python uses a decent amount of memory, while Scala has more memory consumption.Python is easier to learn than Scala.Since Python is a dynamic language, it executes slowly as compared to Scala.Python is less complex while testing as it is dynamic, while Scala is good for testing as it is static.Being a mature language, Python continues to grow. But Scala doesn’t have any widespread knowledge base or use.To conclude:We have compared Python and Scala over a range of factors, and it can be deduced that the selection of language depends on you and the requirements of your project. Hence, analyze and learn all the different artifacts of both Python and Scala before deciding on which one language. If you wish to excel in your career as a successful Python developer, you can opt for Python Certification with KnowledgeHut. Learn from the best! 
Rated 4.5/5 based on 4 customer reviews
6785
Python Vs Scala

Created by Guido Rossum, Python is an object-orien... Read More

Useful links