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

w3schools

The document provides an overview of built-in data types in Python, including text, numeric, sequence, mapping, set, boolean, binary, and none types. It explains how to set specific data types using constructor functions, and details numeric types such as int, float, and complex. Additionally, it covers string manipulation, operators, and various methods available for data types.

Uploaded by

Zana Kurdi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

w3schools

The document provides an overview of built-in data types in Python, including text, numeric, sequence, mapping, set, boolean, binary, and none types. It explains how to set specific data types using constructor functions, and details numeric types such as int, float, and complex. Additionally, it covers string manipulation, operators, and various methods available for data types.

Uploaded by

Zana Kurdi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

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 has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Example Data Type Try it

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset


x = Truebool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example Data Type Try it

x = str("Hello World") str

x = int(20) int

x = float(20.5) float

x = complex(1j) complex

x = list(("apple", "banana", "cherry")) list

x = tuple(("apple", "banana", "cherry")) tuple

x = range(6) range

x = dict(name="John", age=36) dict

x = set(("apple", "banana", "cherry")) set

x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool

x = bytes(5) bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview
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:

ExampleGet your own Python Server


x = 1 # int
y = 2.8 # float
z = 1j # complex

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

Example
Integers:

x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))

Try it Yourself »

Float
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.
Example
Floats:

x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

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

Example
Convert from one type to another:

x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

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:

Example
Import the random module, and display a random number between 1 and 9:

import random

print(random.randrange(1, 10))

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

ExampleGet your own Python Server


print("Hello")
print('Hello')

Try it Yourself »

Quotes Inside Quotes


You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

Try it Yourself »
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:

Example
a = "Hello"
print(a)

Try it Yourself »

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

Example
You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Try it Yourself »

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Try it Yourself »

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

Example
You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Try it Yourself »

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.

Example
Get the character at position 1 (remember that the first character has the
position 0):

a = "Hello, World!"
print(a[1])

Try it Yourself »

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with
a for loop.

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)

Try it Yourself »
String Length
To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Try it Yourself »

heck String
To check if a certain phrase or character is present in a string, we can use the
keyword in.

Example
Check if "free" is present in the following text:

txt = "The best things in life are free!"


print("free" in txt)

Try it Yourself »

Use it in an if statement:

Example
Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")

Try it Yourself »

Check if NOT
To check if a certain phrase or character is NOT present in a string, we can
use the keyword not in.
Example
Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)

Upper Case

ExampleGet your own Python Server

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

Try it Yourself »

Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often you want to remove this
space.

Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

Lower Case

Example

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Split String

The split() method returns a list where the text between the specified separator becomes the list
items.

Example

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

Try it Yourself »

Example
Display the price with 2 decimals:

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)

F-Strings

F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.

To specify a string as an f-string, simply put an f in front of the string literal, and add curly
brackets {} as placeholders for variables and other operations.

Example

Create an f-string:

age = 36
txt = f"My name is John, I am {age}"
print(txt)

Try it Yourself »

Escape Character

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double
quotes:

ExampleGet your own Python Server

You will get an error if you use double quotes inside a string that is surrounded by double quotes:

txt = "We are the so-called "Vikings" from the north."

Try it Yourself »

To fix this problem, use the escape character \":

Example

The escape character allows you to use double quotes when you normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

String Methods

Python has a set of built-in methods that you can use on strings.

Note: All string methods return new values. They do not change the original string.

Method Description
capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable


isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was found

rindex() Searches the string for a specified value and returns the last position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string


swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

Example

Evaluate two variables:

x = "Hello"
y = 15

print(bool(x))
print(bool(y))

Some Values are False

In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the
number 0, and the value None. And of course the value False evaluates to False.

Example

The following will return False:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Functions can Return a Boolean

You can create functions that returns a Boolean Value:

Example

Print the answer of a function:


def myFunction() :
return True

print(myFunction())

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As Try

= x=5 x=5 Try

+= x += 3 x=x+3 Try

-= x -= 3 x=x-3 Try

*= x *= 3 x=x*3 Try
/= x /= 3 x=x/3 Try

%= x %= 3 x=x%3 Try

//= x //= 3 x = x // 3 Try

**= x **= 3 x = x ** 3 Try

&= x &= 3 x=x&3 Try

|= x |= 3 x=x|3 Try

^= x ^= 3 x=x^3 Try

>>= x >>= 3 x = x >> 3 Try

<<= x <<= 3 x = x << 3 Try

:= print(x := 3) x=3 Try


print(x)

ADVERTISEMENT

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y


<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same x is y


object

is not Returns True if both variables are not the same x is not y
object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is not x not in y
present in the object
Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill left Shift left by pushing zeros in from the right and let the x << 2
shift leftmost bits fall off

>> Signed right Shift right by pushing copies of the leftmost bit in from the x >> 2
shift left, and let the rightmost bits fall off

Operator Precedence

Operator precedence describes the order in which operations are performed.

Example

Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:

print((6 + 3) - (6 + 3))

Run example »

Example

Multiplication * has higher precedence than addition +, and therefor multiplications are evaluated
before additions:

print(100 + 5 * 3)

Run example »

The precedence order is described in the table below, starting with the highest precedence at the
top:

Operator Description

() Parentheses
** Exponentiation

+x -x ~x Unary plus, unary minus, and bitwise NOT

* / // % Multiplication, division, floor division, and modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== != > >= < <= is is not in not Comparisons, identity, and membership operators
in

not Logical NOT

and AND

or OR

If two operators have the same precedence, the expression is evaluated from left to right.

Example

Addition + and subtraction - has the same precedence, and therefor we evaluate the expression from
left to right:

print(5 + 4 - 7 + 3)
List

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

ExampleGet your own Python Server

Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

Python Collections (Arrays)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.

 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate


members.

 Dictionary is a collection which is ordered** and changeable. No duplicate members.

 *Set items are unchangeable, but you can remove and/or add items
whenever you like.
 **As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
Python - Add List Items

❮ PreviousNext ❯

Append Items

To add an item to the end of the list, use the append() method:

ExampleGet your own Python Server

Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

Try it Yourself »

Insert Items

To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example

Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)

Try it Yourself »

Note: As a result of the examples above, the lists will now contain 4 items.

ADVERTISEMENT

ADVERTISEMENT

Extend List

To append elements from another list to the current list, use the extend() method.

Example

Add the elements of tropical to thislist:

thislist = ["apple", "banana", "cherry"]


tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

Try it Yourself »

The elements will be added to the end of the list.

Add Any Iterable

The extend() method does not have to append lists, you can add any iterable object (tuples, sets,
dictionaries etc.).

Example

Add elements of a tuple to a list:

thislist = ["apple", "banana", "cherry"]


thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

Remove Specified Item

The remove() method removes the specified item.

ExampleGet your own Python Server

Remove "banana":

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)

You might also like