w3schools
w3schools
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:
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
If you want to specify the data type, you can use the following constructor functions:
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = range(6) range
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:
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
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.
Try it Yourself »
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:
Try it Yourself »
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:
Try it Yourself »
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
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 »
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:
Try it Yourself »
Use it in an if statement:
Example
Print only if "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:
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:
Lower Case
Example
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
An example of an illegal character is a double quote inside a string that is surrounded by double
quotes:
You will get an error if you use double quotes inside a string that is surrounded by double quotes:
Try it Yourself »
Example
The escape character allows you to use double quotes when you normally would not be allowed:
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
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
index() Searches the string for a specified value and returns the position of where it was found
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
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
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
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
zfill() Fills the string with a specified number of 0 values at the beginning
Example
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
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
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Example
print(myFunction())
Arithmetic operators are used with numeric values to perform common mathematical operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
+= 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
ADVERTISEMENT
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true
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:
is not Returns True if both variables are not the same x is not y
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
<< 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
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
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not Comparisons, identity, and membership operators
in
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 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.
Create a List:
List Length
To determine how many items a list has, use the len() function:
Example
There are four collection data types in the Python programming language:
*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:
Try it Yourself »
Insert Items
Example
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
Try it Yourself »
The extend() method does not have to append lists, you can add any iterable object (tuples, sets,
dictionaries etc.).
Example
Remove "banana":