Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

CH 5 Getting Started With Python Part1

Uploaded by

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

CH 5 Getting Started With Python Part1

Uploaded by

prajinprajith808
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Getting Started with Python

INTRODUCTION
• An ordered set of instructions to be executed by a computer to carry out a specific
task is called a program.

• As we know that computers understand the language of 0s and 1s which is called


machine language or low level language.

• The programs are written mostly in high-level languages like Java, C++, Python etc.
and are called source code.

1. Compiler
 The language processor that reads the complete source program written in
high-level language as a whole in one go and translates it into an
equivalent program in machine language is called a Compiler. Example:
C, C++, C#.
 In a compiler, the source code is translated to object code successfully if it
is free of errors. The compiler specifies the errors at the end of the
compilation with line numbers when there are any errors in the source
code.
 The errors must be removed before the compiler can successfully
recompile the source code again the object program can be executed
number of times without translating it again.

2.Assembler
• Assembler is basically the 1st interface that is able to communicate humans with the
machine.

• We need an assembler to fill the gap between human and machine so that they can
communicate with each other.

• code written in assembly language is some sort of mnemonics(instructions) like


ADD, MUL, MUX, SUB, DIV, MOV and so on.
• The assembler is basically able to convert these mnemonics in binary code. Here,
these mnemonics also depend upon the architecture of the machine.

3.Interpreter

• The translation of a single statement of the source program into machine code is done
by a language processor and executes immediately before moving on to the next line
is called an interpreter.

• If there is an error in the statement, the interpreter terminates its translating process at
that statement and displays an error message.

• The interpreter moves on to the next line for execution only after the removal of the
error.

• An interpreter translates one line at a time and then executes it.

Features of Python
 Python is a high level language. It is a free and open source language.

 It is an interpreted language, as Python programs are executed by an interpreter.

 Python programs are easy to understand as they have a clearly defined syntax( set of
rules that defines how a program will be written) and relatively simple structure.

 Python is case-sensitive. For example, NUMBER and number are not same in
Python.

 Python is portable and platform independent, means it can run on various operating
systems and hardware platforms.

 Python has a rich library of predefined functions.

 Python is also helpful in web development. Many popular web services and
applications are built using Python.
Working with Python
To write and run (execute) a Python program, we need to have a Python interpreter
installed on our computer or we can use any online Python interpreter.

The interpreter is also called Python shell.

Execution Modes
There are two ways to use the Python interpreter:

a) Interactive mode : Interactive mode allows execution of individual statement


instantaneously

b) Script mode :Script mode allows us to write more than one instruction in a file
called Python source code file that can be executed

PYTHON KEYWORDS
• Keywords are reserved words(To do Special task).

• Each keyword has a specific meaning to the Python interpreter.

• we can use a keyword in our program only for the purpose for which it has been
defined.

• As Python is case sensitive, keywords must be written exactly as given

IDENTIFIERS
• In programming languages, identifiers are names used to identify a variable, function,
or other entities in a program.
The rules for naming an identifier in Python are as follows:

• The name should begin with an uppercase or a lowercase alphabet or an underscore


sign (_). This may be followed by any combination of characters a–z, A–Z, 0–9 or
underscore (_). Thus, an identifier cannot start with a digit.

• It can be of any length. (However, it is preferred to keep it short and meaningful).

• It should not be a keyword or reserved word

• .We cannot use special symbols like !, @, #, $, %, etc., in identifiers

For example
To find the average of marks obtained by a student in three subjects

we can choose the identifiers as marks1, marks2, marks3 and avg rather than a, b, c, or A, B,
C.

avg = (marks1 + marks2 + marks3)/3

VARIABLES
• A variable in a program is uniquely identified by a name (identifier)

• Variable in Python refers to an object — an item or element that is stored in the


memory.

• Value of a variable can be a string (e.g., „b‟, „Global_Citizen‟), numeric (e.g., 345) or
any combination of alphanumeric characters (CD67).

• In Python we can use an assignment statement to create new variables and assign
specific values to them

• Object – Defined area of memory that holds the data ('values') associated with a
type.

• Value – Actual data/bits in memory interpreted by the 'type„


Write a program to display values of variables in Python.

#To display values of variables

message = "Keep Smiling"

print(message)

userNo = 101

print('User Number is', userNo)

Output:

Keep Smiling

User Number is 101

COMMENTS
• Comments can be used to explain Python code.

• Comments can be used to make the code more readable.

• Comments can be used to prevent execution when testing code.

• Comments starts with a #, and Python will ignore them:

Examples

 #This is a comment
print("Hello, World!")

 print("Hello, World!")

#This is a comment
 #print("Hello, World!")

print("Cheers, Mate!")

Multiline Comments

• To add a multiline comment you could insert a # for each line:

 #This is a comment
#written in
#more than just one line
print("Hello, World!")

• you can add a multiline string (triple quotes) in your code, and place your
comment inside it:

 """
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Class in python
A class is a group of similar objects. Object is a real-world entity such as book, car, etc. Class
is a logical entity.

Class is a detailed description and template of what an object will be.


But it is not the object itself
EVERYTHING IS AN OBJECT
• Python is an object-oriented programming language, and in Python everything is an
object, an object is an entity that contains data along with associated metadata and/or
functionality.

• In order to know the address of the objects we have to use the function id().

Every object has these three attributes:

• Identity – This refers to the address that the object refers to in the computer‟s
memory. (unique name given to object)

• Type – This refers to the kind of object that is created. For example- integer, list,
string etc.

• Value – This refers to the value stored by the object. For example : List=[1,2,3] would
hold the numbers 1,2 and 3

DATA TYPES
Numbers
• A numeric value can be an integer, a floating number, or even a complex number.

These values are defined as Python int, Python float, and Python complex classes in Python.

 Integers – This value is represented by int class. It contains positive or negative


whole numbers. In Python, there is no limit to how long an integer value can be.

 a=5

print("Type of a: ", type(a))

o/p : Type of a: <class 'int'>

 Float – This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point.

 b = 5.0 print

("\nType of b: ", type(b))

o/p: Type of b: <class 'float'>

 Complex Numbers – A complex number is represented by a complex class. It is


specified as (real part) + (imaginary part)j. For example – 2+3j

 c = 2 + 4j
print("\nType of c: ", type(c))

o/p: Type of c: <class 'complex'>

 Boolean data type- Boolean data type (bool) is a subtype of integer.


• It is a unique data type, consisting of two constants, True and False.
• Boolean True value is non-zero, non-null and non-empty.
• Boolean False is the value zero

 print(type(True))
o/p : <class 'bool'>

 print(type(False))
o/p :<class 'bool'>

Sequence
• A Python sequence is an ordered collection of items, where each item is indexed by
an integer starting from 0.

• The three types of sequence data types available in Python are Strings, Lists and
Tuples.

A.String
• String is a group of characters. These characters may be alphabets, digits or special
characters including spaces.

• String values are enclosed either in single quotation marks (e.g., „Welcome‟) or in
double quotation marks (e.g., “Hello”).

• The quotes are not a part of the string, they are used to mark the beginning and end of
the string for the interpreter

• We cannot perform numerical operations on strings, even when the string contains a
numeric value

Example
 New = "Hello , 10, apple, 2.0"
print(New)

 Multiline Strings

MS = ""“Hello
Welcome
To
Sjpuc “””
print(MS)

B. List
• List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
• Lists are used to store multiple items in a single variable.
• The data type list is an ordered sequence that is mutable and made up of one or more
elements.
• A list can have elements of different data types, such as integer, float, string, tuple or
even another list.
• A list is very useful to group together elements of mixed data types.
• List indices also start from 0.

Example

#list1 is an example of Mixed data types


list1 = [20, 5.5, 'Hello"]
print(list1)
o/p : [20, 5.5, 'Hello']

#list2 is an example of a Nested list


list2=[['Varun', 1989],['Ravinder', 1990], [Amrit', 1991]]
print(list2)
o/p : [[ Varun',1989],['Ravinder, 1990], | Amrit', 1991]]

C.Tuples
• Tuples are used to store multiple items in a single variable.
• Tuple is a sequence of items separated by commas and items are enclosed in
parenthesis ( )
• The data type Tuples is an ordered sequence that is immutable
• A Tuples can have elements of different data types, such as integer, float, string, tuple
or even another Tuples.

Example
1) thistuple = ("apple, banana, cherry,6,4.0")
print(thistuple)

2) thistuple = ("apple", "banana", "cherry",6,4.0)


print(thistuple)
thistuple(2)='good'
print(thistuple)

3)Nested tuple
thistuple =(('Varun', 1989),('Ravinder', 1990), ('Amrit', 1991))
print(thistuple)

Sets
• Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }.
• A set is similar to list, except that it cannot have duplicate entries.
• Once created, elements of a set cannot be changed
• sets are unordered, we cannot access items using indexes as we do in lists.

Example
1) thisset = {"apple", "banana", "cherry", 3,4.5,6+5j}
print(type(thisset))

2) thisset = {"apple", "banana", "cherry", 3,4.5,6+5j}


print (thisset)

3) #duplicate elements are not included in set


thisset = {"apple",3, "banana", "cherry", 3,4.5,6+5j}
print (thisset)

None
• The None keyword is used to define a null value, or no value at all.
• None supports no special operations, and it is neither same as False nor 0 (zero).
• It is used to signify the absence of value in a situation

Example

1) myVar = None
print(type(myVar))

2) x = None
print(x)

Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping
data type in Python called dictionary.

Dictionary
• Dictionaries are used to store data values in key:value pairs.

• A dictionary is a collection which is ordered, changeable and do not allow duplicates.

• Dictionaries are written with curly brackets{}, and have keys and values using a
colon (:) sign

• The keys are usually strings and their values can be any data type.

• In order to access any value in the dictionary, we have to specify its key in square
brackets [ ]

Example

1) thisdict = {
"brand": "Ford",

"model": "Mustang",

"year": 1964

2) #Print the value of the dictionary

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict["brand"])

Difference between PDT

You might also like