0% found this document useful (0 votes)
20 views

Constants in Python

constants

Uploaded by

Arya Bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Constants in Python

constants

Uploaded by

Arya Bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Python Syntax

Summary: in this tutorial, you’ll learn about the basic Python syntax so that you can get started
with the Python language quickly.

Whitespace and indentation


If you’ve been working in other programming languages such as Java, C#, or C/C++, you know
that these languages use semicolons (;) to separate the statements.

However, Python uses whitespace and indentation to construct the code structure.

The following shows a snippet of Python code:


# define main function to print out something
def main():
i = 1
max = 10
while (i < max):
print(i)
i = i + 1

# call function main


main()

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

And Python also supports other kinds of comments.

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.

In addition, you cannot use Python keywords for naming identifiers.

Keywords
Some words have special meanings in Python. They are called keywords.

The following shows the list of keywords in Python:


False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

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.

The following shows some examples of string literals:


s = 'This is a string'
print(s)
s = "Another string using double quotes"
print(s)
s = ''' string can span
multiple line '''
print(s)

Summary

● A Python statement ends with a newline character.


● Python uses spaces and indentation to organize its code structure.
● Identifiers are names that identify variables, functions, modules, classes, etc. in
Python.
● Comments describe why the code works. They are ignored by the Python interpreter.
● Use the single quote, double-quotes, triple-quotes, or triple double-quotes to denote

Python Variables
Summary: in this tutorial, you’ll learn about Python variables and how to use them effectively.

What is a variable in Python


When you develop a program, you need to manage values, a lot of them. To store values, you
use variables.

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)

message = 'Good Bye!'


print(message)
Output:
Hello, World!
Good Bye!

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.

The following guidelines help you define good variable names:

● 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:

>>> 20 / (10 + 10)


1.0

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.

In general, you can use floats like integers. For example:


>>> 0.5 + 0.5
1.0
>>> 0.5 - 0.5
0.0
>>> 0.5 / 0.5
1.0
>>> 0.5 * 0.5
0.25

The division of two integers always returns a float:


>>> 20 / 10
2.0

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

The underscores also work for both integers and floats.

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.

Introduction to Python string


A string is a series of characters. In Python, anything inside quotes is a string. And you can use
either single or double quotes. For example:
message = 'This is a string in Python'
message = "This is also a string"

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:

message = 'It\'s also a valid string'

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'

Creating multiline strings


To span a string multiple lines, you use triple-quotes “””…””” or ”’…”’. For example:
help_message = '''
Usage: mysql command
-h hostname
-d database name
-u username
-p password
'''

print(help_message)

It’ll output the following if you execute the program:


Usage: mysql command
-h hostname
-d database name
-u username
-p password

Using variables in Python strings with the f-strings


Sometimes, you want to use the values of variables in a string.

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.

Concatenating Python strings


When you place the string literals next to each other, Python automatically concatenates them
into one string. For example:
greeting = 'Good ' 'Morning!'
print(greeting)

Output:
Good Morning!

To concatenate two string variables, you use the operator +:

greeting = 'Good '


time = 'Afternoon'

greeting = greeting + time + '!'


print(greeting)

Output:
Good Afternoon!

Accessing string elements


Since a string is a sequence of characters, you can access its elements using an index. The first
character in the string has an index of zero.

The following example shows how to access elements using an index:


str = "Python String"
print(str[0]) # P
print(str[1]) # y

How it works:

● First, create a variable that holds a string "Python String".


● Then, access the first and second characters of the string by using the square
brackets [] and indexes.

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

The following illustrates the indexes of the string "Python String":

+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 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

Getting the length of a string


To get the length of a string, you use the len() function. For example:

str = "Python String"


str_len = len(str)
print(str_len)

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 syntax for slicing is as follows:


string[start:end]

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.

Python strings are immutable


Python strings are immutable. It means that you cannot change the string. For example, you’ll
get an error if you update one or more characters in a string:
str = "Python String"
str[0] = 'J'

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

● In Python, a string is a series of characters. Also, Python strings are immutable.


● Use quotes, either single quotes or double quotes to create string literals.
● Use the backslash character \ to escape quotes in strings
● Use raw strings r'...' to escape the backslash character.
● Use f-strings to insert substitute variables in literal strings.
● Place literal strings next to each other to concatenate them. And use the + operator
to concatenate string variables.
● Use the len() function to get the size of a string.
● Use the str[n] to access the character at the position n of the string str.
● Use slicing to extract a substring from a string.
Python Boolean
Summary: in this tutorial, you’ll learn about the Python boolean data type, falsy and truthy
values.

Introduction to Python Boolean data type


In programming, you often want to check if a condition is true or not and perform some actions
based on the result.

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).

The following example defines two boolean variables:


is_active = True
is_admin = False

When you compare two numbers, Python returns the result as a boolean value. For example:
>>> 20 > 10
True
>>> 20 < 10
False

Also, comparing two strings results in a boolean value:


>>> 'a' < 'b'
True
>>> 'a' > 'b'
False

The bool() function


To find out if a value is True or False, you use the bool() function. For example:

>>> 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.

Falsy and Truthy values


When a value evaluates to True, it’s truthy. And if a value evaluates to False, it’s falsy.

The following are falsy values in Python:

● The number zero (0)


● An empty string ''
● False
● None
● An empty list []
● An empty tuple ()
● An empty dictionary {}

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.

The bad news is that Python doesn’t support constants.

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 doesn’t have built-in constant types.


● By convention, Python uses a variable whose name contains all capital letters to
define a constant.

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.

Introduction to Python comments


Sometimes, you want to document the code that you write. For example, you may want to note
why a piece of code works. To do it, you use the comments.

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.

Python block comments


A block comment explains the code that follows it. Typically, you indent a block comment at the
same level as the code block.

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

Python inline comments


When you place a comment on the same line as a statement, you’ll have an inline comment.

Similar to a block comment, an inline comment begins with a single hash sign (#) and is
followed by a space and a text string.

The following example illustrates an inline comment:


salary = salary * 1.02 # increase salary by 2%

Python docstrings
A documentation string is a string literal that you put as the first lines in a code block, for
example, a function.

Unlike a regular comment, a documentation string can be accessed at run-time using


obj.__doc__ attribute where obj is the name of the function.

Typically, you use a documentation string to automatically generate the code documentation.

Documentation strings is called docstrings.

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.

The following example illustrates a one-line docstring in the quicksort() function:

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 (""").

The following example shows you how to use multi-line docstrings:


def increase(salary, percentage, rating):
""" increase salary base on rating and percentage
rating 1 - 2 no increase
rating 3 - 4 increase 5%
rating 4 - 6 increase 10%
"""

Python multiline comments


Python doesn’t support multiline comments.

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.

Python Type Conversion


Summary: in this tutorial, you’ll learn about type conversion in Python and some useful type
conversion functions.

Introduction to type conversion in Python


To get input from users, you use the input() function. For example:

value = input('Enter a value:')


print(value)

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

However, the input() function returns a string, not an integer.

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 (%):')

tax_amount = price * tax / 100

print(f'The tax amount price is ${tax_amount}')

When you execute the program and enter some numbers:


Enter the price ($):100
Enter the tax rate (%):10

… you’ll get the following error:


Traceback (most recent call last):
File "main.py", line 4, in <module>
tax_amount = price * tax / 100
TypeError: can't multiply sequence by non-int of type 'str'

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:

price = input('Enter the price ($):')


tax = input('Enter the tax rate (%):')

tax_amount = int(price) * int(tax) / 100


print(f'The tax amount is ${tax_amount}')

If you run the program, and enter some values, you’ll see that it works correctly:

Enter the price ($):


100
Enter the tax rate (%):
10
The tax amount is $10.0

Other type conversion functions


Besides the int(str) functions, Python supports other type conversion functions. The
following shows the most important ones for now:

● float(str) – convert a string to a floating-point number.


● bool(val) – convert a value to a boolean value, either True or False.
● str(val) – return the string representation of a value.

Getting the type of a value


To get the type of value, you use the type(value) function. For example:

>>> type(100)
<class 'int'>
>>> type(2.0)
<class 'float'>
>>> type('Hello')
<class 'str'>
>>> type(True)
<class 'bool'>

As you can see clearly from the output:

● The number 100 has the type of int.


● The number 2.0 has the type of float.
● The string 'Hello' has the type of str.
● And the True value has the type of 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

● Use the input() function to get an input string from users.


● Use type conversion functions such as int(), float(), bool(), and
str(vaue)to convert a value from one type to another.
● Use the type() function to get the type of a value.

Types of Python Operators


Here's a list of different types of Python operators that we will learn in this tutorial.

1. Arithmetic operators

2. Assignment Operators

3. Comparison Operators

4. Logical Operators

5. Bitwise Operators

6. Special Operators

1. Python Arithmetic Operators


Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc. For example,
sub = 10 - 5 # 5

Here, - is an arithmetic operator that subtracts two values or variables.

Operator Operation Example

+ 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

Example 1: Arithmetic Operators in Python


a = 7
b = 2

# 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

In the above example, we have used multiple arithmetic operators,

● + 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

● % to get the remainder


● ** to get a to the power b

2. Python Assignment Operators


Assignment operators are used to assign values to variables. For example,
# assign 5 to x
var x = 5

Here, = is an assignment operator that assigns 5 to x.

Here's a list of different assignment operators available in Python.

Operator Name Example

= 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

Example 2: Assignment Operators


# assign 10 to a
a = 10

# assign 5 to b
b = 5

# assign the sum of a and b to a


a += b # a = a + b

print(a)

# Output: 15

Here, we have used the += operator to assign the sum of a and b to a.

Similarly, we can use any other assignment operators according to the need.

3. Python Comparison Operators


Comparison operators compare two values/variables and return a boolean result: True or
False. For example,

a = 5
b =2

print (a > b) # True

Here, the > comparison operator is used to compare whether a is greater than b or not.

Operator Meaning Example

== Is Equal To 3 == 5 gives us False

!= Not Equal To 3 != 5 gives us True


> Greater Than 3 > 5 gives us False

< Less Than 3 < 5 gives us True

>= Greater Than or Equal To 3 >= 5 give us False

<= Less Than or Equal To 3 <= 5 gives us True

Example 3: Comparison Operators


a = 5

b = 2

# equal to operator
print('a == b =', a == b)

# not equal to operator


print('a != b =', a != b)

# greater than operator


print('a > b =', a > b)

# less than operator


print('a < b =', a < b)

# greater than or equal to operator


print('a >= b =', a >= b)

# less than or 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.

4. Python Logical Operators


Logical operators are used to check whether an expression is True or False. They are used in
decision-making. For example,
a = 5
b = 6

print((a > 2) and (b >= 6)) # True

Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is
True.

Operator Example Meaning

and a and b Logical AND: True only


if both the operands are
True

or a or b Logical OR: True if at


least one of the operands
is True

not not a Logical NOT: True if


the operand is False
and vice-versa.
Example 4: Logical Operators
# logical AND
print(True and True) # True
print(True and False) # False

# logical OR
print(True or False) # True

# logical NOT
print(not True) # False

Note: Here is the truth table for these logical operators.

5. Python Bitwise operators


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)

Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000


0010)
<< Bitwise left shift x << 2 = 40 (0010
1000)

6. Python Special operators


Python language offers some special types of operators like the identity operator and the
membership operator. They are described below with examples.

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.

Operator Meaning Example

is True if the operands are x is True


identical (refer to the
same object)

is not True if the operands are x is not True


not identical (do not refer
to the same object)

Example 4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 is not y1) # prints False

print(x2 is y2) # prints True

print(x3 is y3) # prints False


Here, we see that x1 and y1 are integers of the same values, so they are equal as well as
identical. Same is the case with x2 and y2 (strings).

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.

Operator Meaning Example

in True if value/variable is 5 in x
found in the sequence

not in True if value/variable is 5 not in x


not found in the sequence

Example 5: Membership operators in Python


x = 'Hello world'
y = {1:'a', 2:'b'}

# check if 'H' is present in x string


print('H' in x) # prints True

# check if 'hello' is present in x string


print('hello' not in x) # prints True

# check if '1' key is present in y


print(1 in y) # prints True

# check if 'a' key is present in y


print('a' in y) # prints False

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.

Python Comparison Operators


Summary: in this tutorial, you’ll learn about Python comparison operators and how to use them
to compare two values.

Introduction to Python comparison operators


In programming, you often want to compare a value with another value. To do that, you use
comparison operators.

Python has six comparison operators, which are as follows:

● Less than ( < )


● Less than or equal to (<=)
● Greater than (>)
● Greater than or equal to (>=)
● Equal to ( == )
● Not equal to ( != )

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.

Less than operator (<)


The Less Than operator (<) compares two values and returns True if the value on the left is
less than the value on the right. Otherwise, it returns False:

left_value < right_value

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

Less than or equal to operator (<=)


The less than or equal to operator compares two values and returns True if the left value is less
than or equal to the right value. Otherwise, it returns False:

left_value <= right_value

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

Greater than operator (>)


The greater than the operator (>) compares two values and returns True if the left value is
greater than the right value. Otherwise, it returns False:
left_value > right_value

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:

>>> 'apple' > 'orange'


False
>>> 'orange' > 'apple'
True

Greater Than or Equal To operator (>=)


The greater than or equal to operator (>=) compares two values and returns True if the left
value is greater than or equal to the right value. Otherwise, it returns False:

left_value >= right_value

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

Equal To operator (==)


The equal to operator (==) compares two values and returns True if the left value is equal to
the right value. Otherwise, it returns False :

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:

>>> 'apple' == 'apple'


True
>>> 'apple' == 'orange'
False

Not Equal To operator (!=)


The not equal to operator (!=) compares two values and returns True if the left value isn’t
equal to the right value. Otherwise, it returns False.

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 (!=).

Python Logical Operators


Summary: in this tutorial, you’ll learn about Python logical operators and how to use them to
combine multiple conditions.

Introduction to Python logical operators


Sometimes, you may want to check multiple conditions at the same time. To do so, you use
logical operators.

Python has three logical operators:


● and
● or
● not

The and operator


The and operator checks whether two conditions are both True simultaneously:

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:

>>> price = 9.99


>>> price > 9 and price < 10
True

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:

>>> price > 10 and price < 20


False

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

True True True

True False False

False False False

False True False

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

True True True

True False True

False True True

False False False

The or operator returns False only when both conditions are False.

The following example shows how to use the or operator:

>>> price = 9.99


>>> price > 10 or price < 20
>>> True

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:

>>> price = 9.99


>>> price > 10 or price < 5
False

The not operator


The not operator applies to one condition. And it reverses the result of that condition, True
becomes False and False becomes True.

not a

If the condition is True, the not operator returns False and vice versa.

The following table illustrates the result of the not operator:

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:

>>> price = 9.99


>>> not price > 10
True

Here is another example that combines the not and the and operators:

>>> not (price > 5 and price < 10)


False

In this example, Python evaluates the conditions based on the following order:

● First, (price > 5 and price < 10) evaluates to True.


● Second, not True evaluates to False.

This leads to an important concept called precedence of logical operators.

Precedence of Logical Operators


When you mix the logical operators in an expression, Python will evaluate them in the order
which is called the operator precedence.

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)

a and b or c and means (a and b) or (c


d and d)

a and b and c or means ((a and b) and c)


d or d

not a and b or c means ((not a) and b)


or c

Summary

● Use logical operators to combine multiple conditions.


● Python has three logical operators: and, or, and not.
● The precedence of the logical operator from the highest to lowest: not, and, and or.

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.

The simple Python if statement


You use the if statement to execute a block of code based on a specified condition.

The syntax of the if statement is as follows:

if condition:
if-blockCode language: Python (python)

The if statement checks the condition first.

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.

The following flowchart illustrates the if statement:


For example:
age = input('Enter your age:')
if int(age) >= 18:
print("You're eligible to vote.")Code language: Python (python)

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.

Enter your age:18


You're eligible to vote.Code language: Python (python)

See the following 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, 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:

Enter your age:11


Let's go and vote.Code language: Python (python)

Python if…else statement


Typically, you want to perform an action when a condition is True and another action when the
condition is False.

To do so, you use the if...else statement.

The following shows the syntax of the if...else statement:

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.

The following flowchart illustrates the if..else statement:


The following example illustrates you how to use the if...else statement:

age = input('Enter your age:')


if int(age) >= 18:
print("You're eligible to vote.")
else:
print("You're not eligible to vote.")Code language: Python (python)

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:

Enter your age:11


You're not eligible to vote.Code language: Python (python)

Python if…elif…else statement


If you want to check multiple conditions and perform an action accordingly, you can use the
if...elif...else statement. The elif stands for else if.

Here is the syntax if the if...elif...else statement:

if if-condition:
if-block
elif elif-condition1:
elif-block1
elif elif-condition2:
elif-block2
...
else:
else-blockCode language: Python (python)

The if...elif...else statement checks each condition (if-condition, elif-


condition1, elif-condition2, …) in the order that they appear in the statement until it
finds the one that evaluates to True.

When the if...elif...else statement finds one, it executes the statement that follows the
condition and skips testing the remaining conditions.

If no condition evaluates to True, the if...elif...else statement executes the statement


in the else branch.

Note that the else block is optional. If you omit it and no condition is True, the statement does
nothing.

The following flowchart illustrates the if...elif...else statement:


The following example uses the if...elif..else statement to determine the ticket price
based on the age:
age = input('Enter your age:')

# convert the string to int


your_age = int(age)

# determine the ticket price


if your_age < 5:
ticket_price = 5
elif your_age < 16:
ticket_price = 10
else:
ticket_price = 18

# show the ticket price


print(f"You'll pay ${ticket_price} for the ticket")
Code language: Python (python)

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.

Python Ternary Operator


Summary: in this tutorial, you’ll learn about the Python ternary operator and how to use it to
make your code more concise.

Introduction to Python Ternary Operator


The following program prompts you for your age and determines the ticket price based on it:
age = input('Enter your age:')

if int(age) >= 18:


ticket_price = 20
else:
ticket_price = 5

print(f"The ticket price is {ticket_price}")Code language: Python


(python)

Here is the output when you enter 18:


Enter your age:18
The ticket price is $20Code language: Python (python)

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:

if int(age) >= 18:


ticket_price = 20
else:
ticket_price = 5Code language: Python (python)

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 following syntax is called a ternary operator in Python:


value_if_true if condition else value_if_falseCode language: Python
(python)

The ternary operator evaluates the condition. If the result is True, it returns the
value_if_true. Otherwise, it returns the value_if_false.

The ternary operator is equivalent to the following if...else statement:

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)

However, Python doesn’t support this ternary operator syntax.

The following program uses the ternary operator instead of the if statement:

age = input('Enter your age:')

ticket_price = 20 if int(age) >= 18 else 5

print(f"The ticket price is {ticket_price}")Code language: Python


(python)

Summary

● The Python ternary operator is value_if_true if condition else


value_if_false.
● Use the ternary operator to make your code more concise.

You might also like