Basic Python Chapter1
Basic Python Chapter1
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
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")
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
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
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.
• 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.
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
• 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.
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
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
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:
>> 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