Constants in Python
Constants in Python
Summary: in this tutorial, you’ll learn about the basic Python syntax so that you can get started
with the Python language quickly.
However, Python uses whitespace and indentation to construct the code structure.
The meaning of the code isn’t important to you now. Please pay attention to the code structure
instead.
At the end of each line, you don’t see any semicolon to terminate the statement. And the code
uses indentation to format the code.
By using indentation and whitespace to organize the code, Python code gains the following
advantages:
● First, you’ll never miss the beginning or ending code of a block like in other
programming languages such as Java or C#.
● Second, the coding style is essentially uniform. If you have to maintain another
developer’s code, that code looks the same as yours.
● Third, the code is more readable and clear in comparison with other programming
languages.
Comments
The comments are as important as the code because they describe why a piece of code was
written.
When the Python interpreter executes the code, it ignores the comments.
In Python, a single-line comment begins with a hash (#) symbol followed by the comment. For
example:
# This is a single line comment in Python
Continuation of statements
Python uses a newline character to separate statements. It places each statement on one line.
However, a long statement can span multiple lines by using the backslash (\) character.
The following example illustrates how to use the backslash (\) character to continue a
statement in the second line:
if (a == True) and (b == False) and \
(c == True):
print("Continuation of statements")
Identifiers
Identifiers are names that identify variables, functions, modules, classes, and other objects in
Python.
The name of an identifier needs to begin with a letter or underscore (_). The following
characters can be alphanumeric or underscore.
Python identifiers are case-sensitive. For example, the counter and Counter are different
identifiers.
Keywords
Some words have special meanings in Python. They are called keywords.
Python is a growing and evolving language. So its keywords will keep increasing and changing.
Python provides a special module for listing its keywords called keyword.
To find the current keyword list, you use the following code:
import keyword
print(keyword.kwlist)
String literals
Python uses single quotes ('), double quotes ("), triple single quotes (''') and triple-double
quotes (""") to denote a string literal.
The string literal need to be surrounded with the same type of quotes. For example, if you use a
single quote to start a string literal, you need to use the same single quote to end it.
Summary
Python Variables
Summary: in this tutorial, you’ll learn about Python variables and how to use them effectively.
In Python, a variable is a label that you can assign a value to it. And a variable is always
associated with a value. For example:
message = 'Hello, World!'
print(message)
In this example, message is a variable. It holds the string 'Hello, World!'. The print()
function shows the message Hello, World! to the screen.
The next line assigns the string 'Good Bye!' to the message variable and print its value to
the screen.
The variable message can hold various values at different times. And its value can change
throughout the program.
Creating variables
To define a variable, you use the following syntax:
variable_name = value
The = is the assignment operator. In this syntax, you assign a value to the variable_name.
The value can be anything like a number, a string, etc., that you assign to the variable.
The following defines a variable named counter and assigns the number 1 to it:
counter = 1
Naming variables
When you name a variable, you need to adhere to some rules. If you don’t, you’ll get an error.
The following are the variable rules that you should keep in mind:
● Variable names can contain only letters, numbers, and underscores (_). They can
start with a letter or an underscore (_), not with a number.
● Variable names cannot contain spaces. To separate words in variables, you use
underscores for example sorted_list.
● Variable names cannot be the same as keywords, reserved words, and built-in
functions in Python.
● Variable names should be concise and descriptive. For example, the active_user
variable is more descriptive than the au.
● Use underscores (_) to separate multiple words in the variable names.
● Avoid using the letter l and the uppercase letter O because they look like the number
1 and 0.
Summary
● A variable is a label that you can assign a value to it. The value of a variable can
change throughout the program.
● Use the variable_name = value to create a variable.
● The variable names should be as concise and descriptive as possible. Also, they
should adhere to Python variable naming rules.
Python Numbers
Summary: in this tutorial, you’ll learn about Python numbers and how to use them in programs.
Python supports integers, floats, and complex numbers. This tutorial discusses only integers
and floats.
Integers
The integers are numbers such as -1, 0, 1, 2, and 3, .. and they have type int.
You can use Math operators like +, -, *, and / to form expressions that include integers. For
example:
>>> 20 + 10
30
>>> 20 - 10
10
>>> 20 * 10
200
>>> 20 / 10
2.0
To calculate exponents, you use two multiplication symbols (**). For example:
>>> 3**3
27
To modify the order of operations, you use the parentheses (). For example:
Floats
Any number with a decimal point is a floating-point number. The term float means that the
decimal point can appear at any position in a number.
If you mix an integer and a float in any arithmetic operation, the result is a float:
>>> 1 + 2.0
3.0
Due to the internal representation of floats, Python will try to represent the result as precisely as
possible. However, you may get the result that you would not expect. For example:
>>> 0.1 + 0.2
0.30000000000000004
Just keep this in mind when you perform calculations with floats. And you’ll learn how to handle
situations like this in later tutorials.
Underscores in numbers
When a number is large, it’ll become difficult to read. For example:
count = 10000000000
To make the long numbers more readable, you can group digits using underscores, like this:
count = 10_000_000_000
When storing these values, Python just ignores the underscores. It does so when displaying the
numbers with underscores on the screen:
count = 10_000_000_000
print(count)
Output:
10000000000
Note that the underscores in numbers have been available since Python 3.6
Summary
● Python supports common numeric types including integers, floats, and complex
numbers.
● Use the underscores to group numbers for the large numbers.
Python String
Summary: in this tutorial, you’ll learn about Python string and its basic operations.
If a string contains a single quote, you should place it in double-quotes like this:
message = "It's a string"
And when a string contains double quotes, you can use the single quotes:
message = '"Beautiful is better than ugly.". Said Tim Peters'
To escape the quotes, you use the backslash (\). For example:
The Python interpreter will treat the backslash character (\) special. If you don’t want it to do so,
you can use raw strings by adding the letter r before the first quote. For example:
message = r'C:\python\bin'
print(help_message)
For example, you may want to use the value of the name variable inside the message string
variable:
name = 'John'
message = 'Hi'
To do it, you place the letter f before the opening quotation mark and put the brace around the
variable name:
name = 'John'
message = f'Hi {name}'
print(message)
Python will replace the {name} by the value of the name variable. The code will show the
following on the screen:
Hi John
The message is a format string, or f-string in short. Python introduced the f-string in version 3.6.
Output:
Good Morning!
Output:
Good Afternoon!
How it works:
If you use a negative index, Python returns the character starting from the end of the string. For
example:
str = "Python String"
print(str[-1]) # g
print(str[-2]) # n
+---+---+---+---+---+---+---+---+---+---+---+---+---+
| P | y | t | h | o | n | | S | t | r | i | n | g |
+---+---+---+---+---+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7 8 9 10 11 12
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Output:
13
Slicing strings
Slicing allows you to get a substring from a string. For example:
str = "Python String"
print(str[0:2])
Output:
Py
The str[0:2] returns a substring that includes the character from the index 0 (included) to 2
(excluded).
The substring always includes the character at the start and excludes the string at the end.
The start and end are optional. If you omit the start, it defaults to zero. If you omit the end,
it defaults to the string’s length.
Error:
Traceback (most recent call last):
File "app.py", line 2, in <module>
str[0] = 'J'
TypeError: 'str' object does not support item assignment</module>
When want to modify a string, you need to create a new one from the existing string. For
example:
str = "Python String"
new_str = 'J' + str[1:]
print(new_str)
Output:
Jython String
Summary
To represent true and false, Python provides you with the boolean data type. The boolean value
has a technical name as bool.
The boolean data type has two values: True and False.
Note that the boolean values True and False start with the capital letters (T) and (F).
When you compare two numbers, Python returns the result as a boolean value. For example:
>>> 20 > 10
True
>>> 20 < 10
False
>>> bool('Hi')
True
>>> bool('')
False
>>> bool(100)
True
>>> bool(0)
False
As you can see clearly from the output, some values evaluate to True and the others evaluate
to False.
The truthy values are the other values that aren’t falsy.
Note that you’ll learn more about the None, list, tuple, and dictionary in the upcoming
tutorials.
Summary
● Python boolean data type has two values: True and False.
● Use the bool() function to test if a value is True or False.
● The falsy values evaluate to False while the truthy values evaluate to True.
● Falsy values are the number zero, an empty string, False, None, an empty list, an
empty tuple, and an empty dictionary. Truthy values are the values that are not falsy.
Python Constants
Summary: in this tutorial, you’ll learn how to define Python constants.
Sometimes, you may want to store values in variables. But you don’t want to change these
values throughout the execution of the program.
To do it in other programming languages, you can use constants. The constants are like
variables but their values don’t change during the program execution.
To work around this, you use all capital letters to name a variable to indicate that the variable
should be treated as a constant. For example:
FILE_SIZE_LIMIT = 2000
When encountering variables like these, you should not change their values. These variables
are constant by convention, not by rules.
Summary
Python Comments
Summary: in this tutorial, you’ll learn how to add comments to your code. And you’ll learn
various kinds of Python comments including block comments, inline comments, and
documentation string.
Typically, you use comments to explain formulas, algorithms, and complex business logic.
When executing a program, the Python interpreter ignores the comments and only interprets the
code.
Python provides three kinds of comments including block comment, inline comment, and
documentation string.
To create a block comment, you start with a single hash sign (#) followed by a single space and
a text string. For example:
# increase price by 5%
price = price * 1.05
Similar to a block comment, an inline comment begins with a single hash sign (#) and is
followed by a space and a text string.
Python docstrings
A documentation string is a string literal that you put as the first lines in a code block, for
example, a function.
Typically, you use a documentation string to automatically generate the code documentation.
Technically speaking, docstrings are not the comments. They create anonymous variables that
reference the strings. Also, they’re not ignored by the Python interpreter.
Python provides two kinds of docstrings: one-line docstrings and multi-line docstrings.
1) One-line docstrings
As its name implies, a one-line docstring fits one line. A one-line docstring begins with triple
quotes (""") and also ends with triple quotes ("""). Also, there won’t be any blank line either
before or after the one-line docstring.
def quicksort():
""" sort the list using quicksort algorithm """
...
2) Multi-line docstrings
Unlike a one-line docstring, a multi-line docstring can span multiple lines. A multi-line docstring
also starts with triple quotes (""") and ends with triple quotes (""").
However, you can use multi-line docstrings as multiline comments. Guido van Rossum, the
creator of Python, also recommended this.
It’s a good practice to keep your comment clear, concise, and explanatory. The ultimate goal is
to save time and energy for you and other developers who will work on the code later.
Summary
● Use comments to document your code when necessary.
● A block comment and inline comment starts with a hash sign (#).
● Use docstrings for functions, modules, and classes.
When you execute this code, it’ll prompt you for input on the Terminal:
Enter a value:
If you enter a value, for example, a number, the program will display that value back:
Enter a value:100
100
The following example prompts you to enter two input values: net price and tax rate. After that, it
calculates the tax and displays the result on the screen:
price = input('Enter the price ($):')
tax = input('Enter the tax rate (%):')
Since the input values are strings, you cannot apply the multiply operator.
To solve this issue, you need to convert the strings to numbers before performing calculations.
To convert a string to a number, you use the int() function. More precisely, the int()
function converts a string to an integer.
The following example uses the int() function to convert the input strings to numbers:
If you run the program, and enter some values, you’ll see that it works correctly:
>>> type(100)
<class 'int'>
>>> type(2.0)
<class 'float'>
>>> type('Hello')
<class 'str'>
>>> type(True)
<class 'bool'>
In front of each type, you see the class keyword. It isn’t important for now. And you’ll learn
more about the class later.
Summary
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
+ Addition 5 + 2 = 7
- Subtraction 4 - 2 = 2
* Multiplication 2 * 3 = 6
/ Division 4 / 2 = 2
// Floor Division 10 // 3 = 3
% Modulo 5 % 2 = 1
** Power 4 ** 2 = 16
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
● + to add a and b
● - to subtract b from a
● * to multiply a and b
● / to divide a by b
● // to floor divide a by b
= Assignment Operator a = 7
+= Addition Assignment a += 1 # a = a +
1
-= Subtraction Assignment a -= 3 # a = a -
3
*= Multiplication a *= 4 # a = a *
Assignment 4
/= Division Assignment a /= 3 # a = a /
3
%= Remainder Assignment a %= 10 # a = a %
10
**= Exponent Assignment a **= 10 # a = a
** 10
# assign 5 to b
b = 5
print(a)
# Output: 15
Similarly, we can use any other assignment operators according to the need.
a = 5
b =2
Here, the > comparison operator is used to compare whether a is greater than b or not.
b = 2
# equal to operator
print('a == b =', a == b)
Output
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
Note: Comparison operators are used in decision-making and loops. We'll discuss more of the
comparison operator and decision-making in later tutorials.
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is
True.
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Identity operators
In Python, is and is not are used to check if two values are located on the same part of the
memory. Two variables that are equal does not imply that they are identical.
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates
them separately in memory although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
in True if value/variable is 5 in x
found in the sequence
Output
True
True
True
False
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.
These comparison operators compare two values and return a boolean value, either True or
False.
You can use these comparison operators to compare both numbers and strings.
The following example uses the Less Than (<) operator to compare two numbers:
>>> 10 < 20
True
>>> 30 < 20
False
It’s quite obvious when you use the less-than operator with the numbers.
The following example uses the less than operator (<) to compare two strings:
>>> 'apple' < 'orange'
True
>>> 'banana' < 'apple'
False
The expression 'apple' < 'orange' returns True because the letter a in apple is before
the letter o in orange.
Similarly, the 'banana' < 'apple' returns False because the letter 'b' is after the letter
'a'.
The following example shows how to use the less-than operator with variables:
>>> x = 10
>>> y = 20
>>> x < y
True
>>> y < x
False
The following example shows how to use the less than or equal to operator to compare two
numbers:
>>> 20 <= 20
True
>>> 10 <= 20
True
>>> 30 <= 30
True
This example shows how to use the less than or equal to operator to compare the values of two
variables:
>>> x = 10
>>> y = 20
>>> x <= y
True
>>> y <= x
False
This example uses the greater than operator (>) to compare two numbers:
>>> 20 > 10
True
>>> 20 > 20
False
>>> 10 > 20
False
The following example uses the greater than operator (>) to compare two strings:
The following example uses the greater than or equal to an operator to compare two numbers:
>>> 20 >= 10
True
>>> 20 >= 20
True
>>> 10 >= 20
False
The following example uses the greater than or equal to operator to compare two strings:
>>> 'apple' >= 'apple'
True
>>> 'apple' >= 'orange'
False
>>> 'orange' >= 'apple'
True
left_value == right_value
The following example uses the equal to operator (==) to compare two numbers:
>>> 20 == 10
False
>>> 20 == 20
True
And the following example uses the equal to operator (==) to compare two strings:
left_value != right_value
For example, the following uses the not equal to operator to compare two numbers:
>>> 20 != 20
False
>>> 20 != 10
True
The following example uses the not equal to operator to compare two strings:
>>> 'apple' != 'apple'
False
>>> 'apple' != 'orange'
True
Summary
● A comparison operator compares two values and returns a boolean value, either
True or False.
● Python has six comparison operators: less than (<), less than or equal to (<=),
greater than (>), greater than or equal to (>=), equal to (==), and not equal to (!=).
a and b
It returns True if both conditions are True. And it returns False if either the condition a or b is
False.
The following example uses the and operator to combine two conditions that compare the
price with numbers:
The result is True because the price is greater than 9 and less than 10.
The following example returns False because the price isn’t greater than 10:
In this example, the condition price > 10 returns False while the second condition price <
20 returns True.
The following table illustrates the result of the and operator when combining two conditions:
a b a and b
As you can see from the table, the condition a and b only returns True if both conditions
evaluate to True.
The or operator
Similar to the and operator, the or operator checks multiple conditions. But it returns True
when either or both individual conditions are True:
a or b
The following table illustrates the result of the or operator when combining two conditions:
a b a or b
The or operator returns False only when both conditions are False.
In this example, the price < 20 returns True, therefore, the whole expression returns True.
The following example returns False because both conditions evaluate to False:
not a
If the condition is True, the not operator returns False and vice versa.
a not a
True False
False True
The following example uses the not operator. Since the price > 10 returns False, the not
price > 10 returns True:
Here is another example that combines the not and the and operators:
In this example, Python evaluates the conditions based on the following order:
The following shows the precedence of the not, and, and or operators:
Operator Precedence
not High
and Medium
or Low
Based on these precedences, Python will group the operands for the operator with the highest
precedence first, then group the operands for the operator with the lower precedence, and so
on.
In case an expression has several logical operators with the same precedence, Python will
evaluate them from the left to right:
a or b and c means a or (b and c)
Summary
Python if Statement
Summary: in this tutorial, you’ll learn how to use the Python if statement to execute a block of
code based on a condition.
if condition:
if-blockCode language: Python (python)
If the condition evaluates to True, it executes the statements in the if-block. Otherwise, it
ignores the statements.
Note that the colon (:) that follows the condition is very important. If you forget it, you’ll get a
syntax error.
This example prompts you to input your age. If you enter a number that is greater than or equal
to 18, it’ll show a message "You're eligible to vote" on the screen. Otherwise, it does
nothing.
The condition int(age) >= 18 converts the input string to an integer and compares it with 18.
In this example, if you enter a number that is greater than or equal to 18, you’ll see two
messages.
In this example, indentation is very important. Any statement that follows the if statement
needs to have four spaces.
If you don’t use the indentation correctly, the program will work differently. For example:
age = input('Enter your age:')
if int(age) >= 18:
print("You're eligible to vote.")
print("Let's go and vote.")
Code language: Python (python)
In this example, the final statement always executes regardless of the condition in the if
statement. The reason is that it doesn’t belong to the if block:
if condition:
if-block;
else:
else-block;Code language: Python (python)
In this syntax, the if...else will execute the if-block if the condition evaluates to True.
Otherwise, it’ll execute the else-block.
In this example, if you enter your age with a number less than 18, you’ll see the message
"You're not eligible to vote." like this:
if if-condition:
if-block
elif elif-condition1:
elif-block1
elif elif-condition2:
elif-block2
...
else:
else-blockCode language: Python (python)
When the if...elif...else statement finds one, it executes the statement that follows the
condition and skips testing the remaining conditions.
Note that the else block is optional. If you omit it and no condition is True, the statement does
nothing.
In this example:
● If the input age is less than 5, the ticket price will be $5.
● If the input age is greater than or equal to 5 and less than 16, the ticket price is $10.
● Otherwise, the ticket price is $18.
Summary
● Use the if statement when you want to run a code block based on a condition.
● Use the if...else statement when you want to run another code block if the
condition is not True.
● Use the if...elif...else statement when you want to check multiple conditions
and run the corresponding code block that follows the condition that evaluates to
True.
In this example, the following if...else statement assigns 20 to the ticket_price if the
age is greater than or equal to 18. Otherwise, it assigns the ticket_price 5:
To make it more concise, you can use an alternative syntax like this:
ticket_price = 20 if int(age) >= 18 else 5Code language: Python (python)
In this statement, the left side of the assignment operator (=) is the variable ticket_price.
The expression on the right side returns 20 if the age is greater than or equal to 18 or 5
otherwise.
The ternary operator evaluates the condition. If the result is True, it returns the
value_if_true. Otherwise, it returns the value_if_false.
if condition:
value_if_true
else:
value_if_trueCode language: Python (python)
Note that you have been programming languages such as C# or Java, and you’re familiar with
the following ternary operator syntax:
condition ? value_if_true : value_if_falseCode language: Python (python)
The following program uses the ternary operator instead of the if statement:
Summary