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

Python unit 1

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

Python unit 1

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

Python Programming

Unit 1
Janhavi Vadke
Contents
• Introduction
• Variables and Expressions
• Conditional Statements
• Looping
• Control statements
History
• Python is general purpose
programming language also
used as scripting language. It is
Open source language.
• The Python programming
language was developed in the
late 1980s and its
implementation was started in
December 1989 by Guido Van
Rossum in the Netherlands as a
successor to the ABC
programming language. (named
after Monty Python’s Flying
circus)
• Python 2.0 was released on 16 October 2000 and
had many major new features, including a cycle-
detecting garbage collector and support for
Unicode. With this release, the development
process became more transparent.
• Python 3.0 (initially called Python 3000 or py3k)
was released on 3 December 2008 after a long
testing period. It is a major revision of the
language.
• Releases of Python 3 include the 2to3 utility,
which automates the translation of Python 2 code
to Python 3.
• Unlike C/C++ or Java, Python statements do
not end in a semicolon
• In Python, indentation is the way you
indicate the scope of a conditional,
function, etc.
• No braces!
• Python is interpretive, meaning you don’t
have to write programs. You can just enter
statements into the Python environment
and they’ll execute
Python Features
1) Easy to Use:
Python is very easy to use and high level
language. Thus it is programmer-friendly
language
2) Expressive Language:
Python language is more expressive. The sense
of expressive is the code is easily
understandable
3) Interpreted Language:
Python is an interpreted language i.e.
interpreter executes the code line by line at a
time. This makes debugging easy and thus
suitable for beginners
4) Cross-platform language:
Python can run equally on different platforms
such as Windows, Linux, Unix , Macintosh etc.
Thus, Python is a portable language
5) Free and Open Source:
Python language is freely available
(www.python.org). The source-code is also
available. Therefore it is open source.
6) Object-Oriented language:
Python supports object oriented language.
Concept of classes and objects comes into
existence.
7) Extensible:
It implies that other languages such as C/C++
can be used to compile the code and thus it can
be used further in your python code
8) Large Standard Library:
Python has a large and broad library. It can help
to do regular expressions, documentation
generation, unit testing, threading, databases,
web browsers, email, xml, html, GUI, Tk ect.
9) GUI Programming:
Graphical user interfaces can be developed
using Python.

10) Integrated:
It can be easily integrated with languages like C,
C++, JAVA etc.
How to install python
• Visit www.python.org and navigate to
Downloads > Windows and click Python
3.6.5.
Running Python program
• use idle
Debugging
• Three kinds of errors can occur in a program: syntax
errors, runtime errors, and semantic errors.
1) Syntax error: “Syntax” refers to the structure of a
program and the rules about that structure
• For example, parentheses have to come in matching
pairs, so (1 + 2) is legal, but 8) is a syntax error
2) Runtime error: These condtype of error is a runtime
error, so called because the error does not appear until
after the program has started running. These errors are
also called exceptions because they usually indicate that
something exceptional (and bad) has happened.
3) Semantic error: The third type of error is
“semantic”, which means related to meaning. If
there is a semantic error in your program, it will
run without generating error messages, but it
will not do the right thing. It will do something
else.
Formal and Natural language

• Natural language – evolved naturally amongst


people like Hindi, English.
• Formal language- it is constructed to serve a
purpose in the context of science , art,
profession or industry
Difference Between Brackets, Braces, and Parentheses

Square brackets are lists


while parentheses are tuples.
Curly braces create dictionaries or sets.
• They are called literals;
1)Braces{}
a set literal:
• aset = {'foo', 'bar'}
a dictionary literal:
adict = {'foo': 42, 'bar': 81}
empty_dict = {}
2) Brackets[]
a list literal:
• alist = ['foo', 'bar', 'bar']
• empty_list = []
3) Parentheses()
Use in functions
Sum()
Identifier
• A Python identifier is a name used to identify a
variable, function, class, module or other object
• A identifier name must start with a letter or the
underscore character
• A identifier name cannot start with a number
• A identifier name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
• identifier names are case-sensitive (age, Age and AGE
are three different variables)
• Python does not allow punctuation characters such as
@, $, and % within identifiers.
Reserved Words
• The following list shows the Python keywords.
These are reserved words and you cannot use
them as constant or variable or any other
identifier names. All the Python keywords
contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Multi-Line Statements
• Statements in Python typically end with a new line.
Python does, however, allow the use of the line
continuation character (\) to denote that the line
should continue.
• total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do
not need to use the line continuation character.
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday']
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. For example
• word = 'word'
• sentence = "This is a sentence.“
• paragraph = ‘’’This is a paragraph. It is made up
of multiple lines and sentences.’’’
Comments in Python
• A hash sign (#) that is not inside a string literal
begins a comment.
• All characters after the # and up to the end of
the physical line are part of the comment and
the Python interpreter ignores them.
• #First comment
• print "Hello, Python!" # second comment
• Print (“hi”) “””comment can be also like this”””
Variables and Expressions
• Variables are nothing but reserved memory
locations to store values.
• Based on the data type of a variable, the
interpreter allocates memory and decides
what can be stored in the reserved memory.
Therefore, by assigning different data types to
variables, you can store integers, decimals or
characters in these variables.
Assigning Values to Variables

• Python variables do not need explicit declaration to


reserve memory space. The declaration happens
automatically when you assign a value to a variable.
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.
• counter = 100 # An integer assignment
• miles = 1000.0 # A floating point
• name = "John" # A string
Multiple Assignment
• Python allows to assign a single value to
several variables simultaneously. For example
• a=b=c=1
• We can also assign multiple objects to
multiple variables. For example −
• a,b,c = 1,2,"john"
Standard Data Types
• The data stored in memory can be of many
types.
• Python has five standard data types −
1) Numbers
2) String
3) List
4) Tuple
5) Dictionary
1) Number
• Number data types store numeric values. Number objects are created
when you assign a value to them. For example −
• var1 = 1
• var2 = 10
• Python supports four different numerical types −
1) int (signed integers)
2) long (long integers, they can also be represented in octal and hexadecimal)
3) float (floating point real values)
4) complex (complex numbers)

int long float complex


10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
2)strings
• Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.
• Python allows for either pairs 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 at the end.
• The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example −
• str = 'Hello World!‘
• print str # Prints complete string
• print str[0] # Prints first character of the string
• print str[2:5] # Prints characters starting from 3rd to 5th
• print str[2:] # Prints string starting from 3rd character
• print str * 2 # Prints string two times
• print str + "TEST" # Prints concatenated string
Type casting
• Casting in python is done using constructor functions
• int() - constructs an integer number from an integer
literal, a float literal or a string literal
• float() - constructs a float number from an integer
literal, a float literal or a string literal
• str() - constructs a string from a wide variety of data
types, including strings, integer literals and float literals
• x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
• long(x) to convert x to a long integer.
• float(x) to convert x to a floating-point
number.
Types of Operator
• Operators are special symbols in Python that carry out
arithmetic or logical computation. The value that the
operator operates on is called the operand.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Decision Making
• Decision making is anticipation of conditions
occurring while execution of the program and
specifying actions taken according to the
conditions.
1) if statements
2) if...else statements
3) if…..elif statements
4) nested if statements
Loop Control Statements
• A loop statement allows us to execute a
statement or group of statements multiple times.
• Loop control statements change execution from
its normal sequence. When execution leaves a
scope, all automatic objects that were created in
that scope are destroyed.
• In looping, sequences of statements are executed
untill some conditions for the termination of the
loop are satisfied. A program loop consist of two
segments , body of the loop and control
statement.
1) The "for" loop
The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects.
Syntax
for val in sequence:
Statements
Here val is a variable that takes the value of items inside
the sequence on each iteration.
Example
primes = [2, 3, 5, 7]
for p in primes:
print(p)
• The range() Function
• The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
• The range() function defaults to increment the
sequence by 1, however it is possible to
specify the increment value by adding a third
parameter: range(2, 30, 3):
2) "while" loop

• While loops repeat as long as a certain boolean


condition is met
• Syntax
while expression:
Statement
Example
count = 0
while (count < 5):
print(count)
count += 1
3) Nested loop
• Nested loop is a loop that occurs within
another loop.
• Syntax
• for val in sequence:
for val in sequence:
Statements
statements
Control statements

1) Terminating loops
break statement terminates the current loop and
resumes execution at the next statement. It is used
to exit a for loop or a while loop
count = 0
while True:
print(count)
count += 1
if (count >= 5):
break
2) Skipping specific conditions
• continue statement is used to skip the
remaining statements in the current iteration
of the loop and to move the control back to
the top of the loop.
• for i in range(1,11):
If (i==5):
continue
print (i)
Interactive mode and Script mode
1) Script mode- it is the mode where the scripted
and finished .py files are run in the Python
interpreter.
2) Interactive mode is command line commands
which gives immediate feedback for each
statement, while running previously fed
statements in active memory. As new lines are
fed into the interpreter, the fed program is
evaluated both in part and in whole.
>>> symbol indicates interactive mode
Using else Statement with Loops

• If the else statement is used with a for loop,


the else statement is executed when the loop
has exhausted iterating the list.
• If the else statement is used with a while loop,
the else statement is executed when the
condition becomes false.
format
• Old
• '%s %s' % ('one', 'two')
• New
• '{} {}'.format('one', 'two')
• Output
• one two

• for re-arranging the order of display without changing the


arguments.
• New
• '{1} {0}'.format('one', 'two')
• Output
• two one

You might also like