Variables and Data Types

What's Variable

Variables are containers for storing data values.

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Variables do not need to be declared with any particular type, and can even change type after they have been set.

Types are only associated with objects of variables

Variable Types

Strings

# define variable
name = "Ayman"
print(name)        
Output: Ayman
# new line
name = "Ayman\nAyman" 
print(name)        
Output: Ayman
          Ayman

Numbers

Operation on Variables

String Operations

  • Strings are immutable

  • Concatenation var1 + var2 = 'var1var2' var1 + '' +var2 = 'var1 var2'

  • Repeated sequence buffer = "A"*100

  • Slicing string[start:end:step]

  • int to string int("100") Output: 100

  • string.find(value)

  • string.replace(old_value, new_value)

  • and a lot more ... check manual

Numbers Operations

normal as other languages

x**y (x power y)

String Formatting

Option #1: %-formatting

Option #2: str.format()

Memory Location

Casting

If you want to specify the data type of a variable, this can be done with casting.

Get the Type

You can get the data type of a variable with the type() function.

Single and Double Quotes

both are the same

Case-Sensitive

Variable names are case-sensitive.

Last updated