02 - Variables and Data Types
02 - 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.
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
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
• Methods
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 (+, *)
• Assignment operator (We will see more details on the section Iterations and Loops)
• 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
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
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.
• 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.