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"
print(month)
#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:

  • A variable name must start with a letter or the underscore character.
  • 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).

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:

print(type(x))
# int
print(type(y))
# float

Operators

Python Arithmetic Operators

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

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 Identity Operators

In Python Identity operators are

is – evaluates if both sides have the same identity
is not – evaluates if both sides have different identities

Examples

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

print(bool("abc"))
# True
print(bool(10))
# True

Strings

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’

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.

Example

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

15 (String)

String Multiplication

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

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"
print(len(my_string))
# 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"
print(len(my_string))
#19

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.

strip() method

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

my_string = " Welcome to webpedia "
print(a.strip()) 
# "Welcome to webpedia"

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.
You can specify the separator, the default separator is any whitespace.

my_str = "reasons to learn Python"
print(my_str.split())
# ['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 replaces a string with another string:

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

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"
print(my_str.find('learn'))
# 11

Type & Type Conversion

int + float = float

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

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

print(type(10))
# <class 'int'>
print(type("10"))
# <class 'str'>
print(type(10.))
# <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)
print(type(a))
# <class 'int'>
#convert from string to int:
a = str(10)
print(type(a))
# <class 'str'>

Hello there!

I hope you find this post useful!

I'm Mihai, an 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 *