0% found this document useful (0 votes)
13 views81 pages

Python Variables and Data Types Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views81 pages

Python Variables and Data Types Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Module 2

Python Variables and Data Types


Outline
2.1Computer Organization
2.2 First Program in Python: Printing a Line of Text
2.3 Python Comments
2.4 Ways To Execute Python Code
2.5 Displaying a Single Line of Text with Multiple Statements
2.6 Displaying Multiple Lines of Text with a Single Statement
2.7 Python Escape sequences
2.8 Variables
2.9 Variable Definition & Declaration
Outline
2.10 Python Variables Naming Rules
2.11 Multi Words Variable Names
2.12 Assigning and Reassigning Python Variables
2.13 Multiple Python variables Assignment
2.14 Data Types
2.15 Numeric Data Types in Python
2.16 Boolean Data Type in Python
2.17 Python Strings
2.18 Accessing elements of String
2.19 Python type() Function
Outline
2.20 Output Variables
2.21 Output Formatting in Python
2.22 The Dynamic Typing Nature of Python
2.23 Dynamic Typing in Action
2.24 Features of dynamic typing
2.25 Disadvantages of dynamic typing
2.26 Static Typing
Outline
2.27 Dynamic Typing vs. Static Typing
2.28 Type Hinting
2.29 Type Hinting Limitations
2.30 Specify the data type of a variable in Python
2.31 Reading input from the user
2.32 Typecasting the input to Integer
2.33 Typecasting the input to Float
2.34 Recommended Articles
Computer Organization
• Virtually every computer, regardless of differences in physical appearance, can
be envisioned as being divided into five logical units, or sections:
Input units
• This “receiving” section of the computer obtains information (data and computer
programs) from various input devices.
• The input unit then places this information at the disposal of the other units to
facilitate the processing of the information.
• Today, most users enter information into computers via keyboards and mouse
devices.
• Other input devices include microphones (for speaking to the computer), scanners
(for scanning images) and digital cameras and video cameras (for taking photographs
and making videos).
Computer Organization
Output units
• This “shipping” section of the computer takes information that the computer has
processed and places it on various output devices, making the information available
for use outside the computer.
• Computers can output information in various ways, including displaying the output on
screens, playing it on audio/video devices, printing it on paper or using the output to
control other devices.
Memory unit
• This is the rapid-access, relatively low-capacity “warehouse” section of the computer,
which facilitates the temporary storage of data.
• The memory unit retains information that has been entered through the input unit,
enabling that information to be immediately available for processing.
Computer Organization
• In addition, the unit retains processed information until that information can be
transmitted to output devices.
• Often, the memory unit is called either memory or primary memory—random access
memory (RAM) is an example of primary memory.
• Primary memory is usually volatile, which means that it is erased when the machine
is powered off.
CPU
• It is Central Processing Unit of the computer. The control unit and ALU are together
known as CPU.
• CPU is the brain of computer system. It performs following tasks:
 It performs all operations.
 It takes all decisions.
 It controls all the units of computer.
Computer Organization
Arithmetic and logic unit (ALU)
• All the calculations are performed in ALU of the computer system.
• The ALU can perform basic operations such as addition, subtraction, division,
multiplication etc.
• It also contains decision mechanisms, allowing the computer to perform such tasks as
determining whether two items stored in memory are equal.
Control Unit
• It controls all other units of the computer.
• It controls the flow of data and instructions to and from the storage unit to ALU.
• Thus it is also known as central nervous system of the computer.
Computer Organization
Secondary storage unit
• This unit is the long-term, high-capacity “warehousing” section of the
computer.
• Secondary storage devices, such as hard drives and disks, normally hold
programs or data that other units are not actively using; the computer then can
retrieve this information when it is needed—hours, days, months or even years
later.
• Information in secondary storage takes much longer to access than does
information in primary memory.
• However, the price per unit of secondary storage is much less than the price per
unit of primary memory.
• Secondary storage is usually nonvolatile—it retains information even when the
computer is off.
Python Comments
• A comment does not have to be text that explains the code, it can also be used
to prevent Python from executing code:
#print("Hello, World!")
print("Cheers, Mate!")
• Unlike other programming languages, Python does not have a separate symbol
for a multiple-line comment, so each line of multiple-line comment must start
with the # symbol.
#This is a comment
#written in
#more than just one line
print("Hello, World!")
First Program in Python: Printing a
Line of Text
1 # [Link]
2 # Printing a line of text in Python.
3
4 print "Welcome to Python!"
Welcome to Python!
• Lines 1–2 begin with the pound symbol (#), which indicates that the remainder of each line
is a comment.
• Programmers insert comments to document programs and to improve program readability.
• Comments also help other programmers read and understand your program.
• Comments do not cause the computer to perform any action when the program is run—
Python ignores comments.
• We begin every program with a comment indicating the file name in which that program is
stored (line 1).
• We can place any text we choose in comments.
Python Comments
• A comment that begins with # is called a single-line comment, because the
comment terminates at the end of the current line.
• A # comment also can begin in the middle of a line and continue until the end
of that line.
• Such a comment typically documents the Python code that appears at the
beginning of that line.
• The comment text “Printing a line of text in Python.” describes the purpose of
the program (line 2).
Python Comments
• Good Programming Practice 2.1
• Place abundant comments throughout a program.
• Comments help other programmers understand the program, assist in
debugging a program (i.e., discovering and removing errors in a program) and
list useful information.
• Comments also help you understand your programs when you revisit the code
for modifications or updates.
• Good Programming Practice 2.2
• Every program should begin with a comment describing the purpose of the
program.
• Good Programming Practice 2.3
• Use blank lines to enhance program readability.
Python Comments
• Or, not quite as intended, you can use a multiline string.
• Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your comment
inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
• As long as the string is not assigned to a variable, Python will read the code, but
then ignore it, and you have made a multiline comment.
First Program in Python: Printing a
Line of Text
1 # Fig. 2.1: fig02_01.py
2 # Printing a line of text in Python.
3
4 print ("Welcome to Python!")
Welcome to Python!
• The Python print command (line 4) instructs the computer to display the string
of characters contained between the quotation marks.
• A string is a sequence of characters contained inside double quotes.
• The entire line is called a statement.
First Program in Python: Printing a
Line of Text
• Output (i.e., displaying information) and input (i.e., receiving information) in
Python are accomplished with streams of characters.
• When the preceding statement executes, it sends the stream of characters
Welcome to Python! to the standard output stream.
• The standard output stream is the channel through which an application
presents information to the user—this information typically is displayed on the
screen, but may be printed on a printer, written to a file, etc.
Ways To Execute Python Code
• Python statements can be executed two ways:
• The first way is by typing statements into an editor to create a program and
saving the file with a .py extension (as in Fig. 2.1).
• Python files typically end with .py, although other extensions (e.g., .pyw on
Windows) can be used.
• To use the Python interpreter to execute (run) the program in the file, type
python [Link] at the DOS or Unix shell command line, in which [Link] is the
name of the Python file.
• The second way to execute Python statements is interactively.
• Typing python at the shell command line runs the Python interpreter in
interactive mode.
• With this mode, the programmer types statements directly to the interpreter,
which executes these statements one at a time.
Displaying a Single Line of Text with
Multiple Statements
print "Welcome",
print "to Python!"
Welcome to Python!
• Normally, after the print statement displays its string, Python begins a new line
—subsequent outputs are displayed on the line or lines that follow the print
statement’s string.
• However, the comma (,) at the end of line 4 tells Python not to begin a new line
but instead to add a space after the string; thus, the next string the program
displays (line 5) appears on the same line as the string "Welcome".
Displaying Multiple Lines of Text with a
Single Statement
print "Welcome\nto\n\nPython!"
Welcome
to

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

• In Python programming, individual characters of a String can be accessed by using the


method of Indexing.
• Negative Indexing allows negative address references to access characters from the back of
the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
name = 'edureka'
print("First character of String is: ")
print(name [0])
print("\nLast character of String is: ")
print(name [-1])
Accessing elements of String
First character of String is:
E
Last character of String is:
A
Python type() Function
• We can use the type() function to know which class a variable or a value
belongs to. Let's see an example:
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 2.0
print(num2, 'is of type', type(num2))
num3 = 1+2j
print(num3, 'is of type', type(num3))
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>
Output Variables
• The Python print() function is often used to output variables.
x = "Python is awesome"
print(x)
Python is awesome
• In the print() function, you output multiple variables, separated by a comma:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Python is awesome
Output Variables
• You can also use the + operator to output multiple variables:
x = "Python"
y = "is"
z = "awesome"
print(x + y + z)
Pythonisawesome
• For numbers, the + character works as a mathematical operator:
x=5
y = 10
print(x + y)
15
Output Variables
• In the print() function, when you try to combine a string and a number with the
+ operator, Python will give you an error:
x=5
y = "John"
print(x + y)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
• The best way to output multiple variables in the print() function is to separate
them with commas, which even support different data types:
x=5
y = "John"
print(x, y)
5 John
Output Formatting in Python
• In Python, there are several ways to present the output of a program.
• Data can be printed in a human-readable form, or written to a file for future
use, or even in some other specified form.
• Users often want more control over the formatting of output than simply
printing space-separated values.
Formatting Output using The Format Method
• The format() method was added in Python(2.6).
• The format method of strings requires more manual effort.
• Users use {} to mark where a variable will be substituted and can provide
detailed formatting directives, but the user also needs to provide the
information to be formatted.
• This method lets us concatenate elements within an output through positional
formatting.
Output Formatting in Python
• The format() method formats the specified value(s) and insert them inside the
string's placeholder.
• The placeholder is defined using curly brackets: {}.
• The format() method returns the formatted string.
• The placeholders can be identified using named indexes {price}, numbered
indexes {0}, or even empty placeholders {}.
Output Formatting in Python
• Example using different placeholder values:
Example 1
name = "samy"
age = 22
txt1 = "My name is {}, I'm {} years old".format(name,age)
txt2 = "My name is {0}, I'm {1} years old".format(name,age)
txt3 = "My name is {myname}, I'm {myage} years old".format(myname = name ,
myage = age)
print(txt1 )
print(txt2)
print(txt3)
Output Formatting in Python
My name is samy, I'm 22 years old
My name is samy, I'm 22 years old
My name is samy, I'm 22 years old
Output Formatting with f-strings in Python
• The release of Python version 3.6 introduced formatted string literals,
simply called “f-strings”.
• Formatted string literals (or f-strings) allow you to include expressions inside your
strings. Just before the string you place an f or F which tells the computer you want to
use an f-string.
• f-strings are really the most simple and practical way for formatting strings.
Example 1
name = "samy"
print(f"hany and {name} have been friends since grade school.”)
hany and samy have been friends since grade school.
Output Formatting with f-strings in Python
Example 2
name = "samy"
age = 22
print(f"My name is {name}, I'm {age} years old")
My name is samy, I'm 22 years old
The Dynamic Typing Nature of Python
• Python is a dynamically typed language.
• This means that variable types are determined and checked at runtime rather
than during compilation.
• In dynamically typed languages like Python, you don’t need to explicitly declare
the variable type before using it. Instead, the type is inferred based on the
value assigned to the variable.
• This means that the Python interpreter does type checking only as code runs,
and the type of a variable is allowed to change over its lifetime.
• In dynamic typing, variables can be reassigned to different types of values
during the execution of a program.
• This flexibility allows for more concise and flexible code, as you can use the
same variable to store different types of data throughout the program.
Dynamic Typing in Action
• To grasp the concept better, let’s consider an example. In Python, you can create a
variable and assign it an integer value:
x=5
• Later in your program, you can reassign the variable x to a string value:
x = "hello"
• Python’s dynamic typing allows the variable x to change its data type seamlessly based
on the value assigned to it.
• This flexibility enables developers to adapt their code and manipulate variables without
rigid type constraints.
Features of dynamic typing
• Below are some features of dynamic typing:
Type inference
• In Python, you don’t need to declare the type of a variable explicitly.
• The interpreter infers the type based on the value assigned to it. If you, for
instance, assign an integer to a variable, it becomes an integer type, and if you
later assign a string to the same variable, it becomes a string type.
Runtime type checking
• Dynamic typing allows for runtime type checking. This means that the type of a
variable is checked during the execution of the program.
• If an operation is performed on a variable that is not compatible with its
current type, a runtime error will occur.
Features of dynamic typing
Flexibility and expressiveness
• Dynamic typing offers greater flexibility and expressiveness in writing code.
• It allows you to easily change the type of a variable or use the same variable to hold
different types of data.
• This flexibility is particularly useful when dealing with complex or evolving data
structures.
Rapid prototyping and iterative development
• Dynamic typing simplifies the process of rapid prototyping and iterative development.
• You can quickly write and test code without the need for explicit type declarations,
making it easier to experiment and make changes on the fly.
Enhanced productivity
• The dynamic nature of Python’s typing system often leads to enhanced productivity.
Disadvantages of dynamic typing
• However, one of the main disadvantages of such a language is that debugging becomes
very difficult as the variable type is not known until runtime.
• It can be difficult to spot errors/bugs from type mismatches.
Static Typing
• The opposite of dynamic typing is static typing. Static type checks are
performed without running the program.
• In most statically typed languages, for instance C and Java, this is done as your
program is compiled.
• The type of a variable is not allowed to change over its lifetime.
• In contrast to dynamic typing, static typing requires variables to be declared
with a specific data type at compile time.
• Once assigned, the data type of a statically typed variable cannot be changed
during runtime.
Static Typing
• In this Hello World example in Java, look at the middle section, where String
thing; is statically defined as a type of String and then assigned the value thing =
"Hello World";:
Static Typing
• If you were to try to reassign thing to a value that is of a different type, you will not get
an error initially. Only when the code is compiled would you see the error:

• 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])

You might also like