0% found this document useful (0 votes)
38 views

02 - Variables and Data Types

The document discusses variables and data types in Python. It covers topics like variable naming rules, data types including strings, integers, floats, Booleans, lists, dictionaries, tuples and sets. It also discusses operators, input/output and errors in Python programs.

Uploaded by

Attit Maharjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

02 - Variables and Data Types

The document discusses variables and data types in Python. It covers topics like variable naming rules, data types including strings, integers, floats, Booleans, lists, dictionaries, tuples and sets. It also discusses operators, input/output and errors in Python programs.

Uploaded by

Attit Maharjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Variables and Data Types

Agenda
• Variables
• Data types
• String
• Number
• Operators
• Math operator
• Comparison operator
• Input and Output
• Error message
Variables
• Variables:
▪ Variables are containers for storing data values.
▪ Variables are used to access and manipulate data stored in memory.
▪ A variable is created the moment you first assign a value to it.

Variable name value


Variables
• Variable Reassignment
▪ Variables can reference different values while program is running
▪ Variable that has been assigned to one type can be reassigned to another type
Variable naming rules
• Rules for naming variables in Python:
▪ Variable name cannot be a Python reserved word
o class = “A001”
o class_id = “A001”
▪ Variable name cannot contain spaces
o Item price = 150
o Item_price = 150
▪ First character must be a letter or an underscore; After first character may use letters, digits,
or underscores
o name1 = 30
o 1name = 30
▪ Variable names are case sensitive
o WORD = “first”
o word = “second”
• Variable name should reflect its use
Python reserved words

The following identifiers are used as reserved words, or keywords of the language, and
cannot be used as ordinary identifiers. They must be spelled exactly as written here:
Data types

Name Type Description Example


String str A sequence of characters “hello”, “course”, “covid-19”, “2”
Integer Int Whole numbers 2, 4, 100, 4000
Float float Numbers containing one or more decimals 3.8, 50.9, 100.0
Booleans bool Logical value indicating TRUE or FALSE True, False
[“hello”, “world”,”2021”]
List list Ordered sequence of objects
[“hello, 5, 100.0]
Dictionary dict Key: value pairs {“key1”: name1, “key2”:name2}
(10,20)
Tuples tup Ordered immutable sequence of objects
(“hello”, “world”)
{2,4,6,8}
Sets set Unordered collection of unique objects
{3,”hello”, 50.9}
Types of values/variables
• Use type function to get the type of value

• Check the type of variable


String
• Must be enclosed in single (‘) or double (‘‘) quote marks
String – Indexing and slicing
• A string can be thought of as a list of characters.
• An index refers to a position within an ordered list.
• Each character is given an index from zero (at the beginning) to the length minus one (at
the end).
h e l l o w o r l d
0 1 2 3 4 5 6 7 8 9 10

From position 0 to position 2, but NOT including 2.


Exercise
String - Methods
• Python has a set of built-in methods that you can use on strings
h e l l o w o r l d
0 1 2 3 4 5 6 7 8 9 10

You can use dir to list the methods available for an object.
String – Methods
• Use find() to search the place of a letter or a substring (it returns -1 if it is not
present).
String – in
• Use the in operator to check if a string contains another string.
Exercise
Numbers – integer and float
• Integer: Whole numbers
• Float: Numbers containing one or more decimals
Numbers – integer and float
• Type conversion

(chop off the decimal portion of a number)

• Methods

(round to the nearest integer)


(rounded to the second decimal place)

You can use dir(int) to list the methods available for int.
Operator – Math operators
• Operators are used to perform operations on variables and values.
Math operator Meaning
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
// Floored division
% Remainder
Operator – Comparison operators
• Comparison operators are used to compare values. It returns either True or False.

Comparison
Meaning
operator
> Greater than
< Less than
== Equal to
!= Not equal to
Greater than or
>=
equal to
Less than or
<= equal to
division
String operation
• Some operators also work with strings.
▪ Math operator (+, *)

▪ Comparison operator (==, !=)


Exercise
More operators
• Logical operator (We will see more details on the section Conditional Expression)

▪ and, or, not

• Assignment operator (We will see more details on the section Iterations and Loops)

▪ =, +=, -=, *=, /=


Input and Output
Input
• Most programs need to read input from the user. The simplest way to accomplish
this in Python is with input().

• input() always returns a string. If you want a numeric type, then you need to
convert the string to the appropriate type.
Exercise
Output – print function

• Display output with the print function


▪ Function: piece of prewritten code that performs an operation.

▪ Argument: data given to a function

Argument
Function name
Output – print multiple items
• Displaying multiple items with the print function
▪ Items are separated by commas when passed as arguments
▪ Items are automatically separated by a space when displayed on screen

▪ Argument “sep” and “end”


Output – print multiple lines
• Displaying multiple lines with the print function
▪ Break a statement into multiple lines by multiline continuation character (\n)

• Try to use “sep” to print multiple items by line.


Exercise
Output - String formatting
• String formatting is the process of inserting a custom string or variable in
predefined text.

• Python uses two different styles of string formatting.


1) str.format() method
2) % string formatter (optional)
Output – str.format() method
• The brackets and characters within them (called format fields) are replaced with
the objects passed into the str.format() method.

• Use :.2f to format a float to two decimal places.


Output - Old % str formatter
• The % operator can also be used for string formatting.
Exercise
Types of errors
1) Syntax errors : Violation of grammar" rules. Easiest to fix. Python tells you at which line
of your code the first error is detected

2) Logic errors (also called semantic errors): logical errors cause the program to behave
incorrectly. A program with logic errors can be run, but it does not operate as intended.
Built-in exceptions
• Even if the syntax of a statement is correct, it may still cause an error when executed.
• There are some built-in exceptions in Python.

See more types of errors https://docs.python.org/3/library/exceptions.html


Debugging
• What can you do about the errors? Debugging
• Debugging is the process of finding and resolving bugs (problems that prevent correct operation)
within computer programs.

• Think:
▪ What kind of error is it: syntax error, logic error?
▪ What information can you get from the error messages, or from the output of the program?
▪ What kind of error could cause the problem you're seeing?
▪ What did you change last, before the problem appeared?

• Retreat:
▪ At some point, the best thing to do is back off, undoing recent changes, until you get back to a
program that works and that you understand. Then you can start re-building.

You might also like