Basic Python Chapter1

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

What is

Python
Python is high-level, general purpose, multi-paradigm
interpreted, programming
?
language. Interprete
r Python
Byte Virtual
Compiler
Code Machine

Editor Source
File Running

Library Progra
Modules m
Application areas
of
PyDattahSc
Machine Learning Natural Language
Processing
Network
Programming

i
oencne

Web Programming Database Internet of things Cyber Security


Programming (IOT)
Features of Python
• Simple and Easy to learn.
• Freeware and Open source.
• High level programming language.
• Platform independent.
• Portable.
• Dynamically typed.
• Both procedural and Object oriented programming language.
• Interpreted.
• Extensible and embedded.
• Rich standard library support.
History of
P• yDtevheloopned by Guido van Rossum in the late 80s and
at 90sthe National Research Institute for Mathematics
early
and Computer Science in the Netherlands.

• Derived from many other languages - ABC, Modula-3, C, C++,


Algol-68, Small Talk, Unix shell, and other scripting languages.

• Name Python, since Rossum was a big fan of Monty Python’s


Flying Circus.

• Now maintained by core development team at the institute,


although Rossum still holds a vital role in it.
print() • print() is used to display output.

• print() does not return any


value.
Various forms of print()
function.
1. print()
• print() with no arguments simply prints a new
line.
2. print(value1[, value2, …])
• print() with any number of values.
Hello Ajit Your Age is 42
• These values can be string, variables, expressions,
You are teaching Python and Data Science
call to any function.
name, age = "Ajit", 43
Sub1, sub2 = "Python", "Data Science"
print("Hello", name, "Your Age is", age)
print("You are teaching",sub1,"and",sub2)
3. print(value1[,value2,…], end="...")

By default, the value of end attribute is '\n'. If you want you can specify a different end value using
the end attribute.
print("Hello",end=' ')
print("World",end=' ')
print("Python")

Hello World Python


4. print(value1[,value2…], sep="...")

By default output values are separated by space. If you want you can specify separator by
using sep attribute.
a,b,c=10,20,30
print(a, b, c, sep=',')
print(a, b, c, sep=':')

10,20,30
10:20:30
5. print(object)

• Pass any object (like list, tuple, set, user defined object etc.) as argument to the print()
• Implicitly calls one magic method str ()

L=[10,20,30,40]
t=(10,20,30,40)
print(L
)
print(t)
[10,20,30,40]
(10,20,30,40)
6. print("format string"%(value1[,value2…]))

• The format string can contain any of the following format specifiers:
%i - for integer
%d - also for integer
%f - for float
%s - for String type

name, age = "Ajit", 43


sub1, sub2 = "Python", "Data Science"
print("Hello %s Your Age is %d"%(name,
age))
print("You are teaching %s and %s"%
(sub1,sub2))
Hello Ajit Your Age is 43
You are teaching Python and Data Science
Q 1: print ("Welcome to Guru99") ouput :Welcome to Guru99

Q 2: print("USA")
print("Canada")
print("Germany")
print("France")
print("Japan")

o/p:USA
Canada
Germany
France
Japan
Q 3;print
(8 * "\
n") OR
Q 3:print
("\n\n\n\
n\n\n\n\
o/P:Welcome to Guru99

Welcome to Guru99

Q 5:print ("Welcome to", end = ' ')


print ("Guru99", end = '!')
Output:

Welcome to Guru99!

Q 6:
# ends the output
with ‘@.’

print("Python" , end
= '@')
Q1. Write Python command/instruction/statement to display your name.

Q2. Write Python command to display your school name, class, and section, separated by -
7. print("string with replace operator {}".format(val1,[val2,…]))

• We can use a replacement operator in our string to put values or multiple values
in it.

name, s1, s2 = "Ajit", "Python", "Data Science"


print("Hello {0} you teach {1} and {2}".format(name,s1,s2))
print("Hello {x} you teach {y} and {z}".format(z=s2, x=name, y=s1))

Hello Ajit you teach Python and Data Science


Hello Ajit you teach Python and Data Science
input() • Function to accept some input from user.

• Note that every value that user enters is treated as a string. So we need to
typecast the entered value into the desired data type.
• Syntax: input([prompt])

s=input("Enter an integer:")
print(type(s) <class 'str'>
) x=int(s)
print(type(x) <class 'int'>
)

s=int(input("Enter an integer"))
print(type(s)) <class 'int'>
Write a program to accept to integers and find their sum.
Identifiers
Identifiers in Python are the names given to variable, class, library, module or a function.

Identifiers Naming Rule


1. Allowed characters: alphabets (lower case or upper case), digits(0 to 9) , underscore symbol(_)

2. The identifier should not start with a digit.

3. Identifiers are case sensitive.

4. We cannot use reserved words as identifiers.

5. There is no length limitation for the identifiers.


Valid ab10c
identifiers abc_DE
_
_abc
ajitmore

Invalid 99
identifiers 9abc
x+y
for
Keywords
• Keywords are reserved words of the language and have their predefined meaning.
• They are to be used for the intended purpose only. Cannot be used as variable, method,
module or class name.
• There are 33 reserved words available in Python.
• True, False, None
• and, or, not, is
• if, elif, else
• while, for, break, continue, return, in, yield
• try, except, finally, raise, assert
• import, from, as, def, pass, global, nonlocal,
class, lambda, del, with
Note:
• All the words are in alphabets.
• All are in lowercase except True, False, None.
Python Statements

• Python statements are instructions that are executed by the Python Interpreter.

a=5

• Python uses the semicolon(;) as a separator, not a terminator.

• You can also use them at the end of a line, which makes them look like a
statement terminator, but they are treated as two statements, the second one blank.
Python Comments
• Comments are portions of code ignored by the Python interpreter.
• Used for making short notes either as documentation or for reminders of the functionality of
a function. This makes the program easy to understand.
• Single line comment:
A line starting with a hash(#) character denotes a single line comment.

#this is an addition of two numbers


a,b,c=5,10,a+b
Python Comments (Contd.)
• Multiple line comment:
These are written within a block of starting and ending quotes(either single or double).
""" this is a multiline comment
just for example.
Single quotes can also be used."""
Data Types
• The data type of a variable basically represents what type of data value is present in the variable.
• In Python, we don't need to specify the data type for any variable because Python is a dynamically typed language.
• On the basis of value provided to the variable, the data type is also assigned.
• To know the data type of a variable we can use the type() function.
• To check whether the variable is of specified type use isinstance() function.
• To get address of object use id() function.
• The type() returns the data type of the variable.
x=5
print(type(x))
<class 'int'>
• The isinstance() returns the boolean values. True if the data types match as mentioned or false if it does
not match.
a = 1+2j
print(isinstance(a, complex))
True
Data Types (Contd.)
• The id() returns object’s memory
address.
x=10

print(id(x), id(y)) # 1394931776 1394931776


y=10
x=15
print(id(x),id(y)) # 1394931936 1394931776
x=10 15
y=10
x 10
x=15 y
y=25 25
int
• This data type is used to represent the whole numbers or the integral values.
• In python 3 there is no long data type. int is capable of storing long values.
• int can be represented in different forms like decimal, octal, hexadecimal, binary forms.

x=5
print(type(x))

<class 'int'>
float
• We can use float data type to store floating values or the decimal values.
• We can also assign values in exponential form using either lower or upper case of E.

f=1.3250
print(type(f))
<class 'float'>

f1=1.2E3
print(f1,type(f1))
1200.0 <class 'float'>
complex
• This data type represents the complex values. Complex values comprise the real and imaginary part.
c=5+6j #5 is real part and 6j is
imaginary. print(type(c))
<class 'complex'>
• We can also certain operations like addition and subtraction.
c=5+6j

e=c+d
d=6+5j #addition
print(e) # (11+11j)
e=d-e #subtracti
print(e) on
e=c*d # (-5-6j)
print(e) #multiplication
# 61j
• The inbuilt attributes real is used to retrieve the real part and imag is used to retrieve the imaginary part.
print(c.real) # 5
print(c.imag) # 6
bool
• This data type represents the boolean values.
• Only allowed values for this data type are True and False.
• Internally the value of True is 1 and the value for False is 0.
b=True
print(type(b)) # <class'bool'>
b=True
c=False
d=b>c
print(d) # True
print(True+True) # 2
print(True-False) # 1
print(False-True) # -1
print(False-False) # 0
str
• This data type represents the string values.
• A string is a sequence of characters that are enclosed within a single quote or a double quote.
• A single character can also be used for str data type.
s="Ram"
s1='Ram'
• For multi-line literals, we need to use triple quotes or triple double quotes.
s1='Python'
s2="""is a community built for
developers good"""
print(s1,s2)
Python is a community
built for developers good
Typ
c•eastin
Type Casting is the conversion of data type from one to another.
•gWe will use following five inbuilt functions for typecasting through the python coding.
int()
float()
complex()
bool()
str()
int(
) We use this function to convert any type into integer type value.
•• We cannot convert complex type into integer type so this becomes an exception.
• Also if we want to convert any string value into integer type then the string should only contain integral values
within quotes in the decimal form.

print(int(12.35)) # 12 str
print(int("123")) # 123 
print(int(True)) # 1
float 
int

print(int(2+4j)) # TypeError bool
print(int("Python")) # ValueError 
complex
float
()
• We use this function for converting other types into float type values.
• We cannot convert the complex type into a float.
• Also, the string should be in decimal form and contain only the integral or floating point value.

print(float(12)) # 12.0
print(float(True)) # 1.0 str
print(float("123.5")) # 123.5 
print(float("10")) # 10.0 int 
print(float("ten")) # ValueError float
print(float(3+5j)) # TypeError 
bool

complex
comple
x
(• )This function is used to convert other types into the complex data type.
• We can use it in two ways:
• complex(x)- In this case the complex type is created but with the zero imaginary part(0j).
• complex(x,y)- In this the complex type is created with the form x+yj.
print(complex(10)) # 10+0j
print(complex(10.5)) # 10.5+0j str
print(complex(True)) # 1+0j 
print(complex("108")) # 108+0j int 
print(complex(10,-5)) # 10-5j
complex
print(complex(True,False)) # 1+0j 
bool

• Note: In case of string it should be the integral value within quotes.
float
bool(
) This is used to convert other data types into a boolean
type.

• Remember these points-
• If x is int-
float- if the total
0 means value
False, is 0 then
Non-zero False,
means else True.
True.
• If x is complex- if both the real and imaginary part is zero. i.e. 0+0j then False, else
True.
• If x is a string- if the string is empty then False else True.
print(bool(0)) # False str
print(bool(5)) # True 
print(bool(0.2)) # True
print(bool(0.0)) # False
int 
print(bool(0+5j)) # True bool

print(bool(0+0j)) # False float
print(bool('')) # False 
print(bool("Python") # True
complex
str(
) We use this to convert other data types into string data type.
•• Whatever argument is passed it just quotes it and makes a string.

print(str(10)) # '10'
print(str(True)) # 'True' int
print(str(8+9j)) # '8+9j' 
float 
str

bool

complex
Operat
r Operators are special symbols in Python that carry out some specific task.
o
•• The value that the operator operates on is called operand.
2+3 #2 and 3 are operands whereas + is an
operator.
• Note that operands can be variables or constant values (literals)
• Operators are either unary (one operand) or binary (two operands) Arithmetic
• Operators have precedence and associativity operators

• To override precedence use brackets Assignment


operators
Comparison
operators
Operators
Logical
operators
Identity operators

Membership

operators Bitwise
Operat
r Operators are special symbols in Python that carry out some specific task.
o
•• The value that the operator operates on is called operand.
2+3 #2 and 3 are operands whereas + is an
operator.
• Note that operands can be variables or constant values (literals)
• Operators are either unary (one operand) or binary (two operands)
• Operators have precedence and associativity
• To override precedence use brackets

Operators

Arithmetic Comparison/Relational Logical


operators operators
Arithmetic
Operators
• Arithmetic operators are used to perform common mathematical operations.

Operator Name Example


+ Addition x+y • Any combination of int, float & bool allowed
- Subtraction x-y

* Multiplication x*y
/ Division x/y + on both str does concatenation
% Modulus x%y • * on str and int does repetition of str
** Exponentiation x ** y
• complex not allowed on % and //
// Floor division x // y

#Normal division print(5/ 2) #it will return 2.5


#Floor division print(5 // 2) #it will return 2
Comparison
O• Cpomeprarasi tonoorpesrators are used to
int float
compare two values.
Operator Name Example
bool
== Equal x == y
!= Not equal x != y X

> Greater than x>y


< Less than x<y str complex
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

== & != can be performed between any data type


Logical
•OLpogeciarl aopteroatrorss are used to combine conditional
Operator Description Example
statements:
and Returns True if both statements are x < 5 and x < 10
true

or Returns True if one of the statements x < 5 or x < 4


is true

not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
Identity
•Od
I peentirtyaotpeorartosrs are used to check whether two objects represent same memory
location or not:

Operator Description Example


is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
Membership
O• Mpeembreasr thiop orpserators are used to check whether an element is present in the

Iterable object or not:

Operator Description Example


in Returns True if an element is present in the Iterable object. x in y

not in Returns True if an element is not present in the Iterable x not in y


object.
Bitwise
•OBptw
i esi reaopteorartosrs are used to perform operation on individual bits of
operands:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall
off

>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let
the rightmost bits fall off
Assignment
O• Apsseginrmaetntoorpesrators are used to assign

value to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
1 x=6 4 x,y=10,50
y=2 print(x ** 2 > 100 and y < 100) False
print(x ** y) 36
print(x // y) 3
5 print(-18 // 4) -5

2 x = 100 6 print(10 - 4 * 2) 2
y = 50
print(x and y) 50
7 print(2 * 3 ** 3 * 4) 216

3 print(2 ** 3 ** 2) 512 8 y = 10
x = y += 2
print(x) SyntaxError
9 13 & 9 >> 1 4

10 a=4
b = 11
print(a | b) 15
print(a >> 2) 1

11 print(bool(0), bool(3.14159), bool(-3), bool(1.0+1j)) False True True True


12 print(4 == 99) Fals
print(10 == 10) e
print("cat" != "dog") True
print("mouse" != "mouse") True
print(True and True) Fals
print(False and True) e
print(False or True) True
print(False or False) Fals
print(not True) e
print(not False) True
print(True and (4 == 4)) Fals
print("lion" == "cat" or 99 ! e
= 88) Fals
e
True
True
True
>>> 2 and 3
>>> 5 and 0.00
>>> [] and 3
>>> 0 and {}
>>> False and "False”

LAZY METHOD/SHORT CIRCUIT METHOD USED BY PYTHON:


In these examples, the and expression returns the operand on the left if it evaluates to False.
Otherwise, it returns the operand on the right.
To produce these results, the and operator uses Python’s internal rules to determine an object’s truth
value.

With these rules in mind, look again at the code above.


In the first example, the integer number 2 is true (nonzero), so and returns the right operand, 3.
In the second example, 5 is true, so and returns the right operand even though it evaluates to False.
The next example uses an empty list ([]) as the left operand. Since empty lists evaluate to false, the and
expression returns the empty list.
The only case where you get True or False is the one where you use a Boolean object explicitly in the
expression.
FEW MORE EXAMPLES FOR PRACTICE

>>> 2 < 4 and 2


>>> 2 and 2 < 4
>>> 2 < 4 and [ ]
>>> [ ] and 2 < 4
>>> 5 > 10 and { }
>>> { } and 5 > 10
>>> 5 > 10 and 4
>>> 4 and 5 > 10F

You might also like