[Go to site: main page, start]

0% found this document useful (0 votes)
20 views61 pages

Module1 Python Basics

The document provides an introduction to Python, detailing its history, features, and various programming concepts such as data types, variables, and built-in data structures like lists, tuples, sets, and dictionaries. It explains the significance of Python's syntax, the use of the Python interpreter, and how to run Python programs in different modes. Additionally, it covers the print function and sequence types, emphasizing Python's flexibility and ease of use for both beginners and experienced programmers.

Uploaded by

akshatawasthi732
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views61 pages

Module1 Python Basics

The document provides an introduction to Python, detailing its history, features, and various programming concepts such as data types, variables, and built-in data structures like lists, tuples, sets, and dictionaries. It explains the significance of Python's syntax, the use of the Python interpreter, and how to run Python programs in different modes. Additionally, it covers the print function and sequence types, emphasizing Python's flexibility and ease of use for both beginners and experienced programmers.

Uploaded by

akshatawasthi732
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Python

Prof. Soumya Patil


Assistant Professor,
Dept. of CSE, DSCE,Bengaluru
Python – a
mysterious name

►Python is a widely used general-purpose,


high level programming language. It was
initially designed by Dutch programmer
Guido van Rossum in 1991.
►The name Python comes from an old BBC
television comedy sketch series called
Monty Python’s Flying Circus. When Guido
van Rossum was creating Python, he was
also reading the scripts of Monty Python. He
thought the name Python was appropriately
short and slightly mysterious.
► Python is a higher level programming
language.
► Its syntax allows programmers to
express concepts in fewer lines of code.
Why should ► Python is a programming language that
we learn lets you work quickly and integrate
systems more efficiently.
Python? ► One can plot figures using Python.
► One can perform symbolic mathematics
easily using Python.
► It is available freely online.
Python versions
Python was first released on February 20, 1991 and later on developed by
Python Software Foundation.
Major Python versions are – Python 1, Python 2 and Python 3.
• On 26th January 1994, Python 1.0 was released.
• On 16th October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and
includes new features.
Latest version - On 2nd October 2023, Python 3.12 was released.
To check your Python version
i) For Linux OS type python -V in the terminal window.
ii) For Windows and MacOS type import sys print([Link]) in the
interactive shell.
Searching for
Python
Downloading
Python
Python Interpreter
The program that translates Python instructions and then executes
them is the Python interpreter. When we write a Python program,
the program is executed by the Python interpreter. This interpreter
is written in the C language.
There are certain online interpreters like
[Link]
[Link] ,
[Link]
that can be used to start Python without installing an interpreter.
Python IDLE
Python interpreter is embedded in a number of larger programs that
make it particularly easy to develop Python programs. Such a
programming environment is IDLE
( Integrated Development and Learning Environment).
It is available freely online. For Windows machine IDLE
(Integrated Development and Learning Environment) is installed
when you install Python.
Running Python
There are two modes for using the Python interpreter:
1) Interactive Mode
2) Script Mode
Options for running the program:
• In Windows, you can display your folder contents, and
double click on [Link] to start the program.
• In Linux or on a Mac you can open a terminal window,
change into your python directory, and enter the command
python [Link]
Interactive shell
IDLE shell
Running Python
1) in interactive mode:
>>> print("Hello Teachers")
Hello Teachers
>>> a=10
>>> print(a)
10
>>> x=10
>>> z=x+20
>>> z
30
Running Python
2) in script mode:
Programmers can store Python script source code in a file
with the .py extension, and use the interpreter to execute the
contents of the file.

For UNIX OS to run a script file [Link] you have to type:


python [Link]
Whitespace
Whitespace is meaningful in Python: especially
indentation and placement of newlines
∙Use a newline to end a line of code
Use \ when must go to next line prematurely
∙No braces {} to mark blocks of code, use
consistent indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
∙Colons start of a new block in many constructs,
e.g. function definitions, then clauses
Comments
∙ Start comments with #, rest of line is ignored
∙ Can include a “documentation string” as the
first line of a new function or class you define
∙ Development environments, debugger, and
other tools use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive
integer and returns facorial of n.”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)
Assignment
∙ Binding a variable in Python means setting a name to hold a reference to
some object
• Assignment creates references, not copies
∙ Names in Python do not have an intrinsic type, objects have types
• Python determines the type of the reference automatically based on what data is
assigned to it
∙ You create a name the first time it appears on the left side of an
assignment expression:
x=3
∙ A reference is deleted via garbage collection after any names bound to it
have passed out of scope
∙ Python uses reference semantics (more later)
Data Types
Python has various standard data types:
▪ Integer [ class ‘int’ ]
▪ Float [ class ‘float’ ]
▪ Boolean [ class ‘bool’ ]
▪ String [ class ‘str’ ]
Integer
Int:
For integer or whole number, positive or negative, without decimals of
unlimited length.
>>> print(2465635468765)
2465635468765
>>> print(0b10) # 0b indicates binary number
2
>>> print(0x10) # 0x indicates hexadecimal number
16
>>> a=11
>>> print(type(a))
<class 'int'>
Float
Float:
Float, or "floating point number" is a number, positive or negative.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
>>> print(0.00000045)
4.5e-07
>>> y=2.8
>>> print(type(y))
<class 'float'>
Boolean and String
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
>>> print(‘Science college’)
Science college
>>> type("My college")
<class 'str'>
Variables
One can store integers, decimals or characters in variables.
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)

a= 100 # An integer assignment


b = 1040.23 # A floating point
c = "John" # A string
Naming Rules
∙ Names are case sensitive and cannot start with a number.
They can contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
∙ There are some reserved words:
and, assert, break, class, continue, def, del,
elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not, or, pass,
print, raise, return, try, while
► Four built-in data structures in Python:-
► list, tuple, set, dictionary
► - each having qualities and usage different from the other three.

► List is a collection of items that is written with square brackets.


It is mutable, ordered and allows duplicate members. Example:
list = [1,2,3,'A','B',7,8,[10,11]]

List, Tuple, ► Tuple is a collection of objects that is written with first brackets.
It is immutable.

Set, Dictionary ► Example: tuple = (2, 1, 10, 4, 7)

► Set is a collection of elements that is written with curly brackets.


It is unindexed and unordered. Example: S = {x for x in
'abracadabra' if x not in 'abc'}

► Dictionary is a collection which is ordered, changeable and does


not allow duplicates. It is written with curly brackets and objects
are stored in key: value format.
► Example: X = {1:’A’, 2:’B’, 3:’c’}

List

1 2
Lists in Python are like The things put away in
arrays in C, but lists can the rundown are isolated
contain data of different with a comma (,) and
types. encased inside square
sections [].
#list of having only integers
► a= [1,2,3,4,5,6]
► print(a)

#list of having only strings


► b=[“Hello",“Ram", “Raghav"]
► print(b)

#list of having both integers and strings


► c= [“Hi",“Good",1,2,3,“Morning"]
► print(c)

#index are 0 based. this will print a single character


► print(c[1]) #this will print "you" in list c
Lists are mutable

>>> li = [‘abc’, 23, 4.34, 23]


>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]
∙ We can change lists in place.
∙ Name li still points to the same memory
reference when we’re done.
Tuple
# tuple having only integer type of
data.
► a=(1,2,3,4)
► print(a) #prints the whole tuple

# tuple having multiple type of data.


► b=("hello", 1,2,3,"go")
► print(b) #prints the whole tuple

#index of tuples are also 0 based


Tuples are immutable
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment

∙You can’t change a tuple.


∙You can make a fresh tuple and assign its
reference to a previously used name.
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
∙The immutability of tuples means they’re faster
than lists.
Summary: Tuples vs. Lists
∙ Lists slower but more powerful than tuples
• Lists can be modified, and they have lots of handy
operations and mehtods
• Tuples are immutable and have fewer features
∙ To convert between tuples and lists use the list() and tuple()
functions:
li = list(tu)
tu = tuple(li)
Dictionary
► Python Dictionary is an unordered sequence of data
of key-value pair form.
► It is similar to the hash table type.
► Dictionaries are written within curly braces in the
form key:value.
► It is very useful to retrieve data in an optimized way
among a large amount of data.
#a sample dictionary variable

a = {1:"first name",2:"last name", "age":33}

#print value having key=1


print(a[1])
#print value having key=2
print(a[2])
#print value having key="age"
print(a["age"])
Sets are used to store multiple items in a single
variable.

Set items are unordered, unchangeable, and do not


allow duplicate values.

Set
Example:

set1 = {"apple", "banana", "cherry", "apple"}

print(set1)
print function
>>>type(print)
Output:
builtin_function_or_method

>>>print( ‘Good morning’ ) or print(“Good morning”)


Output:
Good morning

>>>print(“Workshop”, “on”, “Python”) or print(“Workshop on Python”)


Output:
Workshop on Python
print function
>>>print(‘Workshop’, ‘on’, ‘Python’, sep=’\n’)
# sep=‘\n’ will put each word in a new line
Output:
Workshop
on
Python

>>>print(‘Workshop’, ‘on’, ‘Python’, sep=’, ’)


# sep=‘, ’ will print words separated by ,
Output:
Workshop, on, Python
print function
%d is used as a placeholder for integer value.
%f is used as a placeholder for decimal value.
%s is used as a placeholder for string.
a=2
b = ‘tiger’
print(a, ‘is an integer while’, b, ‘is a string.’)
Output:
2 is an integer while tiger is a string.
Alternative way:
print(“%d is an integer while %s is a string.”%(a, b))
Output:
2 is an integer while tiger is a string.
print function
a=True
# printing a string print(type(a))
name = “Rahul”
Output:
print(“Hey ” + name) <class ‘bool’ >

Output:
Hey Rahul
print(“Roll No: ” + str(34)) # “Roll No: ” + 34 is incorrect
Output:
Roll No: 34
b=10
# printing a bool True / False
print(type(b))
print(True)
Output:
Output: <class ‘int’>
True
print function
int_list = [1, 2, 3, 4, 5]
print(int_list) # printing a list
Output: [1, 2, 3, 4, 5]
my_tuple = (10, 20, 30)
print(my_tuple) # printing a tuple
Output: (10, 20, 30)
my_dict = {“language”: “Python”, “field”: “data science”}
print(my_dict) # printing a dictionary
Output: {“language”: “Python”, “field”: “data science”}
my_set = {“red”, “yellow”, “green”, “blue”}
print(my_set) #printing a set
Output: {“red”, “yellow”, “green”, “blue”}
print function
str1 = ‘Python code’
str2 = ‘Matlab code’
print(str1)
print(str2)
Output: Python code
Matlab code
print(str1, end=’ ‘)
print(str2)
Output: Python code Matlab code
print(str1, end=’, ‘)
print(str2)
Output: Python code, Matlab code
print function
items = [ 1, 2, 3, 4, 5]
for item in items:
print(item)
items = [ 1, 2, 3, 4, 5]

Output: for item in items:

1 print(item, end=’ ‘)

2
3 Output:

4 1 2 3 4 5

5
Sequence Types
∙ Access individual members of a tuple, list, or
string using square bracket “array” notation
∙ Note that all are 0 based…
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] # Second item in the tuple.
‘abc’
>>> li = [“abc”, 34, 4.34, 23]
>>> li[1] # Second item in the list.
34
>>> st = “Hello World”
>>> st[1] # Second character in string.
‘e’
Positive and negative indices

>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)


Positive index: count from the left, starting with 0
>>> t[1]
‘abc’
Negative index: count from right, starting with –1
>>> t[-3]
4.56
Slicing: return copy of a subset

>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)


Return a copy of the container with a subset of
the original members. Start copying at the first
index, and stop copying before second.
>>> t[1:4]
(‘abc’, 4.56, (2,3))
Negative indices count from end
>>> t[1:-1]
(‘abc’, 4.56, (2,3))
Slicing: return copy of a =subset

>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)


Omit first index to make copy starting from
beginning of the container
>>> t[:2]
(23, ‘abc’)
Omit second index to make copy starting at first
index and going to end
>>> t[2:]
(4.56, (2,3), ‘def’)
Copying the Whole Sequence
∙ [ : ] makes a copy of an entire sequence
>>> t[:]
(23, ‘abc’, 4.56, (2,3), ‘def’)
∙ Note the difference between these two lines for mutable
sequences
>>> l2 = l1 # Both refer to 1 ref,
# changing one affects both
>>> l2 = l1[:] # Independent copies, two refs
∙ To convert between tuples and lists use the list() and
tuple() functions:
li = list(tu) tu = tuple(li)
The ‘in’ Operator
∙ Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
∙ For strings, tests for substrings
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False
∙ Be careful: the in keyword is also used in the syntax of for loops and list
comprehensions
Operators
Addition + Subtraction -

Multiplication * Exponentiation **

Division / Integer division //

Remainder %

Binary left shift << Binary right shift >>

And & Or |

Less than < Greater than >

Less than or equal to <= Greater than or equal to >=

Check equality == Check not equal !=


Precedence of operators
Parenthesized expression ( ….. )
Exponentiation **
Positive, negative, bitwise not +n, -n, ~n
Multiplication, float division, int division, remainder *, /, //, %
Addition, subtraction +, -
Bitwise left, right shifts <<, >>
Bitwise and &
Bitwise or |
Membership and equality tests in, not in, is, is not, <, <=, >, >=, !=, ==
Boolean (logical) not not x
Boolean and and
Boolean or or
Conditional expression if ….. else
Precedence of Operators
► Examples:
►a = 20
►b = 10
►c = 15
►d = 5
►e = 2
►f = (a + b) * c / d
►print( f)
►g = a + (b * c) / d - e
►print(g)
►h = a + b*c**e
►print(h)
Multiple
Assignment
►Python allows you to assign a single
value to several variables
simultaneously.
► a = b = c = 1.5
► a, b, c = 1, 2, " Red“
►Here, two integer objects with
values 1 and 2 are assigned to
variables a and b respectively and
one string object with the value
"Red" is assigned to the variable c.
Assignment
∙You can assign to multiple names at the same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
∙Assignments can be chained
>>> a = b = x = 2
Accessing Non-Existent Name
Accessing a name before it’s been properly
created (by placing it on the left side of an
assignment), raises an error
>>> y

Traceback (most recent call last):


File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
Special Use of + and *
Examples:
x = "Python is "
y = "awesome."
z=x+y
print(z)
Output:
Python is awesome.

print(‘It is’ + 2*’very ’ + ’hot.’)


Output:
It is very very hot.
The + Operator
The + operator produces a new tuple, list, or string whose value
is the concatenation of its arguments.

>>> (1, 2, 3) + (4, 5, 6)


(1, 2, 3, 4, 5, 6)

>>> [1, 2, 3] + [4, 5, 6]


[1, 2, 3, 4, 5, 6]

>>> “Hello” + “ ” + “World”


‘Hello World’
The * Operator
∙ The * operator produces a new tuple, list, or string that
“repeats” the original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

>>> “Hello” * 3
‘HelloHelloHello’
Use of \”, \n, \t
Specifying a backslash (\) in front of the quote character in a string
“escapes” it and causes Python to suppress its usual special meaning. It is
then interpreted simply as a literal single quote character:
>>> print(" \”Beauty of Flower\” ")
”Beauty of Flower”
>>> print('Red \n Blue \n Green ')
Red
Blue
Green
>>> print("a \t b \t c \t d")
a b c d
Comments
Single-line comments begins with a hash ( # ) symbol and is useful in mentioning that
the whole line should be considered as a comment until the end of line.

A Multi line comment is useful when we need to comment on many lines. In python,
triple double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example:
“““ My Program to find
Average of three numbers ”””
a = 29 # Assigning value of a
b = 17 # Assigning value of b
c = 36 # Assigning value of c
average = ( a + b + c)/3
print(“Average value is ”, average)
Python Booleans
Booleans represent one of two values: True or False.

Example:

print(10 > 9)
print(10 == 9)
print(10 < 9) Example
Evaluate a string and a number:
print(bool("Hello"))
print(bool(15))

Evaluate two variables:


x = "Hello"
y = 15

print(bool(x))
print(bool(y))
Most Values are True

Almost any value is Any list, tuple, set,


Any string is True,
evaluated to True if Any number is True, and dictionary
except empty
it has some sort of except 0. are True, except
strings.
content. empty ones.

Example
The following will return True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
Some Values are False
► In fact, there are not many values that evaluate to False, except
empty values, such as (), [], {}, "", the number 0, and the
value None. And of course the value False evaluates to False.

Example
The following will return False:
► bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Thank You

You might also like