JNTUK R19 Python Programming Lab

  1. Write a program that asks the user for a weight in kilograms and converts it to pounds. There are 2.2 pounds in a kilogram.
    Click Here of Solutions

    weight = float(input("Enter weight in kilograms: "))
    print(weight,"Kilograms is equal to",2.2*weight,"Pounds")

    Enter weight in kilograms: 5
    5.0 Kilograms is equal to 11.0 Pounds

  2. Write a program that asks the user to enter three numbers (use three separate input statements). Create variables called total and average that hold the sum and average of the three numbers and print out the values of total and average.
    Click Here of Solutions

    n1 = int(input("Enter first number: "))
    n2 = int(input("Enter secod number: "))
    n3 = int(input("Enter third number: "))
    total = n1 + n2 + n3
    average = total/3
    print("Sum of three numbers is:",total)
    print("Average of three numbers is:",average)

    Enter first number: 9
    Enter secod number: 5
    Enter third number: 1
    Sum of three numbers is: 15
    Average of three numbers is: 5.0

  3. Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89.
    Click Here of Solutions

    n = int(input("Enter range: "))
    for i in range(8,n,3):
        print(i,end="")
        if i<n-3:
            print(", ",end="")

    Enter range: 100
    8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74, 77, 80, 83, 86, 89, 92, 95, 98

  4. Write a program that asks the user for their name and how many times to print it. The program should print out the user’s name the specified number of times.
    Click Here of Solutions

    name = input("Enter your name: ")
    n = int(input("How many times you want to print? "))
    for i in range(n):
        print(name)

    Enter your name: Govardhan
    How many times you want to print? 5
    Govardhan
    Govardhan
    Govardhan
    Govardhan
    Govardhan

  5. Use a for loop to print a triangle like the one below. Allow the user to specify how high the triangle should be.
    *
    **
    ***
    ****
    Click Here of Solutions

    h = int(input("Enter height of triangle: "))
    for i in range(h):
        for j in range(i+1):
            print("*",end="")
        print()

    Enter height of triangle: 5
    *
    **
    ***
    ****
    *****

  6. Generate a random number between 1 and 10. Ask the user to guess the number and print a message based on whether they get it right or not.
    Click Here of Solutions

    import random
    sysgen = random.randint(1,10)
    num = int(input("Guess a number between 1 and 10: "))
    if num==sysgen:
        print("You guess is right.")
    else:
        print("Sorry! System generated number is",sysgen)

    Guess a number between 1 and 10: 5
    Sorry! System generated number is 2

  7. Write a program that asks the user for two numbers and prints Close if the numbers are within .001 of each other and Not close otherwise.
    Click Here of Solutions

    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))
    if abs(num1-num2)<0.001:
        print("Close")
    else:
        print("Not Close")

    Enter first number: 1.235
    Enter second number: 1.235469
    Close

  8. Write a program that asks the user to enter a word and prints out whether that word contains any vowels.
    Click Here of Solutions

    word = input("Enter a word: ")
    flag=0
    for ch in word:
        if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' or ch=='A' or ch=='E' or ch=='I' or ch=='O' or ch=='U':
            flag=1
            print(ch,end=" ")
    if flag==0:
        print("No Vowels in word.")

    Enter a word: govardhan
    o a a

  9. Write a program that asks the user to enter two strings of the same length. The program should then check to see if the strings are of the same length. If they are not, the program should print an appropriate message and exit. If they are of the same length, the program should alternate the characters of the two strings. For example, if the user enters abcde and ABCDE the program should print out AaBbCcDdEe.
    Click Here of Solutions

    str1=input("Enter first string: ")
    str2=input("Enter second string: ")
    if len(str1)!=len(str2):
        print("String lengths are not equal.")
    else:
        result=''
        for ch1,ch2 in zip(str1,str2):
            result = result + ch2 + ch1
        print(result)

    Enter first string: abcde
    Enter second string: ABCDE
    AaBbCcDdEe

  10. Write a program that asks the user for a large integer and inserts commas into it according to the standard American convention for commas in large numbers. For instance, if the user enters 1000000, the output should be 1,000,000.
    Click Here of Solutions

    num = int(input("Enter large integer: "))
    sa = str(num)
    for i in range(len(sa)-3,0,-3):
        sa = sa[:i] + ',' + sa[i:]
    print("Standard American convention is :",sa)

    Enter large integer: 9030840889
    Standard American convention is : 9,030,840,889

  11. In algebraic expressions, the symbol for multiplication is often left out, as in 3x+4y or 3(x+5). Computers prefer those expressions to include the multiplication symbol, like 3*x+4*y or 3*(x+5). Write a program that asks the user for an algebraic expression and then inserts multiplication symbols where appropriate.
    Click Here of Solutions

    AlgExpr = input("Enter algebric expression: ")
    ConvertedExpr = ''
    for ch in AlgExpr:
        if ch>='0' and ch<='9':
            ConvertedExpr = ConvertedExpr + ch
        elif ch=='(':
            ConvertedExpr = ConvertedExpr + '*' + ch
        elif ch>='a' and ch<='z' and ConvertedExpr[-1]!='(':
            ConvertedExpr = ConvertedExpr + '*' + ch
        else:
            ConvertedExpr = ConvertedExpr + ch
    print("Converted expression is :",ConvertedExpr)

  12. Write a program that generates a list of 20 random numbers between 1 and 100.
    (a) Print the list.
    (b) Print the average of the elements in the list.
    (c) Print the largest and smallest values in the list.
    (d) Print the second largest and second smallest entries in the list
    (e) Print how many even numbers are in the list.
    Click Here of Solutions
    import random
    numList=[]
    for i in range(20):
        numList.append(random.randint(1,100));
    print("List is :",numList)
    print("Average is :",sum(numList)/20)
    print("Largest element is",sorted(numList)[-1],"and smallest element is",sorted(numList)[0])
    print("Second largest element is",sorted(numList)[-2],"and second smallest element is",sorted(numList)[1])
    count=0
    for ele in numList:
        if ele%2==0:
            count+=1
    print("Total number of even elements are :",count)
  13. Write a program that asks the user for an integer and creates a list that consists of the factors of that integer.
    Click Here of Solutions
    num = int(input("Enter a number : "))
    factors=[]
    for i in range(1,num+1):
        if num%i==0:
            factors.append(i)
    print("Factors of",num,"are :",*factors,end="")
  14. Write a program that generates 100 random integers that are either 0 or 1. Then find the longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in [1,0,1,1,0,0,0,0,1,0,0] is 4.
    Click Here of Solutions
    import random
    bitsList=[]
    for i in range(100):
        bitsList.append(random.randint(0,1))
    maxZeroSeq=zeroCount=0
    for i in range(100):
        if bitsList[i]==0:
            zeroCount+=1
            continue
        else:
            if maxZeroSeq             maxZeroSeq=zeroCount
            zeroCount=0
    print("Longest run of zeros in",bitsList,"is",maxZeroSeq)
  15. Write a program that removes any repeated items from a list so that each item appears at most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].
    Click Here of Solutions
    n=int(input("Enter number of elements to be insert: "))
    eles=[]
    print("Enter {} elements : ".format(n))
    for i in range(n):
        eles.append(int(input()))
    for i in range(n-1):
        j=i+1
        while j<n:
            if eles[i]==eles[j]:
                del eles[j]
                j-=1
                n-=1
            j+=1
    print("After removing duplicates list is",eles)
  16. Write a program that asks the user to enter a length in feet. The program should then give the user the option to convert from feet into inches, yards, miles, millimeters, centimeters, meters, or kilometers. Say if the user enters a 1, then the program converts to inches, if they enter a 2, then the program converts to yards, etc. While this can be done with if statements,it is much shorter with lists and it is also easier to add new conversions if you use lists.
    Click Here of Solutions
  17. Write a function called sum_digits that is given an integer num and returns the sum of the digits of num.
    Click Here of Solutions
    def sum_digits(num):
        sd=0
        while num!=0:
            sd=sd+num%10
            num=num//10
        return sd

    num=int(input("Enter number: "))
    print("Sum of digits of {} is {}".format(num,sum_digits(num)))