Python Basics: Variables and Data Types
Python Basics: Variables and Data Types
1. Introduction
Lecture 2 2. Variable
Introduction to Python 3. Assignment Statement
Sequential Coding
4. Data Type
5. Operators
6. Input and Output Statements
7. Sequential Coding
8. Lab Exercise
Computer Science, CMU 204101 Introduction to Computer 1 Computer Science, CMU 204101 Introduction to Computer 2
Computer Science, CMU 204101 Introduction to Computer 3 Computer Science, CMU 204101 Introduction to Computer 4
Two Modes of Execution 1.3 The First Program
We will use IDLE, Python’s default GUI (Graphical User Interface
1.
Interactive Mode 2.
3.
Work line-by-line, also serve as a main interface
Some Explanations
Line 1 is a comment (start with #) comments are just notes by/for programmers, and will not
be run
Line 2 is another comment, # will denote that the rest of the text to the end of the line is
Script Mode comment
Line 3 contains print() command, which will print string (text) inside the parentheses.
Run the whole file (a program)
When you run (press F5) the program, you should get the following (blue text):
Run
Computer Science, CMU 204101 Introduction to Computer 7 Computer Science, CMU 204101 Introduction to Computer 8
Examples of Variable Naming 3. Assignment Statement
Assignment statement is how we give value to a variable
Variable Name Valid? Why Not?
In other languages, variables need to be declared before usage. But in
python, variables are automatically declared the first time they are
123MyID Cannot start with number assigned values
We assign value to a variable using = operator, for example:
_ThinkBig score = 75
# score is an integer variable with the value of 75
mylife@CMU Cannot contain @ gpa = 2.85
# gpa is a floating point (real number) variable with the value of 2.85
Pin number Cannot contain space NOTE: In Python, you can actually assign values to multiple variables in one line,
for example:
score, gpa = 75, 2.85
Dorm_number Will do the same as the statements above.
Computer Science, CMU 204101 Introduction to Computer 9 Computer Science, CMU 204101 Introduction to Computer 10
Computer Science, CMU 204101 Introduction to Computer 11 Computer Science, CMU 204101 Introduction to Computer 12
4.1 Number Data Type (int, float) 4.2 Boolean Data Type
int contains integer, which are number without decimal Boolean variable can either be True, or False, usually a
point. Example: 2, -50, 1009 result of a comparison. For examples:
float contains real number, sometime called floating point 4 > 1 will get you True
number. Real number can have decimal point. Example: 6 < 7 will get you False
15.20, -21.9 boolean can be very useful in programming. It is use in
selection (if statement) to have program does different
things, based on comparison results.
Computer Science, CMU 204101 Introduction to Computer 13 Computer Science, CMU 204101 Introduction to Computer 14
Computer Science, CMU 204101 Introduction to Computer 15 Computer Science, CMU 204101 Introduction to Computer 16
Examples: Working with String 4.4 List
str = 'Hello World!'
print (str) # Prints complete string
list is a container data type. A list can have multiple items.
print (str[0]) # Prints first character of the string Items in the list can be of multiple data types (compound data type)
print (str[2:5]) # Prints characters starting from 3rd to 5th (end - 1 is 5-1 = 4)
print (str[2:]) # Prints string starting from 3rd character When displayed, items are shown inside [ ] and are separated by
print (str * 2) # Prints string two times comma (,)
print (str + "TEST ") # Prints concatenated string
We can get values of item using [ ] and [ : ] and index values
This will produce the following result:
Like string, the first item is at index 0, and the last item is at end – 1
Hello World! 12
H
Example: myList = [‘Hello’, ‘my’, ‘student’] will looks like this
H e l l o W o r l d !
llo 3
llo World! 0 1 2 3 4 5 6 7 8 9 10 11
Hello World!Hello World! Hello my student
Hello World!TEST
0 1 2
Computer Science, CMU 204101 Introduction to Computer 17 Computer Science, CMU 204101 Introduction to Computer 18
Computer Science, CMU 204101 Introduction to Computer 19 Computer Science, CMU 204101 Introduction to Computer 20
5.1 Arithmetic Operators 5.2 Comparison Operators
Assume variable a holds 10 and variable b holds 20, then: Assume variable a holds 10 and variable b holds 20, then:
Computer Science, CMU 204101 Introduction to Computer 21 Computer Science, CMU 204101 Introduction to Computer 22
Computer Science, CMU 204101 Introduction to Computer 23 Computer Science, CMU 204101 Introduction to Computer 24
5.5 Other Operators 5.6 Operators Precedence
To decide which operator will be performed first, Python follow the precedence
There are other operators that will not be covered (yet) denote in the table below:
Bitwise operators work on number bit by bit: >>, <<, &, | For operators with the same precedence, perform the left one first
Operator Description Highest Precedence
Python Membership Operators: in , not in () parentheses
** Exponentiation (raise to the power)
Python Identity Operators: is , is not ~ + - Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators Lowest Precedence
Computer Science, CMU 204101 Introduction to Computer 25 Computer Science, CMU 204101 Introduction to Computer 26
Computer Science, CMU 204101 Introduction to Computer 27 Computer Science, CMU 204101 Introduction to Computer 28
Example: Operators Precedence #2 Example: Operators Precedence #3
Find the result of -(-5) * (x % y – x // (y+1)), with the following assignments Find the result of c // d + y % x != 2*c – d, with the following assignments
x = 16 x = 16
y=4 y=4
c = 2.5 c = 2.5
d = 0.25 d = 0.25
Solution Solution
-(-5) * (x % y – x // (y+1))
-(-5) * (16 % 4 – 16 // (4+1))
c // d + y % x != 2*c – d
-(-5) * (16 % 4 – 16 // (5)) 2.5 // 0.25 + 4 % 16 != 2*2.5 – 0.25
5 * (16 % 4 – 16 // 5) 10 + 4 != 5 – 0.25
5 * (0 – 3)
14 != 4.75
5 * (– 3)
-15 True
The answer is -15 The answer is True
Computer Science, CMU 204101 Introduction to Computer 29 Computer Science, CMU 204101 Introduction to Computer 30
Computer Science, CMU 204101 Introduction to Computer 31 Computer Science, CMU 204101 Introduction to Computer 32
6. Input-output Statements (Recap) 6.1 print()
For a program to be able to interact with the user, the print() will display its arguments (values inside the
program need a way to: parentheses) on interactive mode windows.
Receive data from the user (input), and You can print multiple strings/variables at the same time
Display result to user (output) by separating them with comma (,). The texts will be
We will start with: concatenated when printed.
Output: print() function If you want the text to start a new line, you can add new
Input: input() function line character (\n) in the text
You can also use \t for tab
Computer Science, CMU 204101 Introduction to Computer 33 Computer Science, CMU 204101 Introduction to Computer 34
Computer Science, CMU 204101 Introduction to Computer 35 Computer Science, CMU 204101 Introduction to Computer 36
6.2 input() (cont.) 7. Writing Sequential Code
Warning: be careful about input data type. Translate from design (description, pseudocode, or
Example: flowchart) into programming code
inp=input("Input number : ") You might need to do program analysis and program
no=int(inp) design first!
Start from the top, moving downward and end at the
bottom
If the user input 1.2, it will read and put into inp with
problem. BUT when Python try to convert it to integer, an
error will occur (since 1.2 is not an integer)
Computer Science, CMU 204101 Introduction to Computer 37 Computer Science, CMU 204101 Introduction to Computer 38
input HEIGHT
print AREA
STOP
Computer Science, CMU 204101 Introduction to Computer 39 Computer Science, CMU 204101 Introduction to Computer 40
7.2 Coding Example #02 – Swapping Concept 7.2 Coding Example #02 – Step by Step
VERY IMPORTANT: A code will be executed one line at a 1. tmp = A # assign the value of A to tmp
time, so If you do A = B first, the original value of A will be 5 tmp
lost
You will need temporary variable (tmp)
A 5 7 B
2. A=B # assign the value of B to A
tmp
5 tmp
A 5 7 B
A 7 7 B
Computer Science, CMU 204101 Introduction to Computer 41 Computer Science, CMU 204101 Introduction to Computer 42
7.2 Coding Example #02 – Step by Step (cont.) 7.2 Coding Example #02 – Complete Codes
B = tmp # assign value of tmp (A’s original values) to B
5 tmp
A 7 5 B
Computer Science, CMU 204101 Introduction to Computer 43 Computer Science, CMU 204101 Introduction to Computer 44
7.3 Coding Example #03 7.3 Coding Example #03 – General Idea
So first, some questions:
Finding Mean Average of Three Numbers What is(are) the input(s) of this program?
Output(s)?
“Receive three numbers from the input, the display the Process? Or, how do we calculate the mean of three numbers?
mean of those three numbers” Can you then describe the algorithm?
What are the steps you need to do to solve the problem, starting from: where are you
Note: use float() for the inputs going to get the input data from?
The program should work like this: If you’re not sure about the codes yet, write the steps down in comments first, then do the
coding for each step
Computer Science, CMU 204101 Introduction to Computer 45 Computer Science, CMU 204101 Introduction to Computer 46
Practice Reference
Find BMI bmi = weight / (height ** 2) Mark Lutz, “Programming Python”, O'Reilly, 1996.
Deitel ,”Python How to program”, Prentice-Hall,Inc., 2002.
Find an average of three numbers
Matt Telles , ”Python Power !”, Thomson Course Teachnology,2008.
Find the circumference of a circle python 3 help documentation
Find the area of a circle PYTHON TUTORIAL Simply Easy Learning by [Link]
Computer Science, CMU 204101 Introduction to Computer 47 Computer Science, CMU 204101 Introduction to Computer 48