#Assigning a value to variable
x=1
#Print function is used to print the object
print(x)
#Type function is used to check the data type of the object
type(x)
The Integer can be converted to float by method of Typecasting, which can be done as follows
b=float(x)
print(b)
Float¶
y=1.5
print(y)
type(y)
The Float can be converted to integer by method of Typecasting, which can be done as follows
#We will be converting value in variable y to integer and assigning it to a
a=int(y)
print(a)
Boolean¶
This store values as True or False
p=True
q=False
type(p)
type(q)
We can also typecast into Boolean from integer. Its interesting to note that 0 will transalte to False
and anything greater than 0 will be treated as True
x=1
y=2
z=0
w=-1
p=bool(x)
q=bool(y)
r=bool(z)
s=bool(w)
print(type(p))
print(p,q,r,s)
print(type(p))
print(type(r))
print(int(p))
print(int(r))
String¶
z='Python is easy'
print(z)
type(z)
One important thing to note is that string is indexed, what I mean by that is that you can reference each element of string by using its index. In Python index starts from 0
#I am retrieving element at index 0 i.e. 1st element of string z
z[0]
Now if we want to retrieve multiple objects we can do slicing. Which is done as follows:
string[start:end:step]
the argument and end is not included. So it will only fetch elements till end-1
step tells difference between consecutive elements that needs to be fetched. By default its 1
z[0:6:]
# In this case we will specify step as 2, such that it picks up every second element
z[0:6:2]
We can also find out how many elements in the string
len(z)
In strings there is also reverse indexing, that starts from -1
#Will print last element in string z
z[-1]
Slicing can also be done using negative indexing. (If end is left blank it means till end of string)
z[-4::]
To Count the number of elements in a string , we can use function count
#Counts number of times s appears in string z
z.count('s')
Changing the case of strings (uppercase/lowercase)
b='TRUST ME'
c='its easy'
print(b)
print(c)
print(b.lower())
print(c.upper())
Cancatenation of Strings
print(b+c)
Adding space in between
print(b+' '+c)
Another method of cancatenating strings is by using placeholders
print("{} when I say {}".format(b,c))
print(b,c)
print(b,c,sep=',')
Lets use some of the concepts learned above to create a simple application.
We will use a function input that accepts input from user
x=input('Enter number one: ')
y=input('Enter number two: ')
z=x+y
print('The sum is {}'.format(z))
The sum is wrong because, input function returns value as string. What Python simply did was cancatenate
x and y, because they were two strings seperated by +
We can fix this by typecasting input as int
x=input('Enter number one: ')
y=input('Enter number two: ')
z=int(x)+int(y)
print('The sum is {}'.format(z))