Topic #2
Input, Output, Expression
 A variable is a name that represents a value
stored in the computer memory.
 Location in memory where value can be
stored
3
 A variable name is any valid identifier that is not a
Python keyword.
 A variable name can not contain spaces.
 A first character must be characters or an
underscore ( _ ).
 Cannot begin with digit
 After first character, the digits 0 through 9 can be
used.
 Case sensitive. Uppercase and lower case are
distinct. This means the variable name ItemOrdered
is not the same as itemordered.
 Choosing meaningful identifiers helps make a
program self-documenting.
4
Variable Name Legal or Illegal
Units_per_day Legal
dayOfWeek Legal
3dGraphic Illegal. Variable name cannot
begins with digit
June1997 Legal
Mixture#3 Illegal. Variable name may only use
letters, digits, or underscore
5
 The variable name begins with lowercase
letters.
 The first character of the second and
subsequent words is written in Uppercase
◦ grossPay
◦ payRate
◦ averageOfNumbers
6
Assignment operator =
 Assigns value on right to variable on left.
Number1 = 45
Number2 = 72
Sum = Number1 + Number2
>>> print(Number1)
45
>>> print(Number2)
72
>>> print(Sum)
117
Note: Variable can not be used until it is assigned a value
7
8
 There are some words that are reserved by
Python for its own use. You can't name variable
with the same name as a keyword. To get a list of
all the keywords, issue the following command
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
9
 If you give the statement to python to
evaluate,
>>> x=6
It will associate the value of the expression on
the right hand side with the name x.
An assignment statement has the following
form:
variable_name = expression
10
 Python evaluates an assignment statement
using the following rules
◦ Evaluate the expression on the right hand side of
the statement. This will result in a value.
◦ Store the id in the variable.
 You can now reuse the variable
>>> x=9
>>>x*8
72
11
 As the name indicates, Python variables can be
readily changed. This means that you can
connect a different value with a previously
assigned variable very easily through simple
reassignment.
 Knowing that you can readily and easily reassign
a variable can also be useful in situations where
you may be working on a large program that was
begun by someone else and you are not clear yet
on what has already been defined.
 See related shell examples
12
 With Python, you can assign one single value
to several variables at the same time.
 This lets you initialize several variables at
once, which you can reassign later in the
program yourself, or through user input.
>>> x = y = z = 0
>>> j , k , l = ‘shark’ , 2.5 , 5
13
 Computers manipulate data values that represent
information and these values can be of different types.
 In fact, each value in a Python program is of a specific
type.
 The data type of a value determines how the data is
represented in the computer and what operations can be
performed on that data.
 A data type provided by the language itself is called a
primitive data type.
 Python supports quite a few data types: numbers, text
strings, files, containers, and many others.
 Programmers can also define their own user-defined
data types, which we will cover in detail later.
15
16
 Expressions are representation in text of
some form of computation.
 Expressions are distinguished by the fact that
when you evaluate (perform the represented
computation) you end up with a resultant
value.
>>> 5
5
>>> 5+6
11
17
 An expression that represents the resultant
internal value that it generates inside the
interpreter. 10 is a primitive expression 10 +
10 is not.
 Numerical Data Types -- int, float, complex
◦ See Shell for examples
 Strings
◦ "your name“
18
 Arithmetic
◦ +, -, *, /, //, %, **
 Relational
◦ >, >, >=, <=, ==, !=
 Logical
and, or, not
20
21
 The precedents of math operators from
highest to lowest is
◦ Exponentiation **
◦ Multiplication, Division, Remainder *, /, //, %,
◦ Addition and subtraction +, -
22
Expression Value
5 + 2 * 4
10 / 2 - 3
8 + 12 * 2 - 4
6 - 3 * 2 + 7 - 1
(6 - 3) * 2 + 7 - 1
10 / (5 - 3) * 2
(6 - 3) * (2 + 7) / 3
8 + 12 * (6 - 4)
23
24
25
 first include the statement
 from math import sqrt
26
27
28
Expression Value of the Expression
True and False False
False and True False
False and False False
True and True True
Expression Value of the Expression
True or False True
False or True True
False or False False
True or True True
Expression Value of the Expression
not True False
Not False True
29
 A Boolean expression is an expression that
evaluates to True or False
>>> 4 > 2
True
>>> 4 < 2
False
30
 True and False are not strings, they are
special values that belong to the type bool
>>> type(True)
<class 'bool'>
>>> type(4 < 2)
<class 'bool'>
31
 How do you explain this?
>>> False or 1
1
>>> True and 0
0
32
 To understand this behavior you need to
learn the following rule:
“The integer 0, the float 0.0, the empty string,
the None object, and other empty data
structures are considered False; everything else
is interpreted as True"
33
 When an expression contains And or Or,
Python evaluates from left to right
 It stops evaluating once the truth value of the
expression is known
◦ For x and y, if x is False, there is no reason to
evaluate y
◦ For x or y, if x is True, there is no reason to
evaluate y
 The value of the expression ends up being
the last condition actually evaluated by
Python
34
Try to evaluate the value of the following
expressions
◦ 0 and 3
◦ 3 and 0
◦ 3 and 5
◦ 1 or 0
◦ 0 or 1
◦ True or 1 / 0
35
In the following expression, which parts are
evaluated?
◦ (7 > 2) or ( (9 < 2) and (8 > 3) )
◦ A. Only the first condition
◦ B. Only the second condition
◦ C. Only the third condition
◦ D. The first and third conditions
◦ E. All of the code is evaluated
36
 What is the output of the following code?
a = 3
b = (a != 3)
print(b)
A. True
B. False
C. 3
D. Syntax error
37
 Consider the following expression:
(not a) or b
 Which of the following assignments makes
the expression False?
A. a = False; b = False
B. a = False; b = True
C. a = True; b = False
D. a = True; b = True
E. More than one of the above
38
 Consider the following expression:
a and (not b)
Which of the following assignments makes the
expression False?
A. a = False; b = False
B. a = False; b = True
C. a = True; b = False
D. a = True; b = True
E. More than one of the above
39
 What happens when we evaluate the
following?
>>> 1 or 1/0 and 1
When expressions involve Boolean and & or
operators, short circuiting is applied first and
then precedence is used.
What is the value of the following expression?
>>>1 or 1/0
40
 function is a collection of programming
instructions that carry out a particular task.
 For Example: Print function to display
information.
 There are many other functions available in
Python.
 Most functions return a value. That is, when the
function completes its task, it passes a value
back to the point where the function was called.
42
Function call expression
Function call expressions are of the form
function_name(arguments)
See Shell for examples
43
 Print function is a piece of prewritten code that
performs an operation. Python has numerous
built-in functions that perform various
operations.
Print(“Hello World”)
In interactive mode, type this statement and press
the Enter key, the message Hello world is
displayed.
Here is an example:
>>> print('Hello world')
Hello world
>>>
44
 Python also allows you to enclose string literals in triple
quotes (either """ or ' '). Triple-quoted strings can
contain both single quotes and double quotes as part of
the string.
45
>>> print("""One
Two
Three""")
One
Two
Three
>>> print("""One Two Three""")
One Two Three
46
 Comments are notes of explanation that
document lines or sections of a program.
Comments are part of the program, but the
Python interpreter ignores them. They are
intended for people who may be reading the
source code.
 In Python, comment begin with the # character.
When the Python interpreter sees a # character, it
ignores everything from that character to the end
of the line.
47
48
 Python built-in functions to read input from
the keyboard.
Variable = input(prompt)
x= input("Enter First Number : ")
name = input(“Whats is your Name : ")
49
>>> name = input(“ What is your Name : ")
What is your Name : Ahmed
>>> print(name)
Ahmed
50
 Input function always returns user input as a
string, even if the user enter numeric data.
 Use data conversion function.
51
52
>>> x= float(input("Enter First Number : "))
Enter First Number : 10
>>> y= float(input("Enter second Number : "))
Enter second Number : 3
>>> z= float(input("Enter Third Number : "))
Enter Third Number : 5
>>> print("The maximum value is : ", max(x,y,z))
The maximum value is : 10.0
53
 An expression that is formed by combining
multiple expressions together.
 For example 4 + len("abc") is a compound
expression formed from a primitive
expressions ('4') and a function call
expression (len("abc")) using the addition
operator.
 See shell for related examples
54
 Go over sections 2.1, 2.2 and 2.5 of the
Textbook.
55

TOPIC-2-Expression Variable Assignment Statement.pdf

  • 1.
  • 3.
     A variableis a name that represents a value stored in the computer memory.  Location in memory where value can be stored 3
  • 4.
     A variablename is any valid identifier that is not a Python keyword.  A variable name can not contain spaces.  A first character must be characters or an underscore ( _ ).  Cannot begin with digit  After first character, the digits 0 through 9 can be used.  Case sensitive. Uppercase and lower case are distinct. This means the variable name ItemOrdered is not the same as itemordered.  Choosing meaningful identifiers helps make a program self-documenting. 4
  • 5.
    Variable Name Legalor Illegal Units_per_day Legal dayOfWeek Legal 3dGraphic Illegal. Variable name cannot begins with digit June1997 Legal Mixture#3 Illegal. Variable name may only use letters, digits, or underscore 5
  • 6.
     The variablename begins with lowercase letters.  The first character of the second and subsequent words is written in Uppercase ◦ grossPay ◦ payRate ◦ averageOfNumbers 6
  • 7.
    Assignment operator = Assigns value on right to variable on left. Number1 = 45 Number2 = 72 Sum = Number1 + Number2 >>> print(Number1) 45 >>> print(Number2) 72 >>> print(Sum) 117 Note: Variable can not be used until it is assigned a value 7
  • 8.
  • 9.
     There aresome words that are reserved by Python for its own use. You can't name variable with the same name as a keyword. To get a list of all the keywords, issue the following command >>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] 9
  • 10.
     If yougive the statement to python to evaluate, >>> x=6 It will associate the value of the expression on the right hand side with the name x. An assignment statement has the following form: variable_name = expression 10
  • 11.
     Python evaluatesan assignment statement using the following rules ◦ Evaluate the expression on the right hand side of the statement. This will result in a value. ◦ Store the id in the variable.  You can now reuse the variable >>> x=9 >>>x*8 72 11
  • 12.
     As thename indicates, Python variables can be readily changed. This means that you can connect a different value with a previously assigned variable very easily through simple reassignment.  Knowing that you can readily and easily reassign a variable can also be useful in situations where you may be working on a large program that was begun by someone else and you are not clear yet on what has already been defined.  See related shell examples 12
  • 13.
     With Python,you can assign one single value to several variables at the same time.  This lets you initialize several variables at once, which you can reassign later in the program yourself, or through user input. >>> x = y = z = 0 >>> j , k , l = ‘shark’ , 2.5 , 5 13
  • 15.
     Computers manipulatedata values that represent information and these values can be of different types.  In fact, each value in a Python program is of a specific type.  The data type of a value determines how the data is represented in the computer and what operations can be performed on that data.  A data type provided by the language itself is called a primitive data type.  Python supports quite a few data types: numbers, text strings, files, containers, and many others.  Programmers can also define their own user-defined data types, which we will cover in detail later. 15
  • 16.
  • 17.
     Expressions arerepresentation in text of some form of computation.  Expressions are distinguished by the fact that when you evaluate (perform the represented computation) you end up with a resultant value. >>> 5 5 >>> 5+6 11 17
  • 18.
     An expressionthat represents the resultant internal value that it generates inside the interpreter. 10 is a primitive expression 10 + 10 is not.  Numerical Data Types -- int, float, complex ◦ See Shell for examples  Strings ◦ "your name“ 18
  • 20.
     Arithmetic ◦ +,-, *, /, //, %, **  Relational ◦ >, >, >=, <=, ==, !=  Logical and, or, not 20
  • 21.
  • 22.
     The precedentsof math operators from highest to lowest is ◦ Exponentiation ** ◦ Multiplication, Division, Remainder *, /, //, %, ◦ Addition and subtraction +, - 22
  • 23.
    Expression Value 5 +2 * 4 10 / 2 - 3 8 + 12 * 2 - 4 6 - 3 * 2 + 7 - 1 (6 - 3) * 2 + 7 - 1 10 / (5 - 3) * 2 (6 - 3) * (2 + 7) / 3 8 + 12 * (6 - 4) 23
  • 24.
  • 25.
  • 26.
     first includethe statement  from math import sqrt 26
  • 27.
  • 28.
  • 29.
    Expression Value ofthe Expression True and False False False and True False False and False False True and True True Expression Value of the Expression True or False True False or True True False or False False True or True True Expression Value of the Expression not True False Not False True 29
  • 30.
     A Booleanexpression is an expression that evaluates to True or False >>> 4 > 2 True >>> 4 < 2 False 30
  • 31.
     True andFalse are not strings, they are special values that belong to the type bool >>> type(True) <class 'bool'> >>> type(4 < 2) <class 'bool'> 31
  • 32.
     How doyou explain this? >>> False or 1 1 >>> True and 0 0 32
  • 33.
     To understandthis behavior you need to learn the following rule: “The integer 0, the float 0.0, the empty string, the None object, and other empty data structures are considered False; everything else is interpreted as True" 33
  • 34.
     When anexpression contains And or Or, Python evaluates from left to right  It stops evaluating once the truth value of the expression is known ◦ For x and y, if x is False, there is no reason to evaluate y ◦ For x or y, if x is True, there is no reason to evaluate y  The value of the expression ends up being the last condition actually evaluated by Python 34
  • 35.
    Try to evaluatethe value of the following expressions ◦ 0 and 3 ◦ 3 and 0 ◦ 3 and 5 ◦ 1 or 0 ◦ 0 or 1 ◦ True or 1 / 0 35
  • 36.
    In the followingexpression, which parts are evaluated? ◦ (7 > 2) or ( (9 < 2) and (8 > 3) ) ◦ A. Only the first condition ◦ B. Only the second condition ◦ C. Only the third condition ◦ D. The first and third conditions ◦ E. All of the code is evaluated 36
  • 37.
     What isthe output of the following code? a = 3 b = (a != 3) print(b) A. True B. False C. 3 D. Syntax error 37
  • 38.
     Consider thefollowing expression: (not a) or b  Which of the following assignments makes the expression False? A. a = False; b = False B. a = False; b = True C. a = True; b = False D. a = True; b = True E. More than one of the above 38
  • 39.
     Consider thefollowing expression: a and (not b) Which of the following assignments makes the expression False? A. a = False; b = False B. a = False; b = True C. a = True; b = False D. a = True; b = True E. More than one of the above 39
  • 40.
     What happenswhen we evaluate the following? >>> 1 or 1/0 and 1 When expressions involve Boolean and & or operators, short circuiting is applied first and then precedence is used. What is the value of the following expression? >>>1 or 1/0 40
  • 42.
     function isa collection of programming instructions that carry out a particular task.  For Example: Print function to display information.  There are many other functions available in Python.  Most functions return a value. That is, when the function completes its task, it passes a value back to the point where the function was called. 42
  • 43.
    Function call expression Functioncall expressions are of the form function_name(arguments) See Shell for examples 43
  • 44.
     Print functionis a piece of prewritten code that performs an operation. Python has numerous built-in functions that perform various operations. Print(“Hello World”) In interactive mode, type this statement and press the Enter key, the message Hello world is displayed. Here is an example: >>> print('Hello world') Hello world >>> 44
  • 45.
     Python alsoallows you to enclose string literals in triple quotes (either """ or ' '). Triple-quoted strings can contain both single quotes and double quotes as part of the string. 45
  • 46.
  • 47.
     Comments arenotes of explanation that document lines or sections of a program. Comments are part of the program, but the Python interpreter ignores them. They are intended for people who may be reading the source code.  In Python, comment begin with the # character. When the Python interpreter sees a # character, it ignores everything from that character to the end of the line. 47
  • 48.
  • 49.
     Python built-infunctions to read input from the keyboard. Variable = input(prompt) x= input("Enter First Number : ") name = input(“Whats is your Name : ") 49
  • 50.
    >>> name =input(“ What is your Name : ") What is your Name : Ahmed >>> print(name) Ahmed 50
  • 51.
     Input functionalways returns user input as a string, even if the user enter numeric data.  Use data conversion function. 51
  • 52.
  • 53.
    >>> x= float(input("EnterFirst Number : ")) Enter First Number : 10 >>> y= float(input("Enter second Number : ")) Enter second Number : 3 >>> z= float(input("Enter Third Number : ")) Enter Third Number : 5 >>> print("The maximum value is : ", max(x,y,z)) The maximum value is : 10.0 53
  • 54.
     An expressionthat is formed by combining multiple expressions together.  For example 4 + len("abc") is a compound expression formed from a primitive expressions ('4') and a function call expression (len("abc")) using the addition operator.  See shell for related examples 54
  • 55.
     Go oversections 2.1, 2.2 and 2.5 of the Textbook. 55