Variables, Keywords, Expressions,
Statements
Program
•Sequence of instructions that specify how to perform a computation.
•Basic instructions in almost every program:
–Input: Get data from keyboard, or file or some other device.
–Output: Display data on the screen or send data to a file or other device.
–Math: Perform basic mathematical operations like addition and multiplication.
–Conditional Execution: Check for certain conditions and execute the appropriate
sequence of statements.
–Repetition: Perform some action repeatedly , usually with some variation
Formal and Natural Languages
• Natural Languages are the languages that people speak, such as
English, Spanish, French. They were not designed by people; they
evolved naturally.
• Formal Languages are languages that are designed by people for
specific applications.
• Programming languages are formal languages that have been
designed to express computations.
• Parsing is a process to figure out what the structure of the sentence
is.
INTRODUCTION
NATURAL LANGUAGE PROGRAMMING LANGUAGE
ALPHABETS • CHARACTER SET
WORDS • IDENTIFIERS
•
• SENTENCES • EXPRESSION
• PARAGRAPHS • FUNCTIONS
• ESSAY/STORY • PROGRAMS
PROGRAMMING LANGUAGES
Compiled Languages Interpreted Languages Compiled + Interpreted
C, C++ , GO, RUST PYTHON, RUBY, JAVASCRIPT JAVA, C#
Syntax vs. semantic
PROGRAMMING LANGUAGE
NATURAL LANGUAGE
Syntax:
Syntax:
• The rules for how an instruction is written.
• The rules for how a sentence is
constructed.
Cat eat the rat. • Area_of_circle = Pi * r*r
Semantics : Semantics:
• The actual meaning of statements. The effect the instructions have.
• Rat eat the cat. Area_of_circle = Pi * r*2
Debugging
• Programming errors are called bugs.
• Process of tracking bugs and correct them is called debugging.
Types of Errors
• Syntax Errors/compile-time errors :
– When rules of a programming language are violated.
– invalid code that the compiler doesn't understand.
– When the proper syntax of the language is not followed then a syntax
error is thrown.
– Python interprets (executes) each instruction in the program line by
line. The moment the interpreter encounters a syntactic error. It stops
further execution of the program.
• Run Time Errors (Exceptions)- occurs when the program is being
run/executed. It occurs when illegal operations are performed.
– Dividing a number by zero
– Lack of free memory space
– Finding square or logarithmic of negative numbers
– May terminate program execution, so code must be written in such a
way that it handles all sorts of unexpected errors rather than
terminating it unexpectedly.
• Semantic/Logical Errors : valid code the compiler understands.
– Which may comply with the rules of the programming language but gives an
unexpected and undesirable output.
– Not detected by the compiler
– Occur due to incorrect statements
– Programmer must check their code line to line.
• Examples
1. Aim- average …..doing- sum
2. Aim +…..doing -
It returns a syntax error message because after the if
statement a colon: is missing. We can fix this by writing
the correct syntax.
Practice question 2 a) To be able to easily switch to a different
programming language
b) So that we know which part is the subject
and which one is the predicate
c) To allow us to clearly express what we want
the computer to do
d) To understand why our computer crashes
C
Is python case sensitive language?
• Yes
• No
Variables, Expressions and Statements
• Value is one of the fundamental things, that a program manipulates.
• Variable is a name that refers to a value that maybe changed in the
program.
• The assignment statement creates new variables and gives them
values:
• >>> message = "What's up, Doc?"
• >>> n = 17
• >>> pi = 3.1415
Identifier
•What it is: An identifier is just a name you give to something in your code.
•Examples: Names for variables, functions, or anything else you define.
•How to create one: It must start with a letter or an underscore, and it can
have letters, numbers, or underscores after that. No spaces or special
symbols!
Variable
•What it is: A variable is a container that holds data. You can change what's
inside this container.
•How to use: You give a variable a name (an identifier) and assign it a value.
Example:
x=5
Here, x is the identifier (name), and it holds the value 5.
• Simple Example
• Think of identifiers as labels you stick on things, like sticky notes. A
variable is like a box that you put stuff into, and you label the box
with an identifier.
• For example, if you have a box labeled "cookies," "cookies" is the
identifier, and the cookies inside are the variable's value. You can take
cookies out and put different cookies in the box, but the label stays
the same.
Variable
• Variable names must be meaningful.
• It contains both numbers and letters, but they have to begin with a letter.
• Case sensitive.
• The underscore (_) character can appear in a name.
• Eg.
– >>>76trombones = "big parade“ >>> more$ = 1000000
– SyntaxError: invalid syntax SyntaxError: invalid syntax
– >>> class = "Computer Science 101“
– SyntaxError: invalid syntax
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
What is this bit of
code doing?
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)
What are these bits
of code doing?
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)
hours = 35.0
What are these bits rate = 12.50
of code doing? pay = hours * rate
print(pay)
Keywords/Reserved words
Keywords/Reserved words
• Keywords define the language’s rules and structure and they can’t be
used as variable names.
• Python in its language defines an inbuilt module “keyword” which
handles certain operations related to keywords. A function
“iskeyword()” checks if a string is keyword or not. Returns true if a
string is keyword, else returns false.
• Python has 35 keywords:
Statements
• A statement is an instruction that the Python interpreter can execute.
• When you type a statement on the command line, Python executes it
and displays the result, if there is one.
• 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.
Evaluating Expressions
• An expression is a combination of values, variables, and operators.
• If you type an expression on the command line, the interpreter
evaluates it and displays the result:
– >>> 1 + 1
– 2
• A value all by itself is considered an expression, and so is a variable.
>>> 17 >>> x
17 2
Sentences or Lines
x = 2 Assignment statement
x = x + 2 Assignment with expression
print(x) Print statement
Variable Operator Constant Function
Assignment Statements
• We assign a value to a variable using the assignment statement (=)
• An assignment statement consists of an expression on the
right-hand side and a variable to store the result
x = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6)
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
The right side is an expression.
0.936
Once the expression is evaluated, the
result is placed in (assigned to) x.
A variable is a memory location used to
store a value. The value stored in a x 0.6 0.936
variable can be updated by replacing the
old value (0.6) with a new value (0.936).
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
The right side is an expression. Once the
expression is evaluated, the result is
placed in (assigned to) the variable on the
0.936
left side (i.e., x).
Simultaneous Assignments
Python also supports simultaneous assignments like this:
var1,var2…………..,varn=exp1,exp2…………….,expn
>>> a,b,c=4,5,6
>>> a
4
>>> b
5
>>> c
6
Write code to swap two numbers
Write code to swap two numbers
>>>X=1
>>>Y=3
>>>Temp=X
>>>X=Y
>>>Y=Temp
Write code to swap two numbers
>>>X=1
>>>Y=3
>>>X,Y=Y,X
What is the maximum possible value of an integer in Python ?
In Python, value of an integer is not restricted by the number of bits
and can expand to the limit of the available memory.
>>> x=10000000000000000000000000000
>>> x
10000000000000000000000000000
As a side note, in Python 3, there is only one type “int” for all type of
integers. In Python 2.7. there are two separate types “int” (which is 32
bit) and “long int” that is same as “int” of Python 3.x, i.e., can store
arbitrarily large numbers.
•x = 10
•print(x)
•x = 10000000000000000000000000000000000000000000
•print(x)
Expressions…
Operators and Operands
• Operators are special symbols that represent computations like
addition and multiplication.
• The values the operator uses are called operands.
• +, -, *, /, %, **,//
• ** is used for exponential.
• / is also used for float division
• // is used to integer division
ARITHMETIC OPERATORS
The modulus operator
• The modulus operator works on integers (and integer expressions)
and yields the remainder when the first operand is divided by the
second.
• In Python, the modulus operator is a percent sign (%).
Example
• The syntax is the same as for other operators:
>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1
• So 7 divided by 3 is 2 with 1 left over.
Numeric Expressions
Operator Operation
+ Addition
• Asterisk is multiplication - Subtraction
* Multiplication
• Exponentiation (raise to a power) looks
different than in math / Division
** Power
% Remainder
Numeric Expressions
>>> xx = 2 >>> jj = 23
>>> xx = xx + 2 >>> kk = jj % 5 Operator Operation
>>> print(xx) >>> print(kk)
+ Addition
4 3
>>> yy = 440 * 12 >>> print(4 ** 3) - Subtraction
>>> print(yy) 64 * Multiplication
5280
>>> zz = yy / 1000 4R3 / Division
>>> print(zz) 5 23 ** Power
5.28 20 % Remainder
3
We always get answer in float!!
>>> 2/3
0.6666666666666666
>>> 2.0/3
0.6666666666666666
>>> 2.0/3.0
0.6666666666666666
>>> 2//3
0
>>> 2.0//3
0.0
>>> 2.0//3.0
0.0
>>> 2.0//10
0.0
>>> 2.0//10.0
0.0
Order of Operations
• When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.
– Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want.
– Exponentiation has the next highest precedence.
– Multiplication, Float Division, Integer Division and remainder have
the same precedence, which is higher than Addition and Subtraction,
which also have the same precedence.
– Operators with the same precedence are evaluated from left to right.
Order of Evaluation
• When we string operators together - Python must know which one
to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others?
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
Highest precedence rule to lowest precedence rule:
• Parentheses are always respected Parenthesis
Power
• Exponentiation (raise to a power) Multiplication
Addition
• Multiplication, Division, and Remainder
Left to Right
• Addition and Subtraction
• Left to right
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0
>>>
Parenthesis
Power
Multiplication
Addition
Left to Right
Operator Precedence Parenthesis
Power
• Remember the rules top to bottom Multiplication
Addition
• When writing code - use parentheses Left to Right
• When writing code - keep mathematical expressions simple enough
that they are easy to understand
• Break long series of mathematical operations up to make them
more clear
Operations on Strings
• Mathematical operations can’t be performed on strings, even if the strings look like
numbers.
• the + operator represents concatenation.
• For Example:
– fruit = “apple"
– bakedGood = " nut bread“
– print(fruit + bakedGood)
• The * operator also works on strings; it performs repetition.
• For eg:
– ‘Fun’*3 is ‘FunFunFun’
What Does “Type” Mean?
• In Python variables, literals, and
constants have a “type”. >>> ddd = 1 + 4
>>> print(ddd)
• Python knows the difference between 5
>>> eee = 'hello ' + 'there'
an integer number and a string.
>>> print(eee)
‘hello there’
• For example “+” means “addition” if
something is a number and
“concatenate” if something is a string
concatenate = put together
Type Matters
• Python knows what “type” >>> eee = 'hello ' + 'there'
everything is >>> eee = eee + 1
Traceback (most recent call last):
File "<stdin>", line 1, in
• Some operations are <module>TypeError: Can't convert
prohibited 'int' object to str implicitly
>>> type(eee)
• You cannot “add 1” to a string <class'str'>
>>> type('hello')
<class'str'>
• We can ask Python what type >>> type(1)
something is by using the <class'int'>
type() function >>>
Several Types of Numbers
>>> xx = 1
• Numbers have two main types
>>> type (xx)
<class 'int'>
- Integers are whole numbers:
>>> temp = 98.6
-14, -2, 0, 1, 100, 401233
>>> type(temp)
<class'float'>
- Floating Point Numbers have
>>> type(1)
decimal parts: -2.5 , 0.0, 98.6, 14.0
<class 'int'>
>>> type(1.0)
• There are other number types - they
<class'float'>
are variations on float and integer >>>
Type Conversions
>>> print(float(99) + 100)
199.0
• When you put an integer and >>> i = 42
floating point in an >>> type(i)
expression, the integer is <class'int'>
implicitly converted to a float >>> f = float(i)
>>> print(f)
• You can control this with the 42.0
>>> type(f)
built-in functions int() and
<class'float'>
float()
>>>
Integer Division
>>> print(10 / 2)
5.0
>>> print(9 / 2)
Integer division produces a floating 4.5
point result >>> print(99 / 100)
0.99
>>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99
This was different in Python 2.x
String >>> sval = '123'
>>> type(sval)
<class 'str'>
Conversions >>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object
• You can also use int() and
to str implicitly
>>> ival = int(sval)
float() to convert between >>> type(ival)
<class 'int'>
strings and integers >>> print(ival + 1)
124
• You will get an error if the string >>> nsv = 'hello bob'
>>> niv = int(nsv)
does not contain numeric Traceback (most recent call last):
characters File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
with base 10: 'x'
User Input
• We can instruct Python to
nam = input('Who are you? ')
pause and read data from print('Welcome', nam)
the user using the input()
function
• The input() function
returns a string Who are you? Gurleen
Welcome Gurleen
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
- Describe what is going to happen in a sequence of code
- Document who wrote the code
- Turn off a line of code - perhaps temporarily
Comments
• It is a good idea to add notes to your programs to explain in natural
language what the program is doing. These notes are called comments.
• They are marked with the # symbol.
•Ctrl + / is used to add multiple line comments.
•“”” “”” or ‘’’ ‘’’
Questions ??
Programs
1. There are 5280 feet in a mile. Write a Python statement that calculates and prints
the number of feet in 13 miles
2. Write a Python statement that calculates and prints the number of seconds in 7
hours, 21 minutes and 37 seconds.
3. The perimeter of a rectangle is 2w+2h, where w and h are the lengths of its
sides. Write a Python statement that calculates and prints the length in inches
of the perimeter of a rectangle with sides of length 4 and 7 inches.
4. The circumference of a circle is 2πr, where r is the radius of the circle. Write a
Python statement that calculates and prints the circumference in inches of a circle
whose radius is 8 inches. Assume that the constant π=3.14.
Programs
4. Given p dollars, the future value of this money when compounded yearly at a rate
of r percent interest for y years is p(1+0.01r)y. Write a Python statement that
calculates and prints the value of 1000 dollars compounded at 7 percent interest
for 10 years.
5. Write a Python expression that combines the string "Joe Warren is 52 years old."
from the string "Joe Warren" and the number 52 and then prints the result (Hint:
Use the function str to convert the number into a string.)
6. The distance between two points (x0,y0) and (x1,y1) is [(x0−x1)2+(y0−y1)2]^(1/2) .
Write a Python statement that calculates and prints the distance between the
points (2,2) and (5,6).
Visualize the output of: