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

Lecture 2

Uploaded by

G Abbas
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 2

Uploaded by

G Abbas
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

CS110: Fundamentals of Computer

Programming

Course instructor
Ayesha Kanwal
Variables, Expressions, and Data Types
Recap
• A computer is a universal information-processing machine, which
can carry out any process that can be described in sufficient
detail.

• The process of creating software is called programming

• A basic functional view of a computer system comprises a central


processing unit (CPU), a main memory, a secondary memory,
and input and output devices

• Programs are written using a formal notation known as


a
programming language

• There are many different languages, but all share the property of
having a precise syntax (form) and semantics (meaning)

• Computer hardware only understands a very low-level language


known as machine language
Recap

• Programs are usually written using human-oriented


high- level languages such as Python

• A high-level language must either be compiled


or
interpreted in order for the computer to understand it

• Python is an interpreted language

• One way to learn about Python is to use an


interactive shell for experimentation…………. IDE
Outline

• Types of Errors
• Basic Elements of Python Programs
• variables
• Literals
• Assignments
• Data-types
• Identifiers and Expressions
• Writing Simple Python Commands

5
Types of errors
• There are mainly three kinds of distinguishable errors in Python: syntax
errors, exceptions (run time error) and logical errors

• Syntax error: Syntax errors are similar to grammar or spelling errors in a


Language. If there is such an error in your code, Python cannot start to execute
your code. You get a clear error message stating what is wrong and what needs to
be fixed. Therefore, it is the easiest error type you can fix.

• Missing symbols (such as comma, bracket, colon), misspelling a keyword, having


incorrect indentation are common syntax errors in Python.

6
Types of errors
• exceptions (run time error) Exceptions may occur in syntactically correct code
blocks at run time.
• Trying to read from a file which does not exist
• dividing a number by zero

• Logical errors:
• If you have logical errors, your code does not run as you expected

7
Elements Of A
Program
The Difference Between Brackets,
Braces, and
Parentheses
• ( ) Parentheses
•[ ] Brackets
•{ } Braces
Operators, Operands and expressions
• In Python, operators are special symbols that designate that some sort of
computation should be performed. The values that an operator acts on are called
operands.
• a = 10
• b= 10
• a+b
• In this case, the + operator adds the operands a and b together
• An expression is a combination of operators and operands that is interpreted to
produce some other value.

10
Simple
Expressions
• 1. 2300 +
20
• 2. 4800 /
12
• 3. 11 * 19
Values &
T ypes
• A value is one of the basic things a program works with.
• It can be a letter or a number.
• Example: Integer
• 14 String is a collection of alphabets,
• ‘Hello !! ’ String words or other characters.
• 13.235
Float
• Every value in Python has a type.
Values &
T ypes
• Printing Values:
• Syntax:

print (value)

Examples:
print (“Python is fun”) Python is fun
print (3.14) 3.14
Values &
Types
• Confirm the type from the interpreter:
• Syntax:
• type(value)
• Examples:
• >>> type (“Hello String”)
• >>> type (3.14)
• >>> type (130)
Values &
Types
• Self-Review Exercise:
Determine the type of the following value:

• >>> type (‘17.0’)

It’s a String….
Values &
Types
• When you have operands of two different types i.e. integer
and float result would automatically be converted to float.

• E.g.
• 2 + 4.0 = 6.0
• 15.0 / 3=???
Variable
s
• Variables are reserved memory locations to store values.

• Creating a variable means you reserve some space in memory.

• The equal sign (=) is used to assign values to variables.

• The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable.
Variable
s
Syntax:

Variable Value

• Example:
• name = “Moosa”
• miles= 25.6
Display the value of a
variable
Syntax(print value):
Print
(variable_name)

Syntax(To check variable type):


type(variable_name)
Updating Variable Augmented Assignment

Values
X = X + 1;
X 10 +

= 11
Variable names and
keywords
1. Choose meaningful names for variables.
2. They can contain both letters and numbers, but they cannot start with a
number.
3. It is legal to use uppercase letters, but it is a good idea to begin variable names
with a lowercase letter.
4. The underscore character (_) can appear in a variable name.
5. Variable names can start with an underscore character, but generally it should
be avoided.
6. For variables with an illegal name, interpreter gives a syntax error.
7. Keywords can not be used as variable name.
Self-Review
Exercise
56House = “This is the 56th house”

number1 = 268

amount$= 56.89

pass = 10
Variable names and
keywords
Keywords:
The words reserved by the
python language.
Litera
ls
• In the following example, the parameter values passed to the print
function are all technically called literals
• More precisely, “Hello” and “Programming is fun!” are called textual literals,
while 3 and 2.3 are called numeric literals
>>> print("Hello")
Hello
>>> print("Programming is fun!")
Programming is fun!
>>> print(3)
3
>>> print(2.3)
2.3
Simple Assignment
Statements
• A literal is used to indicate a specific value, which can be assigned to
a variable
>>> x = 2
 x is a variable and 2 is its value
>>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment
Statements
• A literal is used to indicate a specific value, which can be assigned to
a variable
>>> x = 2
 x is a variable and 2 is its value
>>> print(x)
2
 x can be assigned different values;
>>> x = 2.3
hence, it is called a variable >>> print(x)
2.3
Simple Assignment Statements:
Box View
• A simple way to view the effect of an assignment is to assume that
when a variable changes, its old value is replaced

>>> x = 2 x = 2.3
Before After
>>> print(x)
2 x 2 x 2.3
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements:
Actual View
• In Python, values may end up anywhere in memory, and variables are used to
refer to them

x = 2.3
>>> x = 2
Before After
>>> print(x) What will
2 2 happen to
x 2 x
>>> x = 2.3 value 2?
>>> print(x)
2.3
2.3
Garbage
Collection
• Interestingly, as a Python programmer you do not have to worry about
computer memory getting filled up with old values when new values
are assigned to variables
After
Memory location
• Python will automatically clear old
values out of memory in a x 2 X will be automatically
reclaimed by the
process known as garbage garbage collector
collection
2.3
Assigning
Input
• So far, we have been using values specified by programmers and printed
or assigned to variables
• How can we let users (not programmers) input values?

• In Python, input is accomplished via an assignment statement


combined with a built-in function called input
<variable> = input(<prompt>)
• When Python encounters a call to input, it prints <prompt> (which is a
string literal) then pauses and waits for the user to type some text and
press the <Enter> key
Assigning
Input
• Here is a sample interaction with the Python interpreter:

>>> name = input("Enter your name: ")


Enter your name: shah
>>> name
‘shah'
>>>

• Notice that whatever the user types is then stored as a string


• What happens if the user inputs a number?
Assigning
Input
• Here is a sample interaction with the Python interpreter:

>>> number = input("Enter an expression: ")


Enter a number: 3+1
>>> number
Still a string! '3+1'
>>>

• How can we force an input number to be stored as a number and not as


a string?
• We can use the built-in eval function, which can be “wrapped around” the
input function
Assigning
Input
• Here is a sample interaction with the Python interpreter:

>>> number = eval(input("Enter a


number: "))
Enter a number: 3+1
>>> number
Now an int
4
(will execute the
>>>
Exp)!
Assigning
Input
• Here is a sample interaction with the Python interpreter:

>>> number = eval(input("Enter a


number: "))
Enter a number: 3.7+1
>>> number
And now a float
4.7
(answer)!
>>>
Assigning
Input
• Here is another sample interaction with the Python interpreter:

>>> number = eval(input("Enter an equation: "))


Enter an equation: 3 + 2
>>> number
5
>>>

The eval function will evaluate this formula and


return a value, which is then assigned to the variable “number”
Datatype
Conversion
• Besides, we can convert the string output of the input function into an
integer or a float using the built-in int and float functions
>>> number = int(input("Enter a number: "))
Enter a number: 3
>>> number
An integer
3
(no single
>>>
quotes)!
Datatype
Conversion
• Besides, we can convert the string output of the input function into an
integer or a float using the built-in int and float functions
>>> number = float(input("Enter a number: "))
Enter a number: 3.7
>>> number
A float
3.7
(no single
>>>
quotes)!
Datatype
Conversion
• As a matter of fact, we can do various kinds of conversions between
strings, integers and floats using the built-in int, float, and str functions
>>> x = 10 >>> y = "20" >>> z = 30.0
>>> float(x) >>> float(y) >>> int(z)
10.0 20.0 30
>>> str(x) >>> int(y) >>> str(z)
'10' 20 '30.0'
>>> >>> >>>

integer  float string  float float  integer


integer  string string  integer float  string
Simultaneous
Assignment
• Python allows us also to assign multiple values to multiple variables all
at the same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
>>>
Simultaneous
Assignment
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)

>>> x = 2
>>> y = 3
>>> x = y
>>> y = x
>>> x X CANNOT be done with
two simple assignments
3
>>> y
3
Simultaneous
Assignment
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)
>>> x = 2
Thus far, we have been using >>> y = 3
different names for >>> temp = x CAN be done with
variables. These names three simple assignments,

>>> x = y
are technically called >>> y = temp but more efficiently with
identifiers >>> x simultaneous assignment
3
>>> y
2
>>>
Identifier
s
• Python has some rules about how identifiers can be formed
• Every identifier must begin with a letter or underscore, which may be
followed by any sequence of letters, digits, or underscores
>>> x1 = 10
>>> x2 = 20
>>> y_effect = 1.5
>>> celsius = 32
>>> 2celsius
File "<stdin>", line 1
2celsius
^
SyntaxError: invalid
syntax
Identifier
s
• Python has some rules about how identifiers can be formed
• Identifiers are case-sensitive

>>> x = 10
>>> X = 5.7
>>> print(x)
10
>>> print(X)
5.7
Identifier
s
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Python Keywords
Identifier
s
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers

>>> for = 4
File "<stdin>", line 1
An example… for = 4
^
SyntaxError: invalid
syntax
Expressio
ns
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
 This is an expression that uses the
>>> print(x)
addition operator 5
>>> print(5 * 7)
35
>>> print("5" + "7")
57
Expressio
ns
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
 This is an expression that uses the
>>> print(x)
addition operator 5
>>> print(5 * 7)
 This is another expression that uses the
35
multiplication operator >>> print("5" + "7")
57
Expressio
ns
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
 This is an expression that uses the
>>> print(x)
addition operator 5
>>> print(5 * 7)
 This is another expression that uses the
35
multiplication operator >>> print("5" + "7")
57
 This is yet another expression that uses the
addition operator but to concatenate (or glue)
strings together
Expressio
ns
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 6 >>> print(x*y)
>>> y = 2 12
>>> print(x - y) >>> print(x**y)
Another 4 Yet another 36
example >>> print(x/y) example… >>> print(x%y)
… 3.0 0
>>> print(x//y) >>> print(abs(-x))
3 6
Expressions: Summary of
Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Float Division
** Exponentiation
abs() Absolute Value
// Integer Division
% Remainder

Python Built-In Numeric Operations


Explicit and Implicit Data Type
Conversion
• Data conversion can happen in two ways in Python
1. Explicit Data Conversion (we saw this earlier with the int, float, and str
built-in functions)

2. Implicit Data Conversion


• Takes place automatically during run time between ONLY numeric values
• E.g., Adding a float and an integer will automatically result in a float value
• E.g., Adding a string and an integer (or a float) will result in an error since
string is not numeric
• Applies type promotion to avoid loss of information
• Conversion goes from integer to float (e.g., upon adding a float and an
integer) and not vice versa so as the fractional part of the float is not lost
Implicit Data Type Conversion:
Examples
 The result of an expression that involves >>> print(2 + 3.4)
5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
>>> print(9/5 * 27 + 32)
80.6
>>> print(9//5 * 27 + 32)
59
>>> print(5.9 + 4.2)
10.1
Implicit Data Type Conversion:
Examples
 The result of an expression that involves >>> print(2 + 3.4)
5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
 The result of an expression that involves >>> print(9/5 * 27 + 32)
80.6
values of the same data type will not result
>>> print(9//5 * 27 + 32)
in any conversion
59
>>> print(5.9 + 4.2)
10.1
>>>
• Key Points to Remember
• Type Conversion is the conversion of object from one data type to
another data type.
• Implicit Type Conversion is automatically performed by the Python
interpreter.
• Python avoids the loss of data in Implicit Type Conversion.
• Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
• In Type Casting, loss of data may occur as we enforce the object to a
specific data type.
Modul
es
• One problem with entering code interactively into a Python shell is
that the definitions are lost when we quit the shell
• If we want to use these definitions again, we have to type them all over
again!

• To this end, programs are usually created by typing definitions into a


separate file called a module or script
• This file is saved on disk so that it can be used over and over again

• A Python module file is just a text file with a .py extension, which can
be created using any program for editing text (e.g., notepad or vim)
Programming Environments
and IDLE
• A special type of software known as a programming environment
simplifies the process of creating modules/programs

• A programming environment helps programmers write programs and


includes features such as automatic indenting, color highlighting, and
interactive development

• The standard Python distribution includes a programming


environment called IDLE that you can use for working on the
programs of this course
Summa
ry
• Programs are composed of statements that are built from identifiers and
expressions

• Identifiers are names


• They begin with an underscore or letter which can be followed by a combination
of letter, digit, and/or underscore characters
• They are case sensitive

• Expressions are the fragments of a program that produce data


• They can be composed of literals, variables, and operators
Summa
ry
• A literal is a representation of a specific value (e.g., 3 is a literal
representing the number three)

• A variable is an identifier that stores a value, which can change (hence,


the name variable)

• Operators are used to form and combine expressions into more complex
expressions (e.g., the expression x + 3 * y combines two expressions
together using the + and * operators)
Summa
ry
• In Python, assignment of a value to a variable is done using the equal
sign (i.e., =)

• Using assignments, programs can get inputs from users and manipulate
them internally

• Python allows simultaneous assignments, which are useful for swapping


values of variables

• Datatype conversion involves converting implicitly and explicitly between


various datatypes, including integer, float, and string
Acknowledgeme
nt!

Lecture content by Dr. Dr. Ijaz Khan

60

You might also like