Python is one of the best programming language in the world. It is quite easy to learn when compared to other programming languages and it is free. So if you are starting your journey through programming and if its python then you should know these features to gain hands on knowledge of python.
![]() |
Python features which every new programmer must know |
Python with Mathematical operator
In [2]:
string_1="Welcome To Python..."
print(string_1 * 2)
In [3]:
print(string_1 + "program..." * 2)
Reversing the String
In [4]:
print(string_1[::-1])
Printing the selected part of the string
In [5]:
print(string_1[0:7])
In [6]:
list_1=[11,12,13,14,15]
print(list_1[::-1])
Joining of Strings and Reversing
In [7]:
list_2=["Hello", "Frank", "is", "Here", "Everyone"]
print(" ".join(list_2[::-1]) + " "",Right!!!")
List Comprehension
In [8]:
def mult(x):
return x**2+10
x=5
mult(x)
Out[8]:
Lets separate out the even numbers from the list_num to a new list list_even
In [9]:
list_num=[11,12,13,14,15,16]
list_even=[]
for x in list_num:
if x % 2 ==0:
list_even.append(x)
print(list_even)
After separating the even numbers lets use the function to see what results we get
In [10]:
list_num=[11,12,13,14,15,16]
list_even=[]
for x in list_num:
if x % 2 ==0:
list_even.append(mult(x))
print(list_even)
Instead of writing the code in such a long manner, we can do it in one line
In [11]:
list_num=[11,12,13,14,15,16]
print([mult(x) for x in list_num if x % 2 == 0])
What if we don't want to use the function
In [12]:
print([x ** 2 +10 for x in list_num if x % 2 == 0])
Now lets see what is lambda how to use it
In [13]:
mult = lambda x : x ** 2 +10
print([mult(12), mult(14), mult(16)])
In [14]:
list_int=[2, 1, 0, -1, -2]
print(sorted(list_int))
Lets use lambda for modification
In [15]:
print(sorted(list_int, key = lambda x : x ** 2))
Now lets see what is Map how to use it
map(function, sequence)
In [16]:
print(list(map(lambda x,y,z : x+y+z, [2,4,6],[1,3,5],[1,1,1])))
Lets see this in a simple way
In [17]:
x, y, z = [2,4,6], [1,3,5], [1,1,1]
Total=[]
for i in range(len(x)):
Total.append(x[i]+y[i]+z[i])
print(Total)
if, elif and else condition in one line
In [18]:
x=int(input())
if x >= 18:
print("Adult")
elif x < 18:
print("Teenager")
else:
print("Not Matched")
Now lets code it in one line
In [20]:
x=int(input())
print("Adult" if x >= 18 else "Teenager" if x < 18 else "Not Matched")
How to use Zip()
In [22]:
Country = ["India", "Bangladesh", "Sri Lanka"]
Capital = ["Mumbai", "Dhaka", "Colombo"]
print([" ".join(x) for x in zip(Country, Capital)])
Comments
Post a Comment