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

Python_Lecture_2(Variables & Exprission)

Uploaded by

egilhani981
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)
3 views

Python_Lecture_2(Variables & Exprission)

Uploaded by

egilhani981
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
You are on page 1/ 41

PYTHON PROGRAMMING

VARIABLES AND EXPRESSION


Unit 2: VARIABLES, EXPRESSION

Python Programming : Lecture Two


Dr. Khalil Alawdi 2

Outline of This Lecture


• 2.0 Objectives

• 2.1 Introduction

• 2.2 Values and Types

• 2.2.1 Variables

• 2.2.2 Variable Names and Keywords

• 2.3 Type conversion

• 2.3.1 Implicit Type Conversion

• 2.3.2 Explicit Type Conversion

• 2.4 Operators and Operands

• 2.5 Expressions

• 2.6 Interactive Mode and Script Mode

• 2.7 Order of Operations

• 2.8 Summary

• 2.9 References

• 2.10 Unit End Exercise

Python Programming : Lecture Two


Dr. Khalil Alawdi 3

Lecture Objectives
After reading through this chapter, you will be able to :

• To understand and use the basic datatypes of python.

• To understand the type conversion of variables in python programming.

• To understand the operators and operands in python.

• To understand the interactive mode and script mode in python.

• To understand the order of operations in python.

Python Programming : Lecture Two


Dr. Khalil Alawdi 4

INTRODUCTION
• Variables in a computer program are not quite like mathematical variables. They are placeholders for

locations in memory.

• Memory values consists of a sequence of binary digits (bits) that can be 0 or 1, so all numbers are

represented internally in base 2.

• Names of variables are chosen by the programmer.

• Python is case sensitive, so myVariable is not the same as Myvariable which in turn is not the same

as MyVariable.

• With some exceptions, however, the programmer should avoid assigning names that differ only by

case since human readers can overlook such differences.

Python Programming : Lecture Two


Dr. Khalil Alawdi 5

VALUES AND TYPES


• A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1,

2, and 'Hello, World!'.

• These values belong to different types: 2 is an integer, and 'Hello, World!' is a string, so-called because it contains a

“string” of letters. You can identify strings because they are enclosed in quotation marks.

• If you are not sure what type a value has, the interpreter can tell you.

• >>>type ('Hello, World!') <type ‘str’>

• >>> type (17) <type ‘int’>

• Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a

decimal point belong to a type called float, because these numbers are represented in a format called floating-point.

• >>> type (3.2) <type ‘float’>

• What about values like '17' and '3.2'? They look like numbers, but they are in quotation marks like strings.

• >>> type (‘17’) <type ‘str’>

• >>> type (‘3.2’) <type ‘str’> They are strings.


Python Programming : Lecture Two
Dr. Khalil Alawdi 6

VALUES AND TYPES


• Variables:
• One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value.

• An assignment statement creates new variables and gives them values:


• >>> message = ‘Welcome to University of Knowledge’
• >>> n = 17
• >>> pi = 3.1415926535897932

• The above example makes three assignments. The first assigns a string to a new variable
named message, the second gives the integer 17 to n, the third assigns the (approximate)
value of π to pi.

• A common way to represent variables on paper is to write the name with an arrow pointing to
the variable’s value. >>> type(message) >>> type(n) >>> type(pi)
Python Programming : Lecture Two
Dr. Khalil Alawdi 7

VALUES AND TYPES


• Variable Names and Keywords:
• Programmers generally choose names for their variables that are meaningful they document
what the variable is used for.

• Variable names can be arbitrarily long. They can contain both letters and numbers, but they
have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin
variable names with a lowercase letter.

• The underscore character, _, can appear in a name. It is often used in names with multiple
words, such as my_name or airspeed_of_unladen_swallow.

• If you give a variable an illegal name, you get a syntax error: >>> 76mumbai= 'big city' Syntax
Error: invalid syntax
• >>> more@ = 1000000 Syntax Error: invalid syntax
• >>> class = 'Advanced python' Syntax Error: invalid syntax
Python Programming : Lecture Two
Dr. Khalil Alawdi 8

VALUES AND TYPES


• Variable Names and Keywords:
• 76mumbai is illegal because it does not begin with a letter. more@ is illegal because it
contains an illegal character, @. But what’s wrong with class?

• It turns out that class is one of Python’s keywords. The interpreter uses keywords to
recognize the structure of the program, and they cannot be used as variable names.

• Python has a lot of keywords. The number keeps on growing with the new features coming in
python.

• Python 3.7.3 is the current version as of writing this book. There are 35 keywords in Python
3.7.3 release.

• We can get the complete list of keywords using python interpreter help utility.
• $ python3.7
• >>> help () help> keywords
Python Programming : Lecture Two
Dr. Khalil Alawdi 9

VALUES AND TYPES


• Variable Names and Keywords:

• Here is a list of the Python keywords. Enter any keyword to get more help.

Python Programming : Lecture Two


Dr. Khalil Alawdi 10

TYPE CONVERSION
• The process of converting the value of one data type
(integer, string, float, etc.) to another data type is called
type conversion.

• Python has two types of type conversion.


• Implicit Type Conversion
• Explicit Type Conversion

Python Programming : Lecture Two


Dr. Khalil Alawdi 11

TYPE CONVERSION
• Implicit Type Conversion
• In Implicit type conversion, Python automatically converts one
data type to another data type. This process doesn't need any
user involvement.

• example where Python promotes the conversion of the lower


data type (integer) to the higher data type (float) to avoid data
loss.

Python Programming : Lecture Two


Dr. Khalil Alawdi 12

TYPE CONVERSION
• Implicit Type Conversion
• Example 1:
• Converting integer to float
• num_int = 123
• num_flo = 1.23
• num_new = num_int + num_flo
• print ("datatype of num_int:”, type(num_int))
• print ("datatype of num_flo:”, type(num_flo))
• print ("Value of num_new:”, num_new)
• print ("datatype of num_new:”, type(num_new))
• When we run the above program, the output will be:
• datatype of num_int: <class int>
• datatype of num_flo: <class ‘float’>
• Value of num_new: 124.23

• datatype of num_new: <class ‘float’>


Python Programming : Lecture Two
Dr. Khalil Alawdi 13

TYPE CONVERSION
• Implicit Type Conversion
• Example 1:
• In the above program, we add two variables num_int and num_flo, storing
the value in num_new.
• We will look at the data type of all three objects respectively.
• In the output, we can see the data type of num_int is an integer while the
data type of num_flo is a float.
• Also, we can see the num_new has a float data type because Python
always converts smaller data types to larger data types to avoid the loss
of data.
Python Programming : Lecture Two
Dr. Khalil Alawdi 14

TYPE CONVERSION
• Implicit Type Conversion
• Example 2:

• Addition of string(higher) data type and integer(lower) data type


• num_int = 123

• num_str = “456”

• print (“Data type of num_int:”, type(num_int))

• print (“Data type of num_str:”, type(num_str))

• print(num_int+num_str)

Python Programming : Lecture Two


Dr. Khalil Alawdi 15

TYPE CONVERSION
• Implicit Type Conversion
• Example 2:
• When we run the above program, the output will be:
• Data type of num_int: <class ‘int’>
• Data type of num_str: <class ‘str’>
• Trace back (most recent call last):
• File "python", line 7, in <Module>
• Type Error: unsupported operand type(s) for +: 'int' and 'str'
• In the above program, we add two variables num_int and num_str.
• As we can see from the output, we got Type Error. Python is not able to use Implicit Conversion in
such conditions.
• However, Python has a solution for these types of situations which is known as Explicit
Conversion.

Python Programming : Lecture Two


Dr. Khalil Alawdi 16

TYPE CONVERSION
• Explicit Type Conversion
• In Explicit Type Conversion, users convert the data type of an object to required

data type. We use the predefined functions like int(), float(), str(), etc to perform
explicit type conversion.

• This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.

• Syntax:

• <required_datatype> (expression)

• Typecasting can be done by assigning the required data type function to the expression

Python Programming : Lecture Two


Dr. Khalil Alawdi 17

TYPE CONVERSION
• Explicit Type Conversion
• Example 1
• Addition of string and integer using explicit conversion.
• num_int = 123
• num_str = "456"
• print (“Data type of num_int:”, type(num_int))
• print (“Data type of num_str before Type Casting:”, type(num_str)) num_str = int(num_str)
• print (“Data type of num_str after Type Casting:”, type(num_str))
• num_sum = num_int + num_str
• print (“Sum of num_int and num_str:”, num_sum)
• print (“Data type of the sum:”, type(num_sum))

Python Programming : Lecture Two


Dr. Khalil Alawdi 18

TYPE CONVERSION
• Explicit Type Conversion
• Example 1
• When we run the above program, the output will be:
• Data type of num_int: <calss ‘int’>
• Data type of num_str before Type Casting: <class ‘str’>
• Data type of num_str after Type Casting: <class ‘int’>
• Sum of num_int and num_str: 579
• Data type of the sum: <class ‘int’>
• In the above program, we add num_str and num_int variable.
• We converted num_str from string(higher) to integer(lower) type using int() function to perform the addition.
• After converting num_str to an integer value, Python is able to add these two variables.
• We got the num_sum value and data type to be an integer.

Python Programming : Lecture Two


Dr. Khalil Alawdi 19

OPERATORS AND OPERANDS


• Operators are particular symbols which operate on some values and produce an output.

• The values are known as Operands.

• Example: 4 + 5 = 9 Here 4 and 5 are Operands and (+), (=) signs are the operators.

• They produce the output 9

• Python supports the following operators:

• Arithmetic Operators.

• Relational Operators.

• Logical Operators.

• Membership Operators.

• Identity Operators

Python Programming : Lecture Two


Dr. Khalil Alawdi 20

OPERATORS AND OPERANDS


• Arithmetic Operators

Python Programming : Lecture Two


print(round(22/3,3)) Dr. Khalil Alawdi 21

OPERATORS AND OPERANDS


• Arithmetic Operators Examples

• >>> 10+20 30
• >>> 20-10 10
• >>> 10*2 20
• >>> 10/2 5 print(round(22/3,3))
• >>> 10%3 1
• >>> 2**3 8
• >>> 10//3 3

Python Programming : Lecture Two


Dr. Khalil Alawdi 22

OPERATORS AND OPERANDS


• Relational Operators

Python Programming : Lecture Two


Dr. Khalil Alawdi 23

OPERATORS AND OPERANDS


• Relational Operators Examples

• >>> 10 < 20 False

• >> 10>20 False

• >>> 10<=10 True

• >>> 20>=15 True

• >>> 5==6 False

• >>>5!=6 True

Python Programming : Lecture Two


Dr. Khalil Alawdi 24

OPERATORS AND OPERANDS


• Logical Operators

Python Programming : Lecture Two


Dr. Khalil Alawdi 25

OPERATORS AND OPERANDS


• Logical Operators Examples

• a=5>4 and 3>2 print(a) True

• b=5<4 or 3>4) print(b) False

Python Programming : Lecture Two


Dr. Khalil Alawdi 26

OPERATORS AND OPERANDS


• Membership Operators

Python Programming : Lecture Two


Dr. Khalil Alawdi 27

OPERATORS AND OPERANDS


• Membership Operators Examples
• a=10

• b=20

• list= [10,20,30,40,50]

• if (a in list):
• print (“a is in given list”)
• else:
• print (“a is not in given list”)
• if (b not in list):
• print (“b is not given in list”)
• else:
• print (“b is given in list”)

• Output:
• >>>
• a is in given list
• b is given in list

Python Programming : Lecture Two


Dr. Khalil Alawdi 28

OPERATORS AND OPERANDS


• Identity operators

Python Programming : Lecture Two


Dr. Khalil Alawdi 29

OPERATORS AND OPERANDS


• Identity operators Examples
• a=20

• b=20
• if (a is b):
• print (“a, b has same identity”)
• else:
• print (“a, b is different”)
• b=10
• if (a is not b):

• print (“a, b has different identity”)


• else:
• print (“a, b has same identity”)
• >>>

• a, b has same identity


• a, b has different identity

Python Programming : Lecture Two


Dr. Khalil Alawdi 30

EXPRESSIONS
• An expression is a combination of values, variables, and operators.

• A value all by itself is considered an expression, and so is a variable, so the following are all

legal expressions (assuming that the variable x has been assigned a value):
• 17
• x
• x + 17

• A statement is a unit of code that the Python interpreter can execute. We have seen two kinds
of statement: print and assignment.

• Technically an expression is also a statement, but it is probably simpler to think of them as


different things. The important difference is that an expression has a value; a statement does
not.
Python Programming : Lecture Two
Dr. Khalil Alawdi 31

INTERACTIVE MODE AND SCRIPT MODE


• One of the benefits of working with an interpreted language is that

you can test bits of code in interactive mode before you put them in
a script. But there are differences between interactive mode and
script mode that can be confusing.

• For example, if you are using Python as a calculator, you might type

• >>> miles = 26.2

• >>> miles * 1.61 42.182

Python Programming : Lecture Two


Dr. Khalil Alawdi 32

INTERACTIVE MODE AND SCRIPT MODE


• The first line assigns a value to miles, but it has no visible effect.
The second line is an expression, so the interpreter evaluates it and
displays the result. So we learn that a marathon is about 42
kilometers.

• But if you type the same code into a script and run it, you get no
output at all.

• In script mode an expression, all by itself, has no visible effect.


Python actually evaluates the expression, but it doesn’t display the
value unless you tell it to: miles = 26.2 print (miles * 1.61) This
behavior can be confusing at first.
Python Programming : Lecture Two
Dr. Khalil Alawdi 33

INTERACTIVE MODE AND SCRIPT MODE


• A script usually contains a sequence of statements. If there is more

than one statement, the results appear one at a time as the


statements execute.

• For example
• print 1
•x=2
• print x produces the output 1 2

• The assignment statement produces no output.

Python Programming : Lecture Two


Dr. Khalil Alawdi 34

ORDER OF OPERATIONS
• When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence. For mathematical operators, Python follows
mathematical convention. The acronym PEMDAS is a useful way to remember the
rules:
• Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first,
• 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an
expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3,
not 27.

Python Programming : Lecture Two


Dr. Khalil Alawdi 35

ORDER OF OPERATIONS
• Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).
So, in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi.
To divide by 2π, you can use parentheses or write degrees / 2 / pi.
• Example for Operator Precedence
• >>> 200/200+(100+100) 201.0
• >>>
• >>> a=10
• >>> b=20
• >>> c=15
• >>> (a+b)*(c+b)-150 900
• >>> (a+b)*c+b-150 320 >>> a+b**2 410
Python Programming : Lecture Two
Dr. Khalil Alawdi 36

ORDER OF OPERATIONS
• >>> a or b + 20 10
• >>> c or a + 20 15
• >>> c and a + 20 30
• >>> a and b + 20 40
• >>> a>b>c False

Python Programming : Lecture Two


Dr. Khalil Alawdi 37

SUMMARY
• In this chapter we studied how to declare variables, expression and types of
variables in python.
• We are more focuses on type conversion of variables in this chapter basically
two types of conversion are implicit type conversion and explicit type
conversion.
• Also studied types of operators available in python like arithmetic, logical,
relational and membership operators.
• Focuses on interactive mode and script mode in python and order of
operations.
Python Programming : Lecture Two
Dr. Khalil Alawdi 38

UNIT END EXERCISE


• Assume that we execute the following assignment statements:
• width = 17
• height = 12.0
• delimiter = '.'
• For each of the following expressions, write the value of the
expression and the type (of the value of the expression).
• 1. width/2
• 2. width/2.0
• 3. height/3
• 4. 1 + 2 * 5
• 5. delimiter * 5

Python Programming : Lecture Two


Dr. Khalil Alawdi 39

UNIT END EXERCISE


• Assume that we execute the following assignment statements:
• width = 17
• height = 12.0
• delimiter = '.'
• For each of the following expressions, write the value of the expression and
the type (of the value of the expression).
• 1. width/2
• 2. width/2.0
• 3. height/3
• 4. 1 + 2 * 5
• 5. delimiter * 5
• Use the Python interpreter to check your answers

Python Programming : Lecture Two


Dr. Khalil Alawdi 40

UNIT END EXERCISE


• Type the following statements in the Python interpreter to see what
they do:
•5
•x=5
•x+1
• Now put the same statements into a script and run it. What is the output?
Modify the script by transforming each expression into a print statement and
then run it again.
• Write a program add two numbers provided by the user.
• Write a program to find the square of number.
• Write a program that takes three numbers and prints their sum. Every
number is given on a separate line.
Python Programming : Lecture Two
Dr. Khalil Alawdi 41

REFERENCES
• Think Python by Allen Downey 1st edition.

• Python Programming for Beginners By Prof. Rahul E. Borate, Dr. Sunil Khilari,

Prof. Rahul S. Navale.

• https://learning.rc.virginia.edu/

• www.programiz.com

• www.itvoyagers.in

Python Programming : Lecture Two

You might also like