⦁ Comments
Comments are not part of the command, but rather intended as documentation for anyone reading the code In a Python command, anything
after a # symbol is a comment. For example:
print("welcome")
welcome
print(" Hello Students this is your first day") # This is First ins
print("good morning") #very good morning
#print("welcome to tyco 2024")
Hello Students this is your first day
good morning
Multiline comments are also possible, and are enclosed by triple double-quote symbols:
"""This is an example of a long comment that goes on
and on
and on """
print(" Hello world")
Hello world
""" i m from pune
work in multinational company
welcome all"""
print("welcome")
welcome
#This is an example of a long comment that goes on
#and on a
#and on
print(" Hello world")
Hello world
a variable is named locations used to store data in the memory.
Variables are containers for storing data values.
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
An assignment statement in Python has the form variable = expression.
This has the following effect.
First the expression on the right hand side is evaluated, then the result is assigned to the variable.
After the assignment, the variable becomes a name for the result.
The variable retains the same value until another value is assigned, in which case the previous value is lost.
Executing the assignment produces no output; its purpose it to make the association between the variable and its value.
datatype variable name;
int a,b,c,n;
= assignment operator a=10
== equal
File "<ipython-input-7-76f9f4be23c9>", line 1
= assignment operator a=10
^
SyntaxError: invalid syntax
Next steps: Fix error
A=10
A
print(type(A))
<class 'int'>
x = 2.5+ 2
print(x)
print(type(x))
4.5
<class 'float'>
a="aniket"
print(type(a))
<class 'str'>
Variables do not need to be declared with any particular type, and can be even change after they have been set.
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 aipha-numeric characters and underscores (A-Z,a-z,0-9 and _ )
Variable names are case-sensitive(BIG,Big,big are three different variables)
Variable names with more than one word can be difficult to read.
Start coding or generate with AI.
_x =2
type(x)
int
s=34.50
type(s)
float
aniket=8
type(aniket)
int
There are several techniques you can use to make them more readable:
Camel Case:
Each word,except the first,starts with a capital letter.
myVariableName="SANTOSH"
Pascal Case:
Each word starts with a capital letter.
MyVariableName="Santosh"
Snake Case:
Each word is separated by an underscore character.
my_variable_name="SANTOSH"
1num = 2
File "<ipython-input-17-7e18c4baed9c>", line 1
1num = 2
^
SyntaxError: invalid decimal literal
_num1=2
Many values to multiple variables:
Start coding or generate with AI.
x,y,z="om","Namah","Shivay"
one value to Multiple Variables:
x=y=z="Om"
To combine both text and a variable,python uses the + character :
x="powerful country"
print("India is"+" "+x)
print(x+" "+"INDIA IS")
India is powerful country
powerful country INDIA IS
a=b=c="equal"
print(a)
print("value of b:",b)
print("value of c:",c)
a=b=c=100 # a declaration means variable memory allocation
print("value of a:",a) # a=100 intilization of variable means assi
print("value of b:",b)
print("value of c:",c)
equal
value of b: equal
value of c: equal
value of a: 100
value of b: 100
value of c: 100
Double-click (or enter) to edit
college="working"
college working
holiday=None
print("college:",college)
print("holiday:",holiday)
college: working
holiday: None
a=int(input("Enter a value"))
Enter a value50
50
print(type(a))
<class 'int'>
Data types
Variable can store data of different type,and different types can do different things.
Python has the following data types built:
Text type : strings
Numeric Types : int,float,complex
Sequence Types : list,tuple,range
Mapping Types: dict
Set type: set,frozenset
Boolean type: bool
Binary Types : bytes,bytearray,memoryview
type():
you can get the type of any object by using the type() function
type(-75)
int
type(5)
int
type(5.0)
float
a=int(1.0)
print(a)
print(type(a))
1
<class 'int'>
a=int(input("enter a value"))
enter a value6
a
type(a)
int
a=int(1.0)
print(a)
print(type(a))
1.0
<class 'float'>
a=1.0
print(a)
print(type(a))
1.0
<class 'float'>
python is a dynamically typed language hence we need not define the type variable while declaring it the interprefer implicity bind the value with
its type
1. python numbers
numbers stores numeric values
2. 4 types of numeric data
int
long
float
complex
a=10
print("INTEGER",a)
type(a)
INTEGER 10
int
b=10.6
print("float no:",b)
type(b)
float no: 10.6
float
num_int=26
num_float=32.5
print("integer no:",num_int)
print("float no:",num_float)
integer no: 26
float no: 32.5
3+2i real number+imaginary number
⦁ Strings
Strings are sequences of characters enclosed in single or double quotes
Strings are an example of a sequence type.
'a'
" This is a string "
"This is a string , too"
type(" This is a string ")
str
x = "This is Text"
print(x)
y='This is Text'
print(y)
This is Text
This is Text
print("This is Text")
print('This is Text')
This is Text
This is Text
print(""" i m using
a python for developing
from last 10 years""")
i m using
a python for developing
from last 10 years
"""hello"""
'hello'
"""hello
sir"""
print(''' i m using
a python for developing
from last 10 years''')
i m using
a python for developing
from last 10 years
Strings in pyhon are arrays of bytes representing unicode characters.
However python does not have a character data type, a single character is simply a string with a len of 1.
Square brackets can be used to access elements of the string.
To get the length of a string , use the len() function.
0 1 2 3 4
a[10]={10,20,56,23,98}
b[5]={a,b,f,h,l}
print("\U0001f600")
😀
"r"
type("r")
str
# 01234567891011
x= "Good Morning"
print(x)
print(x[5])
print(len(x))
Good Morning
M
12
x= "Good Morning"
print(len(x))
12
Start coding or generate with AI.
Membership operator
in- Use to check if a certain phrase or charcter is present in a string.
in true false
not in true false
y="A sequence type putting santosh together some other types in a s
print(y)
print(len(y))
print("santosh"in y)
A sequence type putting santosh together some other types in a sequence.
73
True
x="i m santosh"
print(x)
print(len(x))
print("ayush"in x)
i m santosh
11
False
y="A sequence type is formed by putting together some other types in
print(y)
print("india" in y)
A sequence type is formed by putting together some other types in a sequence.
False
Y="i can do anything for our carrier"
print(Y)
print(len(Y))
print(Y[4])
print("india"not in Y)
i can do anything for our carrier
33
n
True
not in - Use to check if a certain phrase or charcter is Not present in a string.
y="A sequence type is formed by putting together some other types in
print(y)
print("type"not in y)
A sequence type is formed by putting together some other types in a sequence.
False
y="A sequence type is formed by putting together some other types in
print(y)
print("india" not in y)
A sequence type is formed by putting together some other types in a sequence.
True
slicing
you can return a range of characters by using the slice syntax.
Specify the start index and the end index, seperated by a colon, to return a part of the string.
slice from the start
By leaving out the start index, the range start at the first charcter.
Slice to the end
By leaving out the end index, the range will go to the end.
*Negative indexing *
Use negative indexes to start the slice from the end of the string.
slice(start, end, step)
Parameter
start Optional.
An integer number specifying at which position to start the slicing. Default is 0
end
An integer number specifying at which position to end the slicing
step
Optional. An integer number specifying the step of the slicing. Default is 1
# 0 1 2 3 4 5 6 7
a = ("a", "b", "c", "d", "e", "f", "g", "h")
# 1 2 1 2 1
x = slice(1,6,2)
# 1,2,3,4,5
print(a[x])
('b', 'd', 'f')
a=("india")
clbr , oaoaoy,clbrt,
# 01234567891011
a = ("colaboratory")
# 121212121
x = slice(0,10,2)
#0,1,2,3,4,5,6,7,8,9
print(a[x])
clbrt
a = ("algorithm")
x = slice(2,7,2)
print(a[x])
grt
# 0123456
a = ("STUDENT")
x = slice(2,5)
# 2,3,4
#0,1,2,3,4 (0,5)
print(a[x])
UDE
a = ("persistent")
x = slice(2,5)
print(a[x])
rsi
a = ("persistent")
# 0123456789
x = slice(5)
# 0,5....0,1,2,3,4
print(a[x])
persi
a = ("persistent")
x = slice(2,5)
print(a[x])
rsi
a = ("persistent")
x = slice(2,5)
print(a[x])
lyt
a = ("polytechnic")
x = slice(7)
print(a[x])
polytec
a = ("INSTITute")
x = slice(0,7,2)
print(a[x])
KISI
# 01234567
a = ("engineer")
# -3-2-1
x = slice(-2)
#0,-2
print(a[x])
engine
a = ("engineer")
print(a[-3:])
eer
txt = "Hellog World"[::-1]
print(txt)
dlroW golleH
y="A sequence type is formed by putting together some other types in
print(y[2])
print(y[0:8])
print(y[:12])
print(y[14:])
s
A sequen
A sequence t
e is formed by putting together some other types in a sequence
y="A sequence type is formed by putting together some other types in
print(y[-1:])
e
y="A sequence type is formed by putting together some other types in
print(y[-12:])
print(y[1::])
n a sequence
sequence type is formed by putting together some other types in a sequence
Upper Case
The upper() method returns the string in upper case.
Lower Case
The lower() method returns the string in lower case.
Remove whitespace strip method
whitespace is the space before and/or after the actual text, and very often you want to remove this space.
Replace String The replace() method replace a string with another string.
Split string
The split() method returns a list where the text between the specified seperator becomes the list item.
y="A sequence type "
print(y.upper())
A SEQUENCE TYPE
y="A sequence type is INDIA "
print(y.lower())
a sequence type is india
y=" A sequence type is formed by putting togethe
print(y)
print(y.strip())
A sequence type is formed by putting together some other types in a sequence
A sequence type is formed by putting together some other types in a sequence
y=" A sequence type is formedby putting together some other types
print(y)
print(y.strip())
A sequence type is formedby putting together some other types in a sequence g
A sequence type is formedby putting together some other types in a sequence g
y="A sequence type is formed "
print(y.replace("i","m"))
A sequence type ms formed
y="A sequence type is formed by putting together some other types in
print(y.replace("is","python"))
A sequence type python formed by putting together some other types in a sequence
y="A sequence&type is&formed by "
print(y.split("&"))
['A sequence', 'type is', 'formed by ']
y="A sequence type is ,formed by putting together some other types,
print(y.split(","))
['A sequence type is ', 'formed by putting together some other types', ' in a sequence']
y="A sequence type is ,formed by putting together some other "
y.replace(" ", "")
'Asequencetypeis,formedbyputtingtogethersomeothertypes,inasequence'
str1='python programming'
print("string 1:",str1)
str2='python programming is interesting'
print("first two characters:",str1[0:2])
print("4th character:",str1[3])
print("*with string:",str1*2)
print("+with string:",str1+str2)
string 1: python programming
first two characters: py
4th character: h
*with string: python programmingpython programming
+with string: python programmingpython programming is interesting
Concatenation
To concatenate ,or conbine,two strings you can use the + operator.
Format()
we can combine strings and numbers by using the format() method. The format() method takes the passed arguments, formats them, and
place them in the string where the placeholders {} is.
The format() methods takes unlimited numbers of arguments, and are placed into the respective plceholders.
You can use index numbers {0} to be sure the arguments are placed in the correct placeholders.
a=21
txt="My name is prathemesh, and i am {}"
print(txt.format(a))
My name is prathemesh, and i am 21
Start coding or generate with AI.
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age =
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)
My name is John, I'm 36
My name is John, I'm 36
My name is John, I'm 36
b="Welcome to engineering.This is {} years course "
y=6
print(b.format(y))
Welcome to engineering.This is 6 years course
a=5
b=5
a is b
True
b="Welcome to {} engineering.This is {} years course "
a=1
y=4
print(b.format(a,y))
Welcome to 1 engineering.This is 4 years course
a=[2,5,1,3,6,9,7]
a[2:6]=[2,4,9,0]
print(a)
Escape character
To insert characters that are illegal in a string, use an escape charcter.
An escape charcter \ followed by the character you want to insert.
Single Quote '
Blackslash
New line \n
Carriage Return \r
Tab \t
Backspace \b
form feed \f
octal value \ooo
Hex value \xhh
a="welcome to "Python" course."
print(a)
File "<ipython-input-2-7d6be68dccce>", line 1
a="welcome to "Python" course."
^
SyntaxError: invalid syntax
a="welcome to \"Python\" course."
print(a)
welcome to "Python" course.
a="welcome to Python course.\n This is an example"
print(a)
welcome to Python course.
This is an example
Strings Methods
Python has a set of built-in method that you can use in strings.
All string methods returns new values. They do not change the original string.
Capitalize()
converts the first character to upper case.
Count()
Returns the number of times a specified value occures in a string.
find()
Searches the string for a specified value and returns the position of where it was found
format()
Formats specified value in a string.
index()
Searches the string for a specified value and returns the position of where it was found.
islower()
Returns True if all characters in the srting of lower case.
lower()
converts a srting in lower case.
split()
splits the string at the specified seperator and returns a list
strip()
returns the trimmed version of the string.
upper()
converts a string into upper case.
y="welcome"
print(y.capitalize())
Welcome
y="welcome to engineering "
print(y.count("e"))
5
y="welcome to engineering "
print(y.find("e"))
1
how to check second occurance of value in string in python
keyboard_arrow_down find index of second occurence of substring in string
idx = string.find(substring, string.find(substring) + 1)
y="welcome tlo engineering"
print(y.find("l",y.find("l")+1))
9
y="welcome To engineering "
print(y.islower())
False
y="welcome to engineering "
print(y.islower())
True
Booleans
its represent one of two values :True or False 1 or 0
bool() function allows you two evaluate any value, and give you True or False in return.
Almost any value is evaluated to True if it has some sort of content .
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple,set and dictionary are True, except empty ones.
if 3>8:
print("Yes")
print("a")
if 3<8:
print("Yes")
Yes
x=110
print(x.__bool__())
True
y=0
print(y.__bool__())
False
# 0 1 3 4 2 5 6
a=[2,5,1,3,6,9,7]
a[2:6]=[2,4,9,0]
print(a)
[2, 5, 2, 4, 9, 0, 7]
b=["Hello","GOOD"]
b.append("python")
print(b)
['Hello', 'GOOD', 'python']
t1=[3,5,6,7]
print(t1[2])
print(t1[-1])
print(t1[2:])
print(t1[:])
print(t1[-2:])
6
7
[6, 7]
[3, 5, 6, 7]
[6, 7]
t1=[7,9,8,2,3,4,1,5]
print(t1[5])
4
t1=[7,9,8,2,3,4,1,5]
print(t1[1:7:3])
[9, 3]
Start coding or generate with AI.