Python While Loop Tutorial

Python While Loop Tutorial

Last updated on 08th Oct 2020, Blog, Tutorials

About author

Sundar ((Sr Technical Project Manager ) )

He is a Proficient Technical Expert for Respective Industry & Serving 11+ Years. Also, Dedicated to Imparts the Informative Knowledge to Freshers. He Share's this Blogs for us.

(5.0) | 14547 Ratings 1835

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:

  • web development (server-side),
  • software development,
  • mathematics,
  • system scripting.

What can Python do?

  • Python can be used on a server to create web applications.
  • Python can be used alongside software to create workflows.
  • Python can connect to database systems. It can also read and modify files.
  • Python can be used to handle big data and perform complex mathematics.
  • Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

  • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-oriented way or a functional way.

Good to know :

  • The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
  • In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.
Subscribe For Free Demo

Error: Contact form not found.

Python Syntax compared to other programming languages :

  • Python was designed for readability, and has some similarities to the English language with influence from mathematics.
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
  • Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose

Python Getting Started :

Python Install :

Many PCs and Macs will have python already installed.

To check if you have python installed on a Windows PC, search in the start bar for Python or run the following on the Command Line (cmd.exe):

Python Quickstart :

Python is an interpreted programming language, this means that as a developer you write Python (.py) files in a text editor and then put those files into the python interpreter to be executed.

Python Variables :

Creating Variables :

Variables are containers for storing data values.

Unlike other programming languages, Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Variable Names :

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for Python variables:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)

Global Variables :

Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

Python Data Types :

Built-in Data Types :

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python Numbers :

There are three numeric types in Python:

  • int
  • float
  • complex

Variables of numeric types are created when you assign a value to them:

Int :

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Float :

Float, or “floating point number” is a number, positive or negative, containing one or more decimals.

Complex :

Complex numbers are written with a “j” as the imaginary part:

Type Conversion :

You can convert from one type to another with the int(), float(), and complex() methods:

Random Number :

Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers:

In our Random Module Reference you will learn more about the Random module.

Course Curriculum

Get Experts Curated Python Training with Industry Trends Concepts

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

Python Casting :

Specify a Variable Type :

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

  • int() – constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)
  • float() – constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
  • str() – constructs a string from a wide variety of data types, including strings, integer literals and float literals

Python Strings :

String Literals :

String literals in python are surrounded by either single quotation marks, or double quotation marks.

‘hello’ is the same as “hello”.

You can display a string literal with the print() function:

Assign String to a Variable :

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

Multiline Strings :

You can assign a multiline string to a variable by using three quotes:

Strings are Arrays :

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Python Operators :

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Loops :

Python has two primitive loop commands:

  • while loops

The while Loop :

With the while loop we can execute a set of statements as long as a condition is true.

The break Statement :

With the break statement we can stop the loop even if the while condition is true:

The continue Statement :

With the continue statement we can stop the current iteration, and continue with the next:

The else Statement :

With the else statement we can run a block of code once when the condition no longer is true:

Python Functions :

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function :

In Python a function is defined using the def

Arguments :

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

Number of Arguments :

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

Arbitrary Arguments, *args :

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.

Python Scope :

A variable is only available from inside the region it is created. This is called scope.

Local Scope :

A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

Function Inside Function :

As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function:

Global Scope :

A variable created in the main body of the Python code is a global variable and belongs to the global scope.

Global variables are available from within any scope, global and local.

Python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Naming Variables :

If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function):

Python Math :

Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.

Built-in Math Functions :

The min() and max() functions can be used to find the lowest or highest value in an iterable:

The Math Module :

Python has also a built-in module called math, which extends the list of mathematical functions.

When you have imported the math module, you can start using methods and constants of the module.

Python String Formatting :

To make sure a string will display as expected, we can format the result with the format() method.

String format()

The format() method allows you to format selected parts of a string.

Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input?

To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method:

Multiple Values :

If you want to use more values, just add more values to the format() method:

Index Numbers :

You can use index numbers (a number inside the curly brackets {0}) to be sure the values are placed in the correct placeholders:

Named Indexes :

You can also use named indexes by entering a name inside the curly brackets {carname}, but then you must use names when you pass the parameter values txt.format(carname = “Ford”):

Are you looking training with Right Jobs?

Contact Us

Popular Courses