Lesson 1 Basic Concepts
Lesson 1 Basic Concepts
>>> x = input('something:’)
>>> x = raw_input("something:“)
something:10 #entered data is treated as number
>>> x something:10 #entered data is treated as string even without ‘’
>>> x
10
'10'
>>> x = input('something:’)
>>> x = raw_input("something:“)
something:'10' #entered data is treated as string something:'10' #entered data treated as string including ‘’
>>> x
>>> x
'10’
"'10'"
Python Programming
What is a New in Python 3
• Reading Input from Keyboard
• In Python 3, raw_input() function is deprecated. Further, the received data is always
treated as string.
>>> x = input("something:")
something:10
>>> x >>> x = raw_input("something:") # will result NameError
'10’ Traceback (most recent call last):
File "<pyshell#3>", line 1, in
>>> x = input("something:") <module>
something:'10' #entered data treated as string with x = raw_input("something:")
or without ‘’ NameError: name 'raw_input' is not defined
>>> x
"'10'"
Python Programming
What is a New in Python 3
• Integer Division
• In Python 2, the result of division of two integers is rounded to the nearest integer. As a
result, 3/2 will show 1.
• In order to obtain a floating-point division, numerator or denominator must be explicitly
used as float. Hence, either 3.0/2 or 3/2.0 or 3.0/2.0 will result in 1.5
• Python 3 evaluates 3 / 2 as 1.5 by default, which is more intuitive for new programmers.
• Unicode Representation
• Python 2 requires you to mark a string with a u if you want to store it as Unicode.
• Python 3 stores strings as Unicode, by default. We have Unicode (utf-8) strings, and 2 byte
classes: byte and byte arrays.
Python Programming
What is a New in Python 3
• xrange() Function Removed
• In Python 2 range() returns a list, and xrange() returns an object that will only generate the
items in the range when needed, saving memory.
• In Python 3, the range() function is removed, and xrange() has been renamed as range().
In addition, the range() object supports slicing in Python 3.2 and later.
• raise exception
• Python 2 accepts both notations, the 'old' and the 'new' syntax; Python 3 raises a
SyntaxError if we do not enclose the exception argument in parenthesis.
a = area(10)
print("area",a)
Interpreter vs Compiler
Python Programming
Interpreter vs Compiler
Interpreter Compiler
Translates program one statement at a time. Scans the entire program and translates it as a
whole into machine code.
It takes less amount of time to analyze the source It takes a large amount of time to analyze the
code but the overall execution time is slower. source code but the overall execution time is
comparatively faster.
No intermediate object code is generated, hence Generates intermediate object code which further
are memory efficient. requires linking, hence requires more memory.
Continues translating the program until the first It generates the error message only after scanning
error is met, in which case it stops. Hence the whole program. Hence debugging is
debugging is easy. comparatively hard.
Programming languages like Python, Ruby use Programming languages like C, C++, Java use
interpreters. compilers.
Programming Language Elements
Python Programming
Programming Language
• A programming language is a set of commands, instructions, and other syntax use to
create a software program.
• Programming Language elements:
• Lexis
• A lexis or lexicon is the complete set of all possible words in a language or its vocabulary.
• Syntax
• Refers to the spelling and grammar of a programming language or the structure of the program.
• Semantics
• Describes the relation between the sense of the program and the computational model or the processes a
computer follows when executing a program.
Basic Syntax
Python Programming
Python Identifiers
• A Python identifier is a name used to identify a variable, function, class, module or other
object.
• An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9).
• Python does not allow punctuation characters such as @, $, and % within identifiers.
• Python is a case sensitive programming language. Thus, Firstname and firstname are two
different identifiers in Python.
Python Programming
Python Naming Convention
• Class names start with an uppercase letter.
• All other identifiers start with a lowercase letter.
• Starting an identifier with a single leading underscore indicates that the identifier is private.
• Starting an identifier with two leading underscores indicates a strong private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
Python Programming
Python Reserve Keywords
and exec not
as finally or
assert for pass
break from print
class global raise
continue if return
def import try
del in while
elif is with
else lambda Yield
except
Python Programming
Lines and Indentation
• Python does not use braces({}) to indicate blocks of code for class and function definitions
or flow control.
• Blocks of code are denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.
• All the continuous lines indented with the same number of spaces would form a block.
Python Programming
Multiple-Line Statements
• Statements in Python typically end with a new line.
• Python, however, allows the use of the line continuation character (\) to denote that the
line should continue.
Python Programming
Multiple-Line Statements
• The statements contained within the [], {}, or () brackets do not need to use the line
continuation character.
Python Programming
Quotation in Python
• Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as
long as the same type of quote starts and ends the string.
• The triple quotes are used to span the string across multiple lines.
Python Programming
Comments in Python
• A hash sign (#) that is not inside a string literal is the beginning of a comment.
• All characters after the #, up to the end of the physical line, are part of the comment and
the Python interpreter ignores them.
Python Programming
Comments in Python
• You can comment multiple lines as follows:
Python Programming
Comments in Python
• Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comments:
Python Programming
Using Blank Lines
• A line containing only whitespace, possibly with a comment, is known as a blank line and
Python totally ignores it.
• In an interactive interpreter session, you must enter an empty physical line to terminate a
multiline statement.
Python Programming
Waiting for the Users
• The following line of the program displays the prompt and, the statement saying “Press the
enter key to exit”, and then waits for the user to take action
Python Programming
Multiple Statement on a Single Line
• The semicolon ( ; ) allows multiple statements on a single line given that no statement
starts a new code block
Python Programming
Multiple Statement Group as Suites
• Groups of individual statements, which make a single code block are called suites in
Python.
• Compound or complex statements, such as if, while, def, and class require a header line and
a suite.
• Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and
are followed by one or more lines which make up the suite.
Variables, Constants and Literals
Python Programming
Variables
• A variable is a named location used to store data in the memory.
• Unlike other programming languages, Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• Variables do not need to be declared with any particular type and can even change type
after they have been set.
• String variables can be declared either by using single or double quotes
• 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.
Python Programming
Variables Example
Python Programming
Multiple Assignment
• Python allows you to assign a single value to several variables simultaneously.
Python Programming
Multiple Assignment
• Python allows you to assign a single value to several variables simultaneously.
Python Programming
Constants
• A constant is a type of variable whose value cannot be changed.
• It is helpful to think of constants as containers that hold information which cannot be
changed later.
Python Programming
Assigning a Value to Constant
• In Python, constants are usually declared and assigned in a module.
• Here, the module is a new file containing variables, functions, etc. which is imported to the
main file.
• Inside the module, constants are written in all capital letters and underscores separating
the words.
Python Programming
Literals
• Literal is a raw data given in a variable or constant.
• In Python, there are various types of literals they are as follows:
• Numeric Literals
• String Literals
• Boolean Literals
• Special Literals
Python Programming
Numeric Literals
• Numeric Literals are immutable (unchangeable).
• Numeric Literals can belong to three (3) different numerical types: Integer, Float, and
Complex.
Python Programming
String Literals
• A string literal is a sequence of characters surrounded by quotes.
• We can use both single, double, or triple quotes for a string.
• And, a character literal is a single character surrounded by single or double quotes.
Python Programming
Boolean Literals
• A Boolean literal can have any of the two values: True or False
Python Programming
Special Literals
• Python contains one special literal i.e. None
• We use it to specify that the field has not been created.
• The None keyword is used to define a null value, or no value at all.
Python Programming
Literal Collections
• There are four different literal collections List literals, Tuple literals, Dictionary literals, and
Set literals.
Python Programming
Standard Data Types
• The data stored in memory can be of many types.
• For example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters.
• Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them.
• Python has five standard data types:
• Number
• String
• List
• Tuple
• Dictionary
Python Programming
Numbers
• Number data types store numeric values.
• Number objects are created when you assign a value to them.
• You can also delete the reference to a number object by using the del statement.
• You can delete a single object or multiple objects by using the del statement.
• Syntax: del var1[, var2[,var3[…,varN]]]
• Python supports three different numerical types:
• int (signed integers)
• float (floating point real values)
• complex (complex numbers)
• All integers in Python3 are represented as long integers.
Python Programming
Numbers
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
-0490 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2-E12 4.53e-7j
A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are
real numbers and j is the imaginary unit.
Python Programming
Strings
• Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
• Python allows either pair of single or double quotes.
• Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at
0 in the beginning of the string and working their way from -1 to the end.
• The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
Python Programming
Strings
Python Programming
Iteration Through a String
• We can iterate through a string using a for loop.
Python Programming
String Membership
• We can test if a substring exists within a string or not, using the keyword in.
Python Programming
String – Built-in Functions to Work With
• Various built-in functions that work with sequence work with strings as well.
• Some of the commonly used ones are enumerate() and len().
• The enumerate() function returns an enumerate object. It contains the index and value of
all items in the strings as pairs. This can be useful for iteration.
• Similarly, len() returns the length (number of characters) of the string.
Python Programming
Escape Sequence
• An escape sequence starts with a backslash and is interpreted differently.
• If we use a single quote to represent a string, all the single quotes inside the string must be
escaped. Similar is the case with double quotes.
• One way to get around this problem is to use triple quotes.
Python Programming
List of Escape Sequences
Escape Sequence Description
\newline Backslash and newline ignored
\\ Backslash
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
Python Programming
Data Type Conversion
Function Description
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key, value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Print() and Input() Functions
Python Programming
Print() Function
• The Print() function prints the specified message to the screen, or other standard output
device.
• The message can be a string, or any other object, the object will be converted into a string
before written to the screen.
• Syntax:
print(object(s), sep=separator, end=end, file=file, flush=flush)
• Parameter Values:
• object(s) - Any object, and as many as you like. Will be converted to string before printed
• sep='separator’ - Optional. Specify how to separate the objects, if there is more than one. Default is ' ‘
• end='end’ - Optional. Specify what to print at the end. Default is '\n' (line feed)
• file - Optional. An object with a write method. Default is sys.stdout
• flush - Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
Python Programming
Print() Function Example
Python Programming
Print() Function – Output Formatting
• Sometimes we would like to format our output to make it look attractive.
• This can be done by using the str.format() method.
• This method is visible to any string object.
• The curly braces are used as placeholders.
• We can specify the order in which they are printed using numbers(tuple index).
• We can even use keyword arguments to format the string.
• We can also format strings like the old sprintf() style used in C Programming language. We
use the % operator to accomplish this.
Python Programming
Print() Function – Output Formatting Example 1
Python Programming
Print() Function – Output Formatting Example 2
Python Programming
Print() Function – Output Formatting Example 3
Python Programming
Print() Function – Output Formatting Example 4
Python Programming
Input() Function
• The Input() function allows user input.
• Syntax:
input(prompt)
• Parameter Values:
• prompt - A String, representing a default message before the input.
Python Programming
Input() Function Example
Expressions
Python Programming
Expressions
• Expression is the building block of computations
• Expression is made up of operands and operators
• Operators are the constructs, which can manipulate the value of operands.
Python Programming
Type of Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Programming
Arithmetic Operators
• Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Description Example Expression
+ Addition Add two operands or unary plus x+y
- Subtraction Subtract right operand from the left or unary minus x–y
* Multiplication Multiply two operands x*y
Division Divide left operand by the right one (always results
/ into float) x/y
< Less than Less than - True if left operand is less than the right x<y
Greater than or Greater than or equal to - True if left operand is
>= equal to x >= y
greater than or equal to the right
Less than or equal Less than or equal to - True if left operand is less than
<= to or equal to the right x <= y
Python Programming
Comparison Operators
Python Programming
Logical Operators
• Logical operators are used to combine conditional statements.
and Logical AND True if both the operands are true x and y
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
Python Programming
Identity Operators Example
Python Programming
Membership Operators
• They are used to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
**
~+-
* / % //
+-
>> <<
&
^|
<= < > >=
<> == !=
= %= /= //= -= += *= **=
is is not
in not in
not or and
Precision Handling
Thank you.
Python Programming
Floating-Point Number Precision Handling
• Python in its definition allows to handle precision of floating point numbers in several ways
using different functions.
• Most of them are defined under the “math” module.
• Some most used operations:
• trunc() :- This function is used to eliminate all decimal part of the floating point
number and return the integer without the decimal part.
• ceil() :- This function is used to print the least integer greater than the given number.
• floor() :- This function is used to print the greatest integer smaller than the given
integer.
Python Programming
Floating-Point Number Precision Handling Example
Python Programming
Floating-Point Number Precision Handling
• There are many ways to set precision of floating point value.
• Ways to set precision of floating point value:
• Using “%” :- “%” operator is used to format as well as set precision in python. This is similar to “printf”
statement in C programming.
• Using format() :- This is yet another way to format the string for setting precision.
• Using round(x,n) :- This function takes 2 arguments, number and the number till which we want
decimal part rounded.
Python Programming
Floating-Point Number Precision Handling
Namespace and Scope
Python Programming
Namespace
• To simply put it, a namespace is a collection of names.
• In Python, you can imagine a namespace as a mapping of every name you have defined to
corresponding objects.
• Different namespaces can co-exist at a given time but are completely isolated.
• A namespace containing all the built-in names is created when we start the Python
interpreter and exists as long as the interpreter runs.
• Each module creates its own global namespace.
• These different namespaces are isolated. Hence, the same name that may exist in different
modules do not collide.
• Modules can have various functions and classes.
• A local namespace is created when a function is called, which has all the names defined in
it. Similar, is the case with class.
Python Programming
Namespace
Python Programming
variable Scope
• Here, the variable a is in the global namespace.
• Variable b is in the local namespace of
outer_function() and c is in the nested local
namespace of inner_function()
• When we are in inner_function(), c is local to us, b is
non-local and a is global.
• We can read and assign new values to c but can
only read b and a from inner_function().
• If we try to assign as a value to b, a new variable b is
created in the local namespace which is different
than non-local b.
• The same thing happens when we assign a value
to a
Python Programming
variable Scope
• However, if we declare a as global, all the reference
and assignment go to the global a.
• Similarly, if we want to rebind the variable b, it must
be declared as non-local.
Python Programming
variable Scope
Python Programming
variable Scope
End of Lesson 1
Thank you.