Python Variables & types, Operators, Type Conversion

Python Variables & types, Operators, Type Conversion

Python Comments

Comments starts with a # in Python

Variables and Assignment Operators

Unlike other programming languages (ex PHP, with $), Python has no command for declaring a variable. A variable is created at the moment you first assign a value to it.

Variables don’t need to be declared with any particular type and You can change the type after they have been set.

month = 3
month = "march"
#Result: march

Assign value to Multiple Variables

Python allows you to assign values to multiple variables in one line:

x, y, z = 1, 2, 3

Rules for Python variables:

  • Must start with a letter or the underscore.
  • Can use only letters, numbers, and underscores in your variable names. They can’t have spaces.
  • Can’t use reserved words or built-in identifiers
  • The pythonic way to name variables is to use all lowercase letters and underscores to separate words (ex my_age = 45).

!!Variable names are Case Sensitive in Python

Scientific notation

In scientific notation, all numbers are written in the form: m × 10n

7.33e2 is equal to 7.33 * 10 ** 2 which is equal to 733

Integers and Floats

int – for integer values
float – for a decimal or floating-point values

Floating points numbers are approximations!

x = 3 = integer
y = 4.0 – float
y = 4. – float

print(3/4) – 0.75 – float

Even one integer divided by another integer exactly, the result will be float

print(4/4) / 1.0 – float

You can create a value that follows the data type by using the following syntax:

x = int(4.7) # x is now an integer 4
The part after the decimal is cut
y = float(4) # y is now a float of 4.0

You can check the type by using the type function:

# int
# float


Python Arithmetic Operators

+ Addition
* Multiplication
/ Division
% Modulus
** Exponentiation
// Floor division

In Python, there are two kinds of division: integer division and float division.

print(4 / 3)
print(4 // 3)

Gives the output in Python 3


Python Logical Operators

and Returns True if both statements are true
or Returns True if one of the statements is true
not Reverse the result, returns False if the result is true

Python uses and, not and or conditionals, instead of &&, ! or ^^.

PHP logical operators

$a and $b 	And 	TRUE if both $a and $b are TRUE.
$a or $b 	Or 	TRUE if either $a or $b is TRUE.
$a xor $b 	Xor 	TRUE if either $a or $b is TRUE, but not both.
! $a 	Not 	TRUE if $a is not TRUE.
$a && $b 	And 	TRUE if both $a and $b are TRUE.
$a || $b 	Or 	TRUE if either $a or $b is TRUE.

Python Identity Operators

In Python Identity operators are

is – evaluates if both sides have the same identity. Is operator is stronger than ==.

is not – evaluates if both sides have different identities

!Comparisons to singletons like None should always be done with ‘is’ or ‘is not’, never with the equality operators. Read more here – Style Guide for Python Code

someobj = None
if not someobj:
#do something


a = [1, 1, 2]
b = a

print(a == b)
# True

print(a is b)
# True

List a and list b are equal and identical.

a = [1, 1, 2]
b = [1, 1, 2]

print(a == b)
# True They have the same content!

print(a is b)
# False

They have the same content but point to two different objects, so they aren’t identical objects.

a = [1, 1, 2]
b = [1, 1, 2, 4]

print(a == b)
# False They don't have the same content!

print(a is b)
# False They don't have the same content and point to different objects!

In PHP identical operator is ===

In PHP the Identical operator is the triple equal sign “===”

This operator returns true if both variable contains same information and same data types otherwise return false.

Why is === faster than == in PHP?

=== is faster because don’t converts the data type to see if two variables have same value

Python Bitwise Operators

& AND (Sets each bit to 1 if both bits are 1)
| OR (Sets each bit to 1 if one of two bits is 1)
^ XOR (Sets each bit to 1 if only one of two bits is 1)
~ NOT (Inverts all the bits)
<< Zero fill left shift (Shift left by pushing zeros in from the right and let the leftmost bits fall off)
>> Signed right shift (Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off)

Divide By Zero in Python

What happens if you divide by zero in Python?

ZeroDivisionError: division by zero

Python Booleans

You can evaluate any expression in Python, and get one of two answers, True or False.

bool() function

The bool() function allows you to evaluate any value, and give you True or False in return

# True
# True

None Keyword

The None keyword is used to define a null value or no value at all.
None is a variable, a value, that we can distinctly detect differently than numbers.

None is not the same as 0, False, or an empty string. None is a datatype of its own (NoneType) and only None can be None.

x = None


How do we get data from the user in Python?

You can read data from the user using the input() function.
The input() function returns a string!

name = input(“What is Your name?”)

Even if the user will tipe “123” the result will be string, not int!


In python, You can define a string with either double quotes ” or single quotes ‘.

Strings in Python are arrays of bytes representing Unicode characters.

!!!Python does not have a character data type, a single character is simply a string with a length of 1.

my_text = “Welcome to webpedia”
my_text = ‘Welcome to webpedia’

Multi-line Strings

The triple-quoted in Python can be used to represent a multi-line string.

Also, we can use triple quotes (i.e., a triplet of single quotes or triplet double-quotes) to represent the strings containing both single and double quotes to eliminate the need for escaping the string.

my_text = '''Nam accumsan feugiat nulla, id lacinia est imperdiet non.
Duis nunc neque, facilisis vel fringilla nec, ullamcorper gravida neque.
Quisque nec pretium "lacus". Integer facilisis mattis odio at congue.'''

//Nam accumsan feugiat nulla, id lacinia est imperdiet non.
Duis nunc neque, facilisis vel fringilla nec, ullamcorper gravida neque.
Quisque nec pretium "lacus". Integer facilisis mattis odio at congue.

How to access characters of a string in Python?

Individual characters in a string can be accessed by specifying the string name followed by the index number in square brackets([]).

  • The index value must be an integer and starts at zero
  • The index value can be an expression that is computed

How to use quotation marks in a string?

my_string = ‘”Welcome to webpedia”‘
my_string = “I’m going to learn python”

or You can use the backslash to escape quotes.

my_string = “\”Welcome to webpedia\””
my_string = ‘I\’m going to learn python’

Python String operations

String Concatenation

To concatenate, or combine, two strings use the + operator.


a = “10”
b = “5”
c = a + b
What value will c have and what type?

15 (String)

Try to concatenate String with int, get an error:

str = '123' + 3
TypeError: can only concatenate str (not "int") to str

#convert from string to int:

str = int('123') + 3

String Multiplication

You can use <strong>*</strong> to repeat strings
my_string = "hi"
print(my_string * 3)
# results hihihi

Slicing strings in Python

You can return a range of characters by using the slice syntax(specify the start index and the end index, separated by a colon, to return a part of the string).

If the second number is beyond the end of the string it stops at the end.

#Slice string
my_str = 'Welcome to webpedia'

If You leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string.

my_str = 'Welcome to webpedia'

How to reverse a String?

n = 'hello'

String Comparation

my_str = 'web'
if my_str == 'web':

Uppercase letters are generally less than lowercase letters.

All uppercase letters come before all lowercase letters, so be careful when sorting a list of words!

if 'XYZ' < 'abc':

len() function

To get the length of a string, use the len() function.

Len() is like print(), a built in function.

my_string = "Welcome to webpedia"
# 19

What does the len() function return when it receives an int instead of a string?

TypeError: object of type ‘int’ has no len()

my_string = "Welcome to webpedia"

Python String Methods

String Methods in Python behaves similarly to a function. Methods are functions that below to objects.

Methods are functions that are called using dot notation.

!!Methods do not modify the original strings, instead they return a new string that has been altered.

my_str = 'Hi Webpedia'
//hi webpedia
//Hi Webpedia

strip() method

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

my_string = " Welcome to webpedia "
# "Welcome to webpedia"

lstrip() or rstrip() remove whitespace at the left or right!

lower() method

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

my_string = "Welcome to webpedia"
print(my_string .lower())
# "welcome to webpedia"

format() method

The format() method formats the specified value(s) and insert them inside the string’s placeholder.
The placeholder is defined using curly brackets: {}.

print("{} reasons to learn Python".format(10))
# 10 reasons to learn Python

split() method

The split() method splits a string into a list. Read here about Python Lists, Operations & methods

You can specify the separator, the default separator is any whitespace.

Also multiple spaces do not matter, they are treated as a single space.

my_str = "reasons to learn Python"
# ['reasons', 'to', 'learn', 'Python']
Methods may or may not have arguments

Each of these methods accepts the string itself as the first argument of the method. However, they also could receive additional arguments, that are passed inside the parentheses, like:

replace() method

The replace() method search and replaces a string with another string:

my_string = "Welcome to webpedia"
print(my_string .replace("Welcome", "Hi"))
# "Hi to webpedia"

It replaces all occurrences of the search string with the replacement string.

find() method

The find() method finds the first occurrence of the specified value or -1 if the value is not found.

The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found.

my_str = "reasons to learn Python"
# 11

Type & Type Conversion

int + float = float

print(.1 + .1 + .1 + .1 == .4)

Because the float, 0.1 is actually slightly more than 0.1.
When we add several of them together will see the difference between the mathematically correct answer and the one that Python creates.

print(0 + 7)
# 7
print("0" + "7")
# 07
print("0" + 7)
# TypeError: can only concatenate str (not "int") to str
print(0 + "7")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

type() function

The type() function returns the type of the specified object

# <class 'int'>
# <class 'str'>
# <class 'float'>

Type Conversion

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

#convert from float to int:
a = int(2.0)
# <class 'int'>
#convert from string to int:
a = str(10)
# <class 'str'>

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

Leave a Reply

Your email address will not be published. Required fields are marked *