Python Variables and Data Types Guide
Python Variables and Data Types Guide
Python!
• A single statement can display multiple lines using newline characters (\n).
• Newline characters are “special characters” that position the screen cursor to
the beginning of the next line.
• Each occurrence of the \n escape sequence causes the screen cursor that
controls where the next character will appear to move to the beginning of the
next line.
Python Escape sequences
• Python offers special characters that perform certain tasks, such as backspace and
carriage return.
• A special character is formed by combining the backslash (\) character, also called
the escape character, with a letter.
• When a backslash exists in a string of characters, the backslash and the character
immediately following the backslash form an escape sequence.
Variables
• In a programming language, a variable is a memory location where you store a
value. The value that you have stored may change in the future according to the
specifications.
• A variable is a container (storage area) to hold data. It can be assigned a name,
you can use it to refer to it later in the program.
• A Python Variable is created as soon as a value is assigned to it. It does not
need any additional commands to declare a variable in python.
Variables
• Based on the value assigned, the interpreter decides its data type.
• You can always store a different type in a variable.
• For example, if you store 7 in a variable, later, you can store ‘Dinosaur’.
• There are a certain rules and regulations we have to follow while writing a variable, lets take a
look at the variable definition and declaration to understand how we declare a variable in python.
Variable Definition & Declaration
• Python has no additional commands to declare a variable. As soon as the value
is assigned to it, the variable is declared.
x = 10
#variable is declared as the value 10 is assigned to it.
• Note: Python is a type-inferred language, so you don't have to explicitly define
the variable type.
• It automatically knows that 10 is an integer and declares the x variable as n
integer.
Python Variables Naming Rules
• Variable names in Python can be any length.
• There are certain rules to what you can name a variable (called an identifier):
The variable name cannot start with a number. Python variables can only begin
with a letter(A-Z/a-z) or an underscore(_).
The rest of the identifier can only contain alpha-numeric characters
(letters(A-Z/a-z) and numbers(0-9)) and underscores(_) .
No special characters are allowed (e.g. $, &, *, !, etc.).
Reserved words (keywords) cannot be used as identifier names.
The Python language reserves a small set of keywords that designate special
language functionality.
No object can have the same name as a reserved word.
You can see this list any time by typing help("keywords") to the Python
interpreter.
Python Reserved words (keywords)
Python Variables Naming Rules
Python is case-sensitive (Lowercase and uppercase letters are not the same), and so
are Python identifiers:
Name and name are two different identifiers.
age, Age and AGE are three different variables.
There is nothing stopping you from creating two different variables in the
same program called age and Age, or for that matter AGE. But it is probably
ill-advised.
It would certainly be likely to confuse anyone trying to read your code, and
even you yourself, after you’d been away from it awhile.
• If you give a variable an illegal name, you get a syntax error when you try to
execute the code.
Python Variables Naming Rules
• It is worthwhile to give a variable a name that is descriptive enough to make
clear what it is being used for.
• For example, suppose you are tallying the number of people who have
graduated college. You could conceivably choose any of the following:
numberofcollegegraduates = 2500
NUMBEROFCOLLEGEGRADUATES = 2500
numberOfCollegeGraduates = 2500
NumberOfCollegeGraduates = 2500
number_of_college_graduates = 2500
• All of them are probably better choices than n, or ncg, or the like.
• At least you can tell from the name what the value of the variable is supposed
to represent.
Python Variables Naming Rules
• You will see later that variables aren’t the only things that can be given names.
• You can also name functions, classes, modules, and so on.
• The rules that apply to variable names also apply to identifiers, the more
general term for names given to program objects.
Python Variables Naming Rules
State whether these variable names (identifiers) are legal or illegal:
myvar = "samy"
more@ = 5
_a1 = 4
my name = “wael”
my_name = “wael”
2myvar = 7
myvar2 = 7
my-var = "saed"
Python Variables Naming Rules
State whether these variable names (identifiers) are legal or illegal:
for = 8
Del = 7.2
1sampleNumber = 5
firstN* = 'Reena'
last!Name = 'Bob'
second 1 = 2l.45
Myfirstnumber = 4
Multi Words Variable Names
• Variable names with more than one word can be difficult to read.
• There are several techniques you can use to make them more readable:
Camel Case
• Each word, except the first, starts with a capital letter:
myVariableName = "samy"
Pascal Case
• Each word starts with a capital letter:
MyVariableName = "samy"
Snake Case
• Each word is separated by an underscore character:
my_variable_name = "samy"
Assigning and Reassigning Python Variables
• To assign a value to Python variables, you don’t need to declare its type.
• You name it according to the rules stated in the previous section, and type the
value after the equal sign(=).
age=7
print(age)
7
age='Dinosaur'
print(age)
Dinosaur
Assigning and Reassigning Python
Variables
• you cannot use Python variables before assigning it a value.
• You can’t put the identifier on the right-hand side of the equal sign, though. The
following code causes an error.
• 7=age
• SyntaxError: can’t assign to literal
Multiple Python variables Assignment
• You can assign values to multiple Python variables in one statement.
• In multiple assignment, the number of variables on the left side of the
assignment operator (=) must match the number of values on the right side. To
separate the values, use a comma ,:
a, b = 1, 2
• Multiple assignment is not limited to one data type:
x, y, z = 1, "Hello", True
• you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
Data Types
• One fundamental thing that any programming language must be able to do is
represent items of data.
• a data type, in any programming language, is essentially a classification
specifying the value type that can be stored in a variable.
• Further, it also shows which operations (mathematical, relational, logical) can
be carried out on without running into an error.
• For example, a string is a data type that is used to classify text and an integer is
a data type used to classify whole numbers.
• Python provides several built-in data types.
• Since everything is an object in Python programming, data types are actually
classes and variables are instances(object) of these classes.
Data Types
• Python Data types are the classification or categorization of data items.
• It represents the kind of value that tells what operations can be performed on a
particular data.
• Since everything is an object in Python programming, Python data types are
classes and variables are instances (objects) of these classes.
• Each data type has its own set of methods and properties that you can use to
manipulate and work with the data.
• Understanding the characteristics of each data type is essential for efficient and
effective programming in Python.
• Python has a variety of built-in data types that you can use to represent
different kinds of values.
Data Types
• The following are the standard or built-in data types in Python:
Data Types
• The following table outlines the different built-in datatypes (along with an example of each category), available
in the Python language.
Numeric Data Types in Python
• The numeric data type in Python represents the data that has a numeric value.
• A numeric value can be an integer, a floating number, or even a complex number.
These values are defined as Python int, Python float, and Python complex classes in
Python.
Integers
• This value is represented by int class.
• It contains positive or negative whole numbers (without fractions or decimals).
• In Python, there is no limit to how long an integer value can be.
Float
• This value is represented by the float class.
• It is a real number with a floating-point representation.
• It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
Numeric Data Types in Python
Complex Numbers
• A complex number is represented by a complex class.
• It is specified as (real part) + (imaginary part)j. For example – 2+3j
a=2+3j
Boolean Data Type in Python
• Python Data type with one of the two built-in values, True or False.
• It is denoted by the class bool.
• Note: True and False with capital ‘T’ and ‘F’ are valid booleans otherwise
python will throw an error.
• For Example:
print(type(True))
print(type(False))
print(type(true))
<class 'bool'>
<class 'bool'>
NameError: name 'true' is not defined
Boolean Data Type in Python
• The first two lines will print the type of the boolean values True and False,
which is <class ‘bool’>.
• The third line will cause an error, because true is not a valid keyword in Python.
• Python is case-sensitive, which means it distinguishes between uppercase and
lowercase letters.
• You need to capitalize the first letter of true to make it a boolean value.
Python Strings
• String is a sequence of characters represented by either single or double
quotes.
• Strings in python are used to represent unicode character values.
• Python does not have a character data type, unlike C++ or Java. a single
character is also considered as a string of length one.
• We denote or declare the string values inside single quotes or double quotes or
even triple quotes.
• It is represented by str class.
Python Strings
Example
a = "Hello"
print(a)
Hello
Multiline Strings
• You can assign a multiline string to a variable by using three double quotes (Or three
single quotes):
a = """This is a
multi line string."""
print(a)
Command line input for strings
x = input()
print( 'hello' , x)
Accessing elements of String
• The line thing = 42; is attempting to change the type of thing from a string to an
int. If you compile this code, you will see the error:
Dynamic Typing vs. Static Typing
Trade-offs: Performance vs. Flexibility
• Static typing offers certain benefits, such as improved performance due to
compile-time optimization and early detection of type-related errors.
• However, it also imposes stricter constraints on variable usage and may require
additional effort to accommodate changing data types.
Python’s Dynamic Typing Philosophy
• Python’s design philosophy prioritizes developer productivity and ease of use.
• By employing dynamic typing, Python empowers programmers with flexibility,
allowing them to focus on the logic of their code rather than rigid type
declarations.
Type Hinting
• While dynamic typing offers flexibility, it also creates room for potential bugs.
• Here's where type hints come in. They can significantly enhance code
readability and prevent type-related errors.
• Starting from Python 3.5, the language introduced the typing module, which
provides the ability to add type hints while declaring variables.
• Type hinting is a formal solution to statically indicate the type of a value within
your Python code.
• This feature, defined in PEP 484 (Python Enhancement Proposal), allows
developers to annotate function signatures, variable types, and return types.
Type Hinting
• Although type hints are optional and do not enforce strict static typing, they
serve as documentation and can be utilized by type checkers and linters for
improved code analysis and error detection.
• The main purpose of type hinting in Python is to give developers a way to make
their code as self-describing as possible, both for their own benefit and that of
other developers.
• It’s important to note that the Python interpreter ignores type hints completely.
Type Hinting
• Python's typing module contains several functions and classes that are used to
provide type hints for your Python code.
• To provide type hints for variables, you can use the colon : symbol followed by
the type. Here's an example:
age: int = 20
name: str = "Alice"
is_active: bool = True
• Here, age is hinted as an integer, name as a string, and is_active as a boolean.
Type Hinting Limitations
Not enforced at runtime
• Python's type hints are not enforced but are merely hints, and the Python
interpreter will not raise errors if the provided types do not match the actual
values.
• This might lead to a misconception that type hints can enforce type safety,
which they cannot.
Over-complicated
• For small or simple scripts, type hints might seem like an overkill, and could
potentially complicate code that should be straightforward and simple.
Not flexible
• One of the reasons for Python's popularity is its dynamic nature and type hints
can restrict this.
Specify the data type of a variable in Python
• There may be times when you want to specify a type on to a variable.
• This can be done with casting.
• Python is an object-orientated language, and as such it uses classes to define
data types, including its primitive types.
• Casting in python is therefore done using constructor functions:
int() - constructs an integer number from an integer literal, a float literal (by
rounding down to the previous whole number), or a string literal (providing the
string represents a whole number)
• Examples:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Specify the data type of a variable in Python
float() - constructs a float number from an integer literal, a float literal or a
string literal (providing the string represents a float or an integer)
• Examples:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Specify the data type of a variable in Python
str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals
• Examples:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Reading input from the user
• Developers often have a need to interact with users, either to get data or to
provide some sort of result.
• Python user input from the keyboard can be read using the input() built-in
function.
• The input() function first takes the input from the user and converts it into a
string. The type of the returned object always will be <class ‘str’>.
• When the input function is called it stops the program and waits for the user’s
input. When the user presses enter, the program resumes and returns what the
user typed.
• The program halts indefinitely for the user input. There is no option to provide
timeout value.
• If we enter EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), EOFError is raised and
the program is terminated.
Reading input from the user
• Syntax:
inp = input('STATEMENT')
• Here is a simple example of getting the user input and printing it on the
console.
name = input('What is your name?\n') # \n ---> newline ---> It causes a line break
What is your name?
Samy
• The text or message displayed on the output screen to ask a user to enter an
input value is optional i.e. the prompt, which will be printed on the screen is
optional.
• Whatever you enter as input, the input function converts it into a string.
• if you enter an integer value still input() function converts it into a string. You
need to explicitly convert it into an integer in your code using typecasting.
Typecasting the input to Integer
• There might be conditions when you might require integer input from the
user/Console, the following code takes two inputs from the console and typecasts
them to an integer then prints the sum.
# input
num1 = int(input())
num2 = int(input())
# printing the sum in integer
print(num1 + num2)
Typecasting the input to Float
• To convert the input to float the following code will work out.
# input
num1 = float(input())
num2 = float(input())
# printing the sum
print(num1 + num2)
Recommended Articles
• Architecture of Computer System | Computer Architecture Tutorial | Studytoni
ght
• [Link]
• Python Variables ([Link])
• Python Data Types ([Link])
• Python Data Types | DigitalOcean
• Python Data Types - GeeksforGeeks
• Python Variables and Data Types - A complete guide for beginners - DataFlair (
[Link])
• Python Comments ([Link])
• Variables in Python – Real Python
• Understanding Data Types in Python with Examples - StrataScratch
Recommended Articles
• How to specify a variable type in Python ([Link])
• DataTypes and Variables in Python | Python in Plain English
• 2.3. Variable names and keywords — Python for Everybody - Interactive (runes
[Link])
• Python Specify Variable Type ([Link])
• Python User Input from Keyboard - input() function - AskPython
• Taking input from console in Python - GeeksforGeeks
• Taking input in Python - GeeksforGeeks
• Understanding the Dynamic Typing Nature of Python: A Comprehensive Guide
| by RS Punia 💠 | Medium
• Dynamic vs Static – Real Python
• Is Python a dynamically typed language? ([Link])
Recommended Articles
• PEP 484 – Type Hints | [Link]
• Get started with Python type hints | InfoWorld
• Type Hinting in Python | Dagster Blog
• Python Type Hints ([Link])
• Pros and Cons of Type Hints – Real Python
• DataTypes and Variables in Python | Python in Plain English
• Python String format() Method ([Link])
• Python String Format – Python S Print Format Example ([Link])
• Python String format() Method - GeeksforGeeks
• Python | Output Formatting - GeeksforGeeks
• Unpacking And Multiple Assignment in Python on Exercism
Recommended Articles
• Python Strings ([Link])