Author: Saim Khalid

  • Python Arrays and lists?

    • Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.
    • Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.
    import array
    a = array.array('i', [1, 2, 3])
    for i in a:
    
    print(i, end=' ')    #OUTPUT: 1 2 3
    a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str) a = [1, 2, 'string'] for i in a: print(i, end=' ') #OUTPUT: 1 2 string
  • floor a number in Python?

    To floor a number in Python, you can use the math.floor() function, which returns the largest integer less than or equal to the given number.

    • floor()method in Python returns the floor of x i.e., the largest integer not greater than x. 
    • Also, The method ceil(x) in Pythonreturns a ceiling value of x i.e., the smallest integer greater than or equal to x.

    import math
    n = 3.7
    F_num = math.floor(n)
    print(F_num)

    Output

    3
  • for loop and while loop in Python?

    • For loopUsed when we know how many times to repeat, often with lists, tuples, sets, or dictionaries.
    • While loop: Used when we only have an end condition and don’t know exactly how many times it will repeat.

    for i in range(5):
        print(i)
    c = 0
    while c < 5:
        print(c)
        c += 1

    Output

    0
    1
    2
    3
    4
    0
    1
    2
    3
    4
    
  • concatenate two lists in Python?

    We can concatenate two lists in Python using the +operator or the extend() method.

    1. Using the + operator:

    This creates a new list by joining two lists together.

    a = [1, 2, 3]
    b = [4, 5, 6]
    res = a + b
    print(res)

    Output

    [1, 2, 3, 4, 5, 6]
    

    2. Using the extend() method:

    This adds all the elements of the second list to the first list in-place.

    a = [1, 2, 3]
    b = [4, 5, 6]
    a.extend(b)
    print(a)

    Output

    [1, 2, 3, 4, 5, 6]

  • What is init in Python?

    The __init__() method is known as a constructor in object-oriented programming (OOP) terminology. It is used to initialize an object’s state when it is created. This method is automatically called when a new instance of a class is instantiated.

    Purpose:

    • Assign values to object properties.
    • Perform any initialization operations.

    Example

    We have created a book_shop class and added the constructor and book() function. The constructor will store the book title name and the book() function will print the book name.

    To test our code we have initialized the b object with “Sandman” and executed the book() function. 

    class book_shop:

    # constructor
    def __init__(self, title):
    self.title = title

    # Sample method
    def book(self):
    print('The tile of the book is', self.title)


    b = book_shop('Sandman')
    b.book()
    # The tile of the book is Sandman
  • Python lists and tuples?

    Lists and tuples are fundamental Python data structures with distinct characteristics and use cases.

    List:

    • Mutable: Elements can be changed after creation.
    • Memory Usage: Consumes more memory.
    • Performance: Slower iteration compared to tuples but better for insertion and deletion operations.
    • Methods: Offers various built-in methods for manipulation.

    Example:

    a_list = ["Data", "Camp", "Tutorial"]
    a_list.append("Session")
    print(a_list)  # Output: ['Data', 'Camp', 'Tutorial', 'Session']Powered By 

    Tuple:

    • Immutable: Elements cannot be changed after creation.
    • Memory Usage: Consumes less memory.
    • Performance: Faster iteration compared to lists but lacks the flexibility of lists.
    • Methods: Limited built-in methods.

    Example:

    a_tuple = ("Data", "Camp", "Tutorial")
    print(a_tuple) # Output: ('Data', 'Camp', 'Tutorial')

  • list some of its key features?

    Python is a versatile, high-level programming language known for its easy-to-read syntax and broad applications. Here are some of Python’s key features:

    • Simple and Readable Syntax: Python’s syntax is clear and straightforward, making it accessible for beginners and efficient for experienced developers.
    • Interpreted Language: Python executes code line by line, which helps in debugging and testing.
    • Dynamic Typing: Python does not require explicit data type declarations, allowing more flexibility.
    • Extensive Libraries and Frameworks: Libraries like NumPy, Pandas, and Django expand Python’s functionality for specialized tasks in data science, web development, and more.
    • Cross-Platform Compatibility: Python can run on different operating systems, including Windows, macOS, and Linux.
  • global and local scope?

    • A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
    • A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.

  • Find the Factorial of a Number

    Python Program to Find the Factorial of a Number

    To understand this example, you should have the knowledge of the following Python programming topics:


    The factorial of a number is the product of all the integers from 1 to that number.

    For example, the factorial of 6 is 1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers, and the factorial of zero is one, 0! = 1.

    Factorial of a Number using Loop

    # Python program to find the factorial of a number provided by the user.
    
    # change the value for a different result
    num = 7
    
    # To take input from the user
    #num = int(input("Enter a number: "))
    
    factorial = 1
    
    # check if the number is negative, positive or zero
    if num < 0:
       print("Sorry, factorial does not exist for negative numbers")
    elif num == 0:
       print("The factorial of 0 is 1")
    else:
       for i in range(1,num + 1):
    
       factorial = factorial*i
    print("The factorial of",num,"is",factorial)

    Output

    The factorial of 7 is 5040
    

    Note: To test the program for a different number, change the value of num.

    Here, the number whose factorial is to be found is stored in num, and we check if the number is negative, zero or positive using if...elif...else statement. If the number is positive, we use for loop and range() function to calculate the factorial.

    iterationfactorial*i (returned value)
    i = 11 * 1 = 1
    i = 21 * 2 = 2
    i = 32 * 3 = 6
    i = 46 * 4 = 24
    i = 524 * 5 = 120
    i = 6120 * 6 = 720
    i = 7720 * 7 = 5040

    Factorial of a Number using Recursion

    # Python program to find the factorial of a number provided by the user
    # using recursion
    
    def factorial(x):
    
    """This is a recursive function
    to find the factorial of an integer"""
    if x == 1 or x == 0:
        return 1
    else:
        # recursive call to the function
        return (x * factorial(x-1))
    # change the value for a different result num = 7 # to take input from the user # num = int(input("Enter a number: ")) # call the factorial function result = factorial(num) print("The factorial of", num, "is", result)

    In the above example, factorial() is a recursive function that calls itself. Here, the function will recursively call itself by decreasing the value of the x.


    Also Read:

    Before we wrap up, let’s put your understanding of this example to the test! Can you solve the following challenge?

    Challenge:

    Write a function to calculate the factorial of a number.

    • The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
    • For example, for input5, the output should be 120
    1. def factorial(n):

  • Check Prime Number

    Python Program to Check Prime Number

    To understand this example, you should have the knowledge of the following Python programming topics:


    A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6.


    Example 1: Using a flag variable

    # Program to check if a number is prime or not
    
    num = 29
    
    # To take input from the user
    #num = int(input("Enter a number: "))
    
    # define a flag variable
    flag = False
    
    if num == 0 or num == 1:
    
    print(num, "is not a prime number")
    elif num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break
    # check if flag is True
    if flag:
        print(num, "is not a prime number")
    else:
        print(num, "is a prime number")</code></pre>

    Run Code

    Output

    29 is a prime number

    In this program, we have checked if num is prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.

    We check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the number is not prime, so we set flag to True and break out of the loop.

    Outside the loop, we check if flag is True or False.

    • If it is Truenum is not a prime number.
    • If it is Falsenum is a prime number.

    Note: We can improve our program by decreasing the range of numbers where we look for factors.

    In the above program, our search range is from 2 to num - 1.

    We could have used the range, range(2,num//2) or range(2,math.floor(math.sqrt(num)+1)). The latter range is based on the fact that a composite number must have a factor less than or equal to the square root of that number. Otherwise, the number is prime.

    You can change the value of variable num in the above source code to check whether a number is prime or not for other integers.

    In Python, we can also use the for...else statement to do this task without using an additional flag variable.