0% found this document useful (0 votes)
8 views12 pages

Python Basics: Variables and Data Types

This document outlines an introductory lecture on Python programming, covering its history, basic concepts such as variables, data types, assignment statements, and operators. It includes explanations of Python's execution modes, examples of variable naming, and the use of different data types like integers, floats, strings, and lists. Additionally, it discusses various operators including arithmetic, comparison, and logical operators, along with their precedence in expressions.

Uploaded by

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

Python Basics: Variables and Data Types

This document outlines an introductory lecture on Python programming, covering its history, basic concepts such as variables, data types, assignment statements, and operators. It includes explanations of Python's execution modes, examples of variable naming, and the use of different data types like integers, floats, strings, and lists. Additionally, it discusses various operators including arithmetic, comparison, and logical operators, along with their precedence in expressions.

Uploaded by

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

Outline

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

1.1 History of Python 1.2 The Python Language


Developed in 1989 by Guido van Rossum while working Python is a high-level (3GL) language, with the following
for Centrum Wiskunde & Informatica (National Research characteristics:
Institute for Mathematics and Computer Science) in 1. It use interpreter, translating and processing codes
Amsterdam, Netherlands. line-by-line, which allows:
Python was first released in 1991 2. Interactive mode, allowing users to run their code one
Python combines features from many languages (ABC, commands at a time
Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, etc.) 3. It is currently, one of the most popular programming
with additional features such as easy-to-use interface. languages, especially for learning to program

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

[Link] Output (result) on interactive mode


Computer Science, CMU 204101 Introduction to Computer 5 Computer Science, CMU 204101 Introduction to Computer 6

2. Variable Reserved Words


Variables are used to reserve some memory to contain data. Variables can and exec not
have different data types, and can require different memory sizes.
assert finally or
In Python, there are some rules in naming variables.
1. It must begin with a letter (a - z, A - B) or underscore (_) break for pass
2. Other characters can be letters, numbers (0-9) or _ class from print
3. Cannot be reserved words continue global raise
4. No space allowed in variable’s name def if return
5. Can be any (reasonable) length
del import try
6. The name is case-sensitive, capital letters and lowercase letters are
considered different characters. elif in while
Example: NUM, Num, and num are considered different variables else is with
except lambda yield

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

Examples of Assignments 4. Data Type


You can also do chain assignment, where all the variables in the The followings are basic data types you should know:
chain will be assigned the value of the rightmost variables/constant
Example 1 1. int contains integer number
a=b=c=1 2. float contains real number
# a, b, and c will be integers, with the value of 1
Example 2 3. boolean contains True/False value
a, b, c = 1, 2 , “john” 4. string contains text
# a and b will be integer, with values of 1 and 2 respectively
5. list contains multiple items
# c will be string, containing john

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

4.3 String Data Type 4.3 String Data Type (cont.)


string is used to contain text. In python string can be denote by You can also access part of string, which we will call substring, by
quotation marks, and can use single ( ' ), double ( " ) or triple ( ''' using [] or [:] and index (location)
or """ ) marks. Characters in a string are stored by index, from 0 to end – 1
Examples: “Hello World!” example:
word = 'word'
12
sentence = "This is a sentence."
Triple marks are use for string longer than a single line H e l l o W o r l d !
paragraph = """This is a paragraph. It is 0 1 2 3 4 5 6 7 8 9 10 11
made up of multiple lines and sentences."""
Furthermore, you can use +, * operators The string has the length of 12
+ will concatenate two or more strings together The first character (index 0) is ‘H’
* will repeatedly concatenate one string multiple times The last character (index 11) is “!”

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

Examples: Working with List 5. Operators


exlist1 = ['abcd', 786 , 2.23, 'john', 70.2 ]
exlist2 = ['Hello' ,'my' , 'student']
Operators are symbols we used to perform some
action/operations on operands (variables or constants). Today,
print (exlist1) # Prints complete list
print (exlist1[0]) # Prints first element of the list
we will look at
print (exlist1[1:3]) # Prints elements starting from 2nd till 3rd (end - 1 is 3 – 1 = 2) 1. Arithmetic operators
print (exlist1[2:]) # Prints elements starting from 3rd element
print (exlist2 * 2)
print (exlist1 + exlist2)
#
#
Prints
Prints
list two times
concatenated lists
2. Comparison (relational) operators
3. Assignment operators
This will produce the following result:
5 4. Logical operators
['abcd', 786, 2.23, 'john', 70.2]
abcd
abcd 786 2.23 john 70.2 5. Bitwise operators
[786, 2.23] 0 1 2 3 4
[2.23, 'john', 70.2] 6. Membership operators
['Hello', 'my', 'student', 'Hello', 'my', 'student']
['abcd', 786, 2.23, 'john', 70.2, 'Hello', 'my', 'student'] 7. Identity operators

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:

Operator Description Example Result


Operator Description Example result
+ Addition a+b 30
- Subtraction a-b -10 == equal a == b False
* Multiplication a*b 200 != not equal a != b True
/ Division b/a 2 > greater than a>b False
% Modulus b%a 0 < less than a<b True
** Exponent 2**3 8
>= greater than or equal a >= b False
// Floor Division 9//2 4
<= less than or equal a <= b True
9.0//2.0 4.0

Computer Science, CMU 204101 Introduction to Computer 21 Computer Science, CMU 204101 Introduction to Computer 22

5.3 Assignment Operators 5.4 Logical Operators


Assume variable c holds True and variable d holds False, then:
Beside straight assignment (=), you can also use:
Operator Example Explanation Operator Example Result
= c=a+b and c and c True
+= c += a c=c+a c and d False
-= c -= a c=c-a or a or b True
*= c *= a c=c*a not not(a or b) False
Truth Table
/= c /= a c=c/a P Q P and Q P or Q P Not P
%= c %= a c=c%a True True True True True False
True False False True False True
**= c **= a c = c ** a
False True False True
//= c //= a c = c // a False False False False

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

Translating Mathematical Expression into Python Example: Operators Precedence #1


You might be familiar with a certain style of writing an Find the result of c * d – x / y, with the following assignments
expression, but it might not be understood by Python, and you x = 16
need to convert them. y=4
c = 2.5
Examples: d = 0.25
Mathematical Expression Python Expression Solution
c*d–x/y
xy - 5z x*y–9*z 2.5 * 0.25 – 16 / 4 # assignment
0.625 – 16 / 4 # perform *
x2 + 4y + 5 x**2 + 4 * y + 5 0.625 - 4 # perform /
-3.375 # perform –
8y2 - 8z 8 * y**2 - 8 * z The answer is -3.375

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

Some Useful Functions in Python Some Useful Functions in Python (cont.)


int(A)  Note: you can have nested function call (one function
Convert argument (Value of variable A, in this case) into integer inside another). The innermost function will be called first,
Also need a variable to assign the integer to and the result will be argument for the one right outside it
Try A = int(3.142)  What is the value of A?  For example: A = int(input(“Enter a number”))
float(A) input(“Enter a number”) will be called first, prompting the user
Similar to int(), but will convert the argument into floating point to enter the number
number instead The result of input(), which is a string, will then be converted

into an integer by int(), and then assigned to variable A

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

6.2 input() 6.2 input() (cont.)


input() function will prompt user (with the message inside the Since the input will be string (text), it cannot be used in calculation
parentheses) to enter data. User will type out data, then press enter. right away
Received input will be of string type, and we need a variable to hold We will need to convert the input into appropriate type first (int or
the data (function return) float)
Example: Example:
str = input("Enter your input: ") inp1 = input("Input integer number : ") # prompt user for input
print ("Received input is : ", str) # store the result on inp1
Result (user input in blue): no1 = int(inp1) # convert result in inp1 to int
# store it on no1
Enter your input: Hello Python inp2 = input("Input float number : ") # get next user input into inp2
Received input is : Hello Python no2 = float(inp2) # convert to float, store on no2
From the example, “Hello Python” will be stored in variable str

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

7.1 Coding Example #01 7.2 Coding Example #02


Finding rectangle’s area Swap the values of two variables
START “Take two already-assigned variables, A and B. Swap the
values between them, then print the result”
input WIDTH

input HEIGHT

AREA = WIDTH × 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

And we have A = 7 and B = 5!

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

Example #03 – Complete Codes

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

You might also like