You are here: Home / Topics / Search / python

### Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchange

Filed under: Python
`def new_string(str): if len(str) >= 2 and str[:2] == "Is":   return str return "Is" + strprint(new_string("Array"))print(new_string("IsEmpty"))     Output:IsArray                             &  ......`

### Write a Python program to get a string which is n (non-negative integer) copies of a given str

Filed under: Python
`def larger_string(str, n):  result = ""  for i in range(n):     result = result + str  return resultprint(larger_string('abc', 2))print(larger_string('.py', 3))     Output:abcabc                        ......`

### Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum

Filed under: Python
`def sum_thrice(x, y, z):    sum = x + y + z     if x == y == z:     sum = sum * 3    return sumprint(sum_thrice(1, 2, 3))print(sum_thrice(3, 3, 3))     Output:6                     &nbs  ......`

### Write a Python program to test whether a number is within 100 of 1000 or 2000

Filed under: Python
`def near_thousand(n):     return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))print(near_thousand(1000))print(near_thousand(900))print(near_thousand(800))   print(near_thousand(2200))     Output:True                 ......`

### Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference

Filed under: Python
`def difference(n):   if n <= 17:       return 17 - n   else:       return (n - 17) * 2print(difference(22))print(difference(14))     Output:10                       &n  ......`

### Write a Python program to get the the volume of a sphere with radius 6

Filed under: Python
`pi = 3.1415926535897931r= 6.0V= 4.0/3.0*pi* r**3print('The volume of the sphere is: ',V)    Output:The volume of the sphere is:  904.7786842338603  `

### Write a Python program to calculate number of days between two dates

Filed under: Python
`The function returns date object with same year, month and day. All arguments are required. Arguments may be integers, in the following ranges:MINYEAR <= year <= MAXYEAR1 <= month <= 121 <= day <= number of days in the given month and yearIf an argument outside those ranges is give  ......`

### Python program to print formatted string

Filed under: Python
`print("""a string that you "don't" have to escapeThisis a  ....... multi-lineheredoc string --------> example""")      Output:a string that you "don't" have to escape                                  ......`

### Python program to print the calendar of a given month and year

Filed under: Python
`Code:import calendary = int(input("Input the year : "))m = int(input("Input the month : "))print(calendar.month(y, m))     Output:Input the year : 2017                                         ......`

### program to print the documents (syntax, description etc.) of Python built-in function(s)

Filed under: Python
`In Python, __doc__ is a special attribute that contains the documentation string for a module, class, function, or method. The documentation string is a brief description of the object and is often used to provide documentation for the object in the Python documentation.Sample function: abs()print(a`

### Python program that accepts an integer (n) and computes the value of n+nn+nnn

Filed under: Python
`Code:a = int(input("Input an integer : "))n1 = int( "%s" % a )n2 = int( "%s%s" % (a,a) )n3 = int( "%s%s%s" % (a,a,a) )print (n1+n2+n3)     Output:615  `

### program to display the examination schedule

Filed under: Python
`Python program to display the examination schedule. (extract the date from exam_st_date).exam_st_date = (11, 12, 2014)Sample Output: The examination will start from : 11 / 12 / 2014 Code:exam_st_date = (11,12,2014)print( "The examination will start from : %i / %i / %i"%exam_st_date)   &nbs`

### Python program to display the first and last colors from the following list

Filed under: Python
`color_list = ["Red","Green","White" ,"Black"]color_list = ["Red","Green","White" ,"Black"]print( "%s %s"%(color_list,color_list[-1]))     Output:Red Black 	`

### Python program to accept a filename from the user and print the extension of that

Filed under: Python
`filename = input("Input the Filename: ")f_extns = filename.split(".")print ("The extension of the file is : " + repr(f_extns[-1]))     Output:Input the Filename: abc.java                                 &n  ......`

### Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers

Filed under: Python
`Sample data: 3, 5, 7, 23Python list:A list is a container which holds comma separated values (items or elements) between square brackets where items or elements need not all have the same type. In general, we can define a list as an object that contains multiple data items (elements). The contents o  ......`

### Python program which accepts the user's first and last name and print them in reverse order with a space between them

Filed under: Python
`Python has two functions designed for accepting data directly from the user:Python 2.x. -> raw_input()Python 3.x. -> input()raw_input():raw_input() asks the user for a string of data and simply returns the string, the string data ended with a newline). It can also take an argument, which is di  ......`

### Python program which takes radius from user and print area

Filed under: Python
`#Write a Python program which accepts the radius of a circle from the user and compute the area Python: Area of a CircleIn geometry, the area enclosed by a circle of radius r is πr2. Here the Greek letter π represents a constant, approximately equal to 3.14159, which is equal to the ratio of   ......`

### Write a Python program to display the current date and time

Filed under: Python
`#Write a Python program to display the current date and time.import datetimenow = datetime.datetime.now()print ("Current date and time : ")print (now.strftime("%Y-%m-%d %H:%M:%S"))     Output:Current date and time : 2014-07-05 14:34:14 `

### Python Program to generate a random number between 0 and 9

Filed under: Python
`# Program to generate a random number between 0 and 9# importing the random moduleimport randomprint(random.randint(0, 9))`

### Python code to find sum of elements in given array

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python 3 code to find sum# of elements in given arraydef _sum(arr):   # initialize a variable   # to store the sum   # while iterating through   # the array later   sum = 0   # iterate through the a  ......`

### Python program for implementation of Bubble Sort

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python program for implementation of Bubble Sortdef bubbleSort(arr):   n = len(arr)   # Traverse through all array elements   for i in range(n - 1):   # range(n) also work but outer loop will repeat one time more than   ......`

### Python program for implementation of Quicksort Sort

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python program for implementation of Quicksort Sort# This function takes last element as pivot, places# the pivot element at its correct position in sorted# array, and places all smaller (smaller than pivot)# to left of pivot and all greater elements to righ  ......`

### Python code to count the number of occurrences in list

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python code to count the number of occurrencesdef countX(lst, x):   count = 0   for ele in lst:       if ele == x:           count = count + 1   return count# Driver Codelst = [&  ......`

### Python program to Reversing a list using reversed()

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Reversing a list using reversed()def Reverse(lst):   return [ele for ele in reversed(lst)]# Driver Codelst = [   10,   11,   12,   13,   14,   15,   ]print Reverse(lst)`

### Python program to swap first and last element of a list

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python3 program to swap first# and last element of a list# Swap functiondef swapList(newList):   size = len(newList)   # Swapping   temp = newList   newList = newList[size - 1]   newList[size - 1] = tem`

### Python program to find maximum in arr[] of size n

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python3 program to find maximum# in arr[] of size n# python function to find maximum# in arr[] of size ndef largest(arr, n):   # Initialize maximum element   max = arr   # Traverse array elements from second   # and  ......`

### Python Program to sort alphabetically the words form a string provided by the user

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Program to sort alphabetically the words form a string provided by the user# To take input from the usermy_str = input('Enter a string: ')# breakdown the string into a list of wordswords = [word.lower() for word in my_str.split()]# sort the listwords.sort()#`

### Python Program to check if a string is palindrome or not

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Program to check if a string is palindrome or notmy_str = 'aibohphobia'# make it suitable for caseless comparison# reverse the stringrev_str = reversed(my_str)# check if the string is equal to its reverseif list(my_str) == list(rev_str):   print 'T`

### Python program to find H.C.F of two numbers

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python program to find H.C.F of two numbers# define a functiondef compute_hcf(x, y):# choose the smaller number   if x > y:       smaller = y   else:       smaller = x   for i in range(  ......`

### Python Program to find the ASCII value of the given character

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Program to find the ASCII value of the given characterc = 'p'print ("The ASCII value of '" + c + "' is", ord(c))`

### Python Program to display the Fibonacci sequence up to n-th term

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Program to display the Fibonacci sequence up to n-th termnterms = int(input('How many terms? '))# first two terms(n1, n2) = (0, 1)count = 0# check if the number of terms is validif nterms <= 0:   print 'Please enter a positive integer'elif nterm  ......`

### Python program for Armstrong number

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python program to check if the number is an Armstrong number or not# take input from the usernum = int(input('Enter a number: '))# initialize sumsum = 0# find the sum of the cube of each digittemp = numwhile temp > 0:   digit = temp % 10  &  ......`

### Python program to find the Factorial of any number

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python program to find the factorial of a number provided by the user.# change the value for a different result# To take input from the usernum = int(input('Enter a number: '))factorial = 1# check if the number is negative, positive or zeroif num < 0:&nbs  ......`

### Python program to find the largest of three numbers

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python program to find the largest number among the three input numbers# change the values of num1, num2 and num3# for a different result# uncomment following lines to take three numbers from usernum1 = float(input('Enter first number: '))num2 = float(input(  ......`

### Python program to find the roots of Quadratic equation

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Solve the quadratic equation ax**2 + bx + c = 0# import complex math moduleimport cmatha = 1b = 5c = 6# calculate the discriminantd = b ** 2 - 4 * a * c# find two solutionssol1 = (-b - cmath.sqrt(d)) / (2 * a)sol2 = (-b + cmath.sqrt(d)) / (2 * a)print 'The s`

### Python Program to find the area of triangle

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python Program to find the area of triangle# Uncomment below to take inputs from the usera = float(input('Enter first side: '))b = float(input('Enter second side: '))c = float(input('Enter third side: '))# calculate the semi-perimeters = (a + b + c) / 2# cal  ......`

### Python program to swap two variables

Filed under: Python
`#!/usr/bin/python# -*- coding: utf-8 -*-# Python program to swap two variables# To take inputs from the userx = input('Enter value of x: ')y = input('Enter value of y: ')# create a temporary variable and swap the valuestemp = xx = yy = tempprint 'The value of x after swapping: {}'.format(x)print 'Th`

### While loop in python

Filed under: Python
`In python , there are two type of loops-- for loop- while loopwhile loop are simple loop which run until the condition will not become false Syntax :- while(condition):body of whileProgrami=20print("While loop start")while(i>10):print(i)i=i-1print("While loop ends")Output-While loop sta  ......`

### What is Break statement in python

Filed under: Python
`There are two type of loop in python -- for loop- while loop-At the time of execution of loop, if we want to terminate the loop before its actual termination point then we use break inside loop or we can say break is used to terminate the loop and resume the next instruction in the program.- break i  ......`

### Return list by function in python

Filed under: Python
`In function some times we need to return the value at back to the calling point of the function so that the return value is further used in program , generally in other programming like C language, we only return one value but in python we return number of values.- for returning the items we have a   ......`

### Write a program to add two numbers in python

Filed under: Python
`Program code#add two number by seperate functiondef add(a,b):return a+ba=int(input("Enter first numbern"))b=int(input("Enter second numbern"))#add and printprint("Sum is "+str(a+b))#add by function callingans=add(a,b)print("sum is "+str(ans))print(add(a,b))Output-Enter first number2Enter second numb  ......`

### How to add all number in list in python

Filed under: Python
`For calculating the sum of all numbers in the list in python, firstly we are aware of the list in python. list is mutable data type in python which hold a collection of items of different type.example -we have a list mylist=[1,2,3,4,5,6] and sum of all numbers in this list is :- 21 pr  ......`

### Increment and decrement operator in python

Filed under: Python
`In other programming language like C,C++, JAVA, we have a increment(++) and decrement(--) operator which increase and decrease the value respectively.example -a=3a++a will become 4a--a--a will become 2-But in python this type of operation is not validprogram -a=3a++print(a)a--a--print(a)output-   ......`

### What is "Set" in python

Filed under: Python
`Set in python are also similar as the list but in set items can never be repeated but in list items may repeated. Set is a immutable data type because in set , items value are not changes or index operation is not allowed.Even in set any kind of index operation is not allowed.Example of set:- S  ......`

### Type casting in python

Filed under: Python
`What is type casting -Conversion of one data type to another type is called type casting that means in programming at runtime we change the type of the data or variable which store data.Possible Type casting -int to floatfloat to intint to stringnumeric string to intlist to stringlist to setset to l  ......`

### List to string conversion in python

Filed under: Python
`String and list both are the different data type of different domain and structure of both data type is different. So when we want to convert list to string, we must aware of string as well as list in python.Example of conversion- List=['Hello','String']And we want to make a string which is loo  ......`

### String to list conversion in python

Filed under: Python
`String and list both are the different data type of different domain and structure of both data type is different. So when we want to convert string to list, we must aware of string as well as list in python.Example of conversion-String1='Mytext'And we want to make a list which is look like �List=  ......`

### What is List in python

Filed under: Python
`List is a mutable collection of the elements which belongs to different class of the data type, item in list are separated by comma (,) and list is enclosed in square brackets ([]),.List are very much similar to the array in c , but the major difference in both list and array in c is that item in li  ......`

### What is tuple in python

Filed under: Python
`Tuple in python also a sequence data type similar as list, item in tuple is separated by comma(,) and enclosed by parentheses.Tuple is immutable that means in tuple we can not modified the index value.Update is not allowed or addition new item are also not allowedTuple is read only listProgram-t=(1,  ......`

### What is Dictionary in python

Filed under: Python
`Python dictionary are the hash table type data. It arrangement are the two dimensional type or we can say each item contain two values ,one is key and another one is value corresponding to their keyDictionary is the mutable data typeEach item in dictionary are separated by the comma(,) and enclosed   ......`

### Explain String in Python

Filed under: Python
`String is a collection of characters, python provides simple and easy way to manage or manipulate the string. In Python, single character are also a string of length one and string in python are immutable.String is Immutable :-It means that at runtime we can not change the index value in the string   ......`

### Zip() function in python

Filed under: Python
`In Python, Zip() is an In-build function in which we pass two list as a argument and it will give or return the dictionary of python.Basically it take two list and take items of first list as a key and items of second list as a corresponding valuesExample - L1=[1,2,3]L2=[4,,5,6]ans= zip(L1,L2)h  ......`

### Range() function in Python

Filed under: Python
`Range in python is a in-build function which return the collection of sequential numbers started from the 0 by default up to specified range. It uses in python programming where we want to generate some sequential numbers.Example -range(4) will give 0,1,2,3range(1,5) will give 1,2,3,4range(5,1) will  ......`

### Write Hello World Program in Python

Filed under: Python
`In python 3, we have a print function for printing any string or statement on console. Here we are able to pass our string in single,double and triple quotation .i,e all three quotation are valid and we do not require to add a semicolon at the end of the line in python because python is a scripting   ......`

### Input in Python

Filed under: Python
`Python3 provide build-in function input() to take input or data from the user at the runtime of the program. python have print() function for display the data and input() for get the data, but here input() function have a capability of display and get the data from user side simultaneously.Syntax :   ......`

### Basic data type in python

Filed under: Python
`Basic data type in Python-followings are the basic data type in python:-1. bool2. int 3. float4. str5. list6. set7. tuple8. dict BoolContain boolean values i.e. true or falseexample :- a=True print(a) // output - True ________________________________________Intcontain i  ......`

### Append and read in file handling in python

Filed under: Python
`read()-- read() is a python file function which are used to read the existing file.Syntax-f=open('file.txt','r')f.read()-Here 'f' is the object which points the existing file.Append in file-Syntax-f=open('file.txt','a')f.write(string)-Here string is the content which we want to append into the file.  ......`

### write() and read() in file handling in python

Filed under: Python
`read()-read() is a python file function which are used to read the existing file.Syntax-f.read()Here 'f' is the object which points the existing file.write()- write() is a python file function which are used to write in the file. If the file is not exist then write() function create new fi  ......`

### File handling in python

Filed under: Python
`-Python supports file handling and allow users to handles the file.-user can easily perform many operation on file like read,write, modification etc.-the concept of file handling in python was inherit from the other old languages like c,c++.Open a file-Syntax-f=open(filename,mode)-Here filename is t  ......`