Python Lesson 2 (Variables and types)

Python is completely object oriented, and not “statically typed”. You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.

Numbers

Python supports two types of numbers – integers(whole numbers) and floating point numbers(decimals).

myint = 7
print(myint) # Print integer 7

myfloat = 7.0
print(myfloat) # Print float 7.0

myfloat = float(7)
print(myfloat) # Print float 7.0

Strings

Strings are defined either with a single quote or a double quotes.

mystring = 'hello'
print(mystring)

mystring = "hello"
print(mystring)

Assignment of variables

first = sec = third = 1 # All three variables will be assigned 1
first, sec, third = "Hi", 75, 23.1 # Variables will be assigned in turn

To assign variable value from keyboard use command:

# String from keyboard will be assigned to variable first_var
first_var = input("Enter text: ") 

Change type of variable:

int_var = int(input("Enter integer number: "))
float_var = float(input("Enter float number: "))
str_var = str(input("Enter integer number: "))

float_var = float(int_var) # Convert int to float
int_var = int(float_var) + int(float_var) # Convert float to int
str_var = str(25) # Convert number 25 to string

If you try to convert string to number you will get error.

You can do arithmetic operations width variables

# Assign integer value 10 to variable int_var
int_var = int(5.0) + int(5.0) 

# Add 2 to int_var
int_var += 2

# Multiply string
str_var = 'Test'
str_var *= 5 # assing string 'TestTestTestTestTest'