PyAnWin/Python Variables and Data Types

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Python Variables and Data Types

[edit | edit source]

Python is a dynamically typed language, meaning you don't need to declare variables with a specific type. Python variables can hold values of any data type.

Variable Assignment

[edit | edit source]

To assign a value to a variable, use the = sign:

 x = 5 name = "John"

Variable names can contain letters, numbers and underscores. They cannot start with a number.

Data Types

[edit | edit source]

Some common data types in Python:

Integers - Whole numbers like 1, 2, 3.

Floats - Decimal numbers like 1.5, 2.25.

Strings - Text values defined in quotes like "John"

Booleans - Logical values True or False.

Lists - Ordered sequence of values in []. Lists can hold different data types.

Tuples - Immutable ordered sequence of values in ().

Dictionaries - Collection of key-value pairs in { }.

Type Conversion

[edit | edit source]

You can convert between data types by using functions like int(), float(), str() etc:

 num = 5 #integer str_num = str(num) #converts to string

Checking Data Types

[edit | edit source]

You can check the type of a value with the type() function:

<syntaxhighlight lang="python"> num = 5 print(type(num)) # Prints <int> </syntaxhighlight