💻Introduction to Python
Last updated
Last updated
A variable is a named location used to store data in the memory. It is helpful to think of variables as a container that holds data that can be changed later in the program.
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Here, we have created 2 variables named number and name . We have assigned the values 10 and John to the variables.
A variable can have a short name (like x and y) or a more descriptive name (age, carname, totalvolume). 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)
Legal variable names:
Illegal variable names:
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Each word, except the first, starts with a capital letter:
Each word starts with a capital letter:
Each word is separated by an underscore character:
! The Style Guide for Python Code, also known as PEP 8, contains Naming Conventions that list suggested standards for names of different object types. PEP 8 includes the following recommendations:
Snake Case should be used for functions and variable names.
Pascal Case should be used for class names. (PEP 8 refers to this as the “CapWords” convention.)
There is one more restriction on identifier names. The Python language reserves a small set of keywords that designate special language functionality. No object can have the same name as a reserved word.
In Python 3.6, there are 33 reserved keywords:
You can think of variables as a bag to store books in it and that book can be replaced at any time.
Initially, the value of number was 10 . Later, it was changed to 1.1 .
In the above program, we have assigned apple.com to the website variable initially. Then, the value is changed to pycoders.nl .
Python allows you to assign values to multiple variables in one line:
Note: Make sure the number of variables matches the number of values, or else you will get an error.
If we want to assign the same value to multiple variables at once, we can do this as:
In the above program assigns the same string to all the three variables x , y and z .
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
You can also use the + character to add a variable to another variable:
For numbers, the + character works as a mathematical operator:
If you try to combine a string and a number, Python will give you an error:
Click the links below for some python variable exercises.
Click for further reading on python variables.
In programming, data type is an important concept. Variables can store data of different types, and different types can do different things.
In any assignment, the assigned value must always be a valid data type.
Python has the following data types built-in by default, in these categories:
Python is highly flexible about reassigning variables to different types:
We call this dynamic typing, since variables can change types readily
You can get the data type of any object by using the type() function:
In Python, the data type is set when you assign a value to a variable:
If you want to specify the data type, you can use the following constructor functions:
Python supports integers, floating-point numbers and complex numbers. They are defined as int , float , and complex classes in Python.
Integers and floating points are separated by the presence or absence of a decimal point. For instance, 5 is an integer whereas 5.0 is a floating-point number.
Complex numbers are written in the form, x + yj , where x is the real part and y is the imaginary part.
We can convert one type of number into another. This is also known as coercion.
Operations like addition, subtraction coerce integer to float implicitly (automatically), if one of the operands is float.
We can see above that 1 (integer) is coerced into 1.0 (float) for addition and the result is also a floating point number.
We can also use built-in functions like int() , float() and complex() to convert between types explicitly. These functions can even convert from strings.
When converting from float to integer, the number gets truncated (decimal parts are removed).
Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError . The index must be an integer. We can't use floats or other types, this will result into TypeError .
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator : (colon).
If we try to access an index out of the range or use numbers other than an integer, we will get errors.
To get the length of a string, use the len() function.
Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name.
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del keyword.
Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python. Simply writing two string literals together also concatenates them.
The * operator can be used to repeat the string for a given number of times.
We can test if a substring exists within a string or not, using the keyword in .
If we want to print a text like He said, "What's there?", we can neither use single quotes nor double quotes. This will result in a SyntaxError as the text itself contains both single and double quotes
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.
Here is a list of all the escape sequences supported by Python.
As seen in the above output, the first print statement produced an output where the \t got resolved into a vertical tab and is omitted in the output. On the other hand, in the second print statement, the \j persists, as no legal resolution for that sequence exists.
Consistently doubling the backslashes, also allows us to overcome such issues. In this method, we manually find every single backslash in the string and concatenate another backslash to it (at its immediate position). Generally, a tedious method, and only advised if the string size is less
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.
The format() method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces {} as placeholders or replacement fields which get replaced. We can use positional arguments or keyword arguments to specify the order.
The syntax is similar to the one you used with str.format() but less verbose. Look at how easily readable this is:
You can have multiline strings:
But remember that you need to place an f in front of each line of a multiline string.
Common Python String Methods
There are numerous methods available with the string object. The format() method that we mentioned above is one of them. Some of the commonly used methods are lower() , upper() , join() , split() , find() , replace() etc.
Here is a complete list of all the built-in methods to work with strings in Python.
The print() function prints the given object to the standard output device (screen) or to the text stream file.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Click for further reading on print function
The input() method reads a line from input, converts into a string and returns it.
The syntax of input() method is:
input([prompt])
The input() method takes a single optional argument:
prompt (Optional) - a string that is written to standard output (usually screen) without trailing newline
In programming you often need to know if an expression is True or False .
You can evaluate any expression in Python, and get one of two answers, True or False .
When you compare two values, the expression is evaluated and Python returns the Boolean answer:
The bool() function allows you to evaluate any value, and give you True or False in return,
In fact, there are not many values that evaluates to False , except empty values, such as () , [] , {} , "" , the number 0 , and the value None . And of course the value False evaluates to False .
Comparison operators are used to compare values. It returns either True or False according to the condition.
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5 .
is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical
In python, "==" and "is" are very similar comparators, however they are not the same
"is" is only true if the variables reference the same item in memory
Membership operators are used to test if a sequence is presented in an object:
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False .
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111 .
In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)
Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if…elif…else statement is used in Python for decision making.
1 if test expression:
2 statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True .
If the test expression is False , the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True . None and 0 are interpreted as False .
In the above example, num > 0 is the test expression.
The body of if is executed only if this evaluates to True .
When the variable num is equal to 3, test expression is true and statements inside the body of if are executed.
If the variable num is equal to -1, test expression is false and statements inside the body of if are skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test expression.
The if..else statement evaluates test expression and will execute the body of if only when the test condition is True .
If the condition is False , the body of else is executed. Indentation is used to separate the blocks.
In the above example, when num is equal to 3, the test expression is true and the body of if is executed and the body of else is skipped.
If num is equal to -5, the test expression is false and the body of else is executed and the body of if is skipped.
If num is equal to 0, the test expression is true and body of if is executed and body of else is skipped.
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False , it checks the condition of the next elif block and so on.
If all the conditions are False , the body of else is executed. Only one block among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.
We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary
Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in Python.
The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate beforehand.
In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True . After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates to False . In Python, the body of the while loop is determined through indentation.
The body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True . None and 0 are interpreted as False .
In the above program, the test expression will be True as long as our counter variable i is less than or equal to n (10 in our program).
We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).
Finally, the result is displayed.
The else part is executed if the condition in the while loop evaluates to False .
Here, we use a counter variable to print the string Inside loop three times.
On the fourth iteration, the condition in while becomes False . Hence, the else part is executed.
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Here is an example to illustrate this.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints No items left.
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start, stop,step_size) . step_size defaults to 1 if not provided.
To force this function to output all the items, we can use the function list() .
The following example will clarify this.
We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate through a sequence using indexing. Here is an example.
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.
The break and continue statements are used in these cases.
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.
If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
In this program, we iterate through the "string" sequence. We check if the letter is i, upon which we break from the loop. Hence, we see in our output that all the letters up till i gets printed. After that, the loop terminates.
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
This program is same as the above example except the break statement has been replaced with continue .
We continue with the loop, if the string is i, not executing the rest of the block. Hence, we see in our output that all the letters except i gets printed.
In Python programming, the pass statement is a null statement. The difference between a comment and a pass statement in Python is that while the interpreter ignores a comment entirely, pass is not ignored.
However, nothing happens when the pass is executed. It results in no operation (NOP).
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing.
data type
description
bool
True or False values
int
an integer (1, 2, 3)
str
(string) a sequence of Unicode characters, e.g. "PyCoders" or "程序设计"
list
an ordered sequence of values of other data types, e.g. [1, 2, 3] or ["a", "b", "c"]
dict
a collection of key: values, e.g. { "first_name": "Py", "last_name": "Coders" }