[MarsRover]

MarsRover()

Function Definition: MarsRover(Head = 4, Front Left = 1, Front Right = 7, Back Left = 2, Back Right = 6)

Parameters

NameTypeDescriptionExpected ValuesDefault Value
HeadintServo Port Number at which the Head Servo Motor is connected. 1-84
Front LeftintServo Port Number at which the Front Left Servo Motor is connected. 1-81
Front RightintServo Port Number at which the Front Right Servo Motor is connected. 1-87
Back LeftintServo Port Number at which the Back Left Servo Motor is connected. 1-82
Back RightintServo Port Number at which the Back Right Servo Motor is connected. 1-86

Description

The function initializes the Mars Rover object in Python and maps the 5 servos to the specified pins.

By default the following configuration is added:

  1. Head Servo – 4
  2. Front Left Servo – 1
  3. Front Right Servo – 5
  4. Back Left Servo – 2
  5. Back Right Servo – 6

Example

Display a mixed fraction for an improper fraction. Check if the input fraction is improper and call the mixedFraction() function for display.

Introduction:

This Python code allows users to input a numerator and denominator and checks if it forms an improper fraction. If it is an improper fraction, the code calls a function called mixedFraction() to display the mixed fraction. If the fraction evaluates to a whole number, it will display a message indicating that.

Code:

#Function to display mixed fraction for an improper fraction
#The requirements are listed below:
 #1. Input numerator and denominator from the user.
 #2. Check if the entered numerator and denominator form a proper fraction.
 #3. If they do not form a proper fraction, then call mixedFraction().
 #4. mixedFraction()display a mixed fraction only when the fraction does not evaluate to a whole number.
def mixedFraction(num,deno = 1):
 remainder = num % deno
#check if the fraction does not evaluate to a whole number
 if remainder!= 0: 
  quotient = int(num/deno)
  print("The mixed fraction=", quotient,"(",remainder, "/", deno,")")
 else:
  print("The given fraction evaluates to a whole number")
#function ends here
num = int(input("Enter the numerator: "))
deno = int(input("Enter the denominator: "))
print("You entered:",num,"/",deno)
if num > deno: #condition to check whether the fraction is improper
 mixedFraction(num,deno) #function call
else:
 print("It is a proper fraction")

Logic:

  1. Get the numerator and denominator from the user.
  2. Check if the entered fraction is an improper fraction (num > deno).
  3. If it is an improper fraction, call the mixedFraction() function.
  4. In the mixedFraction() function:
    – Calculate the remainder of the fraction (num % deno).
    – If the remainder is not 0, calculate the quotient (num/deno) and print the mixed fraction as “The mixed fraction = quotient (remainder/denominator)”.
    – If the remainder is 0, print “The given fraction evaluates to a whole number”.
  5. If the fraction is not an improper fraction, print “It is a proper fraction”.

Output:

The output of this code will be the display of the entered fraction and whether it is a proper fraction or an improper fraction. If it is an improper fraction, the mixed fraction will be displayed.

Enter the numerator: 10

Enter the denominator: 7

>> You entered: 10 / 7

>> The mixed fraction= 1 ( 3 / 7 )

Read More
This Python program define the function `calcpow` that calculates and displays the result of raising a given base to a given exponent.

Introduction:

This Python program calculates the result of raising a given base to a given exponent. It defines a function that accepts the base and exponent as arguments, calculates the result, and returns it. The program then prompts the user to enter the values for the base and exponent, calls the function with these values, and displays the result.

Code:

#Function to calculate and display base raised to the power exponent
#The requirements are listed below:
 #1. Base and exponent are to be accepted as arguments.
 #2. Calculate Baseexponent
 #3. Return the result (use return statement )
 #4. Display the returned value.
def calcpow(number,power): #function definition
 result = 1
 for i in range(1,power+1):
  result = result * number
 return result
 
base = int(input("Enter the value for the Base: "))
expo = int(input("Enter the value for the Exponent: "))
answer = calcpow(base,expo) #function call 
print(base,"raised to the power",expo,"is",answer)

Logic:

  1. Define the function `calcpow` to calculate and return the result of base raised to the power exponent.
  2. Initialize the variable `result` to 1.
  3. Use a `for` loop to iterate from 1 to power+1.
  4. Inside the loop, multiply `result` by `number` and update `result`.
  5. Return `result`.
  6. Prompt the user to enter the value for the base and exponent, and store them in `base` and `expo` variables.
  7. Call the `calcpow` function with `base` and `expo` as arguments and store the result in the `answer` variable.
  8. Print the base, exponent, and the result of the calculation.

Output:

Enter the value for the Base: 2

Enter the value for the Exponent: 3

>> 2 raised to the power 3 is 8

Read More
See an example of a function call and discover how a common error can be fixed by placing the function definition before the function call.

Introduction:

In this Python code example, we are exploring the concept of functions. Functions are blocks of code that can be defined and called multiple times, allowing for code organization and reusability. In this example, we have a function called `helloPython()` that simply prints the message “I love Programming”. However, we encounter a common error when trying to call the function. Let’s analyze the code and fix the error.

Code:

#print using functions
helloPython() #Function Call
def helloPython(): #Function definition
 print("I love Programming")

Logic:

  1. We start by defining the function `helloPython()`, which does not take any arguments.
  2. Inside the function, we use the `print()` function to display the message “I love Programming”.
  3. We then try to call the function `helloPython()` after its definition.
  4. However, we encounter a `NameError` because the function call is made before the function definition.
  5. To fix the error, we need to move the function definition `helloPython()` above the function call.

Output:

>> I love Programming

Read More
This Python code demonstrates how to calculate the area and perimeter of a rectangle using a function calcAreaPeri

Introduction:

This Python code demonstrates how to create a function to calculate the area and perimeter of a rectangle. The function accepts two parameters – length and breadth. It calculates the area and perimeter using the given formulae and returns a tuple containing the area and perimeter values. The user is prompted to enter the length and breadth of the rectangle, and the area and perimeter values are then displayed.

Code:

#Function to calculate area and perimeter of a rectangle
#The requirements are listed below:
 #1. The function should accept 2 parameters.
 #2. Calculate area and perimeter.
 #3. Return area and perimeter.
def calcAreaPeri(Length,Breadth):
 area = l*b 
 perimeter = 2*(l+b)
 #a tuple is returned consisting of 2 values area and perimeter
 return (area,perimeter) 
l = float(input("Enter length of the rectangle: "))
b = float(input("Enter breadth of the rectangle: "))
#value of tuples assigned in order they are returned
area,perimeter = calcAreaPeri(l,b) 
print("Area is:",area,"\nPerimeter is:",perimeter)

Logic:

  1. The function accepts two parameters – Length and Breadth.
  2. It calculates the area by multiplying the length and breadth and the perimeter by 2 times the sum of the length and breadth.
  3. The function returns a tuple containing the area and perimeter values.

Output:

Enter length of the rectangle: 100

Enter breadth of the rectangle: 80

>> Area is: 8000.0

>> Perimeter is: 360.0

Read More
Discover how Passive Infrared (PIR) motion sensors work, their principle of detecting infrared radiation, and their applications in security systems and lighting control
Introduction

A Passive Infrared (PIR) motion sensor is a device commonly used in security systems, lighting control, and other applications to detect the presence of a moving object or person by measuring changes in infrared radiation. It’s called “passive” because it doesn’t emit any energy itself; it only detects the infrared radiation emitted by objects in its field of view.

  1. Detection Principle: PIR sensors work based on the fact that all objects with a temperature above absolute zero (-273.15°C or -459.67°F) emit infrared radiation. PIR sensors are designed to detect changes in the amount of infrared radiation in their surroundings.
  2. Sensor Construction: A PIR sensor typically consists of two pyroelectric sensors, which are sensitive to changes in temperature, and a special Fresnel lens that focuses the infrared radiation onto these sensors.

Overview | PIR Motion Sensor | Adafruit Learning System

Circuit

connection

IR_VCC – 5v

IR_GND – GND

IR_OUTPUT – D7

LED+ to D9

LED- to  GND

Resistance -270

Code

Create a circuit as per the above circuit diagram

  1. From control drag  if -else block.
  2. From the Arduino sensor palette, add a “read digital sensor () at ()” block. Choose “PIR” as the sensor type and select pin 7.
  3. The sensor’s detection of an object will alter the status of pin 7 from LOW to HIGH. In response to object detection, add the “set digital pin () output as ()” block from the Arduino palette within the “if” block.
  4. For the “else” part, ensure the LED turns off when no object is in front of the sensor.
  5. Drag a “forever” block from the controls palette and place the above set of blocks inside it.
  6. finally, add when flag clicked block from events palette

 

Script

Output

OUTPUT will be updated soon

Read More
Discover how a metal touch sensor works, generating signals upon contact with charged objects. Learn to build a touch-responsive switch circuit using Arduino.
introduction

A metal touch sensor is a type of sensor that generates signals when touched by any charged object. it has a transistor-like element which sensor the external touch on it, based on thee signal generated we can use this sensor as a switch or any other application.

Circuit

 

 

Code

  1. Add an “if” block from the controls palette into the scripting area.
  2. From the Arduino sensor palette, add “read digital sensor () at pin()” inside the “if” block. Choose “touch sensor” from the drop-down menu
  3. Create a variable and name it “count.” Increment the count by 1 inside the “if” block, which helps keep track of touch interactions.
  4. Now use an “if then else” block inside the “if” block to check whether the count variable is even or odd. The modulo (mod) block from the Arduino palette can be utilized for this purpose.
  5. Based on the condition, control the LED to turn it ON for even counts and OFF for odd counts.
  6. Add the “set digital pin () output as ()” block from the Arduino palette within the “if” and “else” blocks, respectively.
  7. Set the “count” variable to 0 at the beginning of the code to ensure accurate counting from the start.
  8. Add a “when flag clicked” block from the events palette to initiate the code execution.

Script


  • Output

Read More
Understand how the piezoelectric effect generates electric charge in response to mechanical stress, making these sensors useful for pressure, acceleration, vibration, sound detection, and more
Introduction

A piezoelectric sensor is a type of sensor that uses the piezoelectric effect to measure changes in pressure, acceleration, force, temperature, and other physical quantities. The piezoelectric effect is a phenomenon in which certain materials generate an electric charge in response to mechanical stress or deformation. This property makes piezoelectric sensors useful for a wide range of applications where accurate measurements of mechanical changes are required. Here’s how piezoelectric sensors work:

  1. Piezoelectric Material: Piezoelectric sensors are constructed using materials that exhibit the piezoelectric effect, such as quartz, certain ceramics, and some polymers. These materials have a crystalline structure that allows them to generate an electric charge when subjected to mechanical pressure or deformation
  2. Applications: Piezoelectric sensors find applications in various fields:
    • Pressure Sensing: Measuring changes in pressure in industrial, medical, and automotive applications.
    • Acceleration and Vibration Monitoring: Detecting vibrations and accelerations in devices, structures, and machinery.
    • Acoustic and Sound Detection: Capturing sound waves for microphones and other acoustic applications.
    • Force Measurement: Measuring forces in materials testing, robotics, and biomechanics.
    • Temperature Compensation: Piezoelectric materials can be used for temperature compensation in electronic components.

Circuit diagram

Code

  1. Open pictoblox and create a new file.
  2. Goto boards and select Arduino Uno.
  3. Add ” When Flag Clicked” when from the event palette into the scripting area.
  4.  Add Forever ” block from controls palette.
  5. From looks palette drag “say() ” block into the scripting area and place it inside the forever block.
  6. From Sensor palette of Arduino, Drag ‘Read analog sensor () at ()”  and place it inside the say block. Choose generic from the drop-down.
  7.  Your final script will look like this.

Output

OUTPUT Gifs will be updated soon.

Read More
Understand how PIR sensors detect moving objects based on changes in infrared radiation.
Introduction

A Passive Infrared (PIR) motion sensor is a device commonly used in security systems, lighting control, and other applications to detect the presence of a moving object or person by measuring changes in infrared radiation. It’s called “passive” because it doesn’t emit any energy itself; it only detects the infrared radiation emitted by objects in its field of view.

  1. Detection Principle: PIR sensors work based on the fact that all objects with a temperature above absolute zero (-273.15°C or -459.67°F) emit infrared radiation. PIR sensors are designed to detect changes in the amount of infrared radiation in their surroundings.
  2. Sensor Construction: A PIR sensor typically consists of two pyroelectric sensors, which are sensitive to changes in temperature, and a special Fresnel lens that focuses the infrared radiation onto these sensors.

Overview | PIR Motion Sensor | Adafruit Learning System

 

 

Circuit Diagram:

 

Code:

Follow these steps to implement the code using Pictoblox for Quarky to control the LED based on the PIR sensor’s readings:

  1. Open Pictoblox and create a new file in block coding.
  2. Go to boards and select Quarky.
  3. Add an if-then-else block from the controls palette
  4. From sensor palette of Quarky, add “read digital senor () at pin ()” block in if-then-else block.
  5. Now if the D2 is high, the LED must turn ON by set D1 to High.
  6. Else the LED must remain OFF.
  7. Put the above set of code into the Forever block 
  8. Finally, add “when flag clicked” block at the start of the code. With this simple script your project is complete now.

OUTPUT

In this comprehensive introduction, you have learned about Quarky, the versatile microcontroller, and its potential in robotics and AI projects. Explore its various features, sensors, and plug-and-play functionality. Follow our step-by-step guide to set up the circuit with the PIR sensor and LED, and program Quarky using Pictoblox’s block coding. Witness the successful implementation through the final script and output, experiencing the magic of Quarky in action!

Read More
Learn about the working principle of piezoelectric sensors, their applications, and how to interface them with Quarky using Pictoblox.
Introduction
Introduction

A piezoelectric sensor is a type of sensor that uses the piezoelectric effect to measure changes in pressure, acceleration, force, temperature, and other physical quantities. The piezoelectric effect is a phenomenon in which certain materials generate an electric charge in response to mechanical stress or deformation. This property makes piezoelectric sensors useful for a wide range of applications where accurate measurements of mechanical changes are required. Here’s how piezoelectric sensors work:

  1. Piezoelectric Material: Piezoelectric sensors are constructed using materials that exhibit the piezoelectric effect, such as quartz, certain ceramics, and some polymers. These materials have a crystalline structure that allows them to generate an electric charge when subjected to mechanical pressure or deformation
  2. Applications: Piezoelectric sensors find applications in various fields:
    • Pressure Sensing: Measuring changes in pressure in industrial, medical, and automotive applications.
    • Acceleration and Vibration Monitoring: Detecting vibrations and accelerations in devices, structures, and machinery.
    • Acoustic and Sound Detection: Capturing sound waves for microphones and other acoustic applications.
    • Force Measurement: Measuring forces in materials testing, robotics, and biomechanics.
    • Temperature Compensation: Piezoelectric materials can be used for temperature compensation in electronic components.

Piezoelectric Sensor Pinout, Working & Datasheet

Circuit Diagram

 

Code

  1. Open Pictoblox and create a new file.
  2. Goto boards and select Quarky.
  3. Add ” When Flag Clicked” from the event palette into the scripting area.
  4.  Add Forever ” block from the controls palette.
  5. From looks palette drag “say() ” block into the scripting area and place it inside the forever block.
  6. From Sensor palette of Quarky, Drag ‘Read analog sensor () at ()”  and place it inside the say block. Choose generic from the drop-down.
  7.  Your final script will look like this.

Output

Now to read the different changes from the sensor, hit the sensor with your punch and you will see the change in sensor value shown by your sprite.

OUTPUT Gifs will be updated soon.

 

Read More
The code includes user-defined functions for determining the light color and providing a corresponding message, stay safe on the roads.

Introduction:

This Python code simulates a traffic light using two user-defined functions. The first function, trafficLight(), prompts the user to enter the color of the traffic light and then calls the second function, light(), to determine the corresponding message. The second function, light(), returns a value based on the color input, which is used to display the appropriate message. Make sure to enter the traffic light color in CAPITALS. After running the code, a safety message is printed.

Code:

#Function to simulate a traffic light
#It is required to make 2 user defined functions trafficLight() and light().
def trafficLight():
 signal = input("Enter the colour of the traffic light: ")
 if (signal not in ("RED","YELLOW","GREEN")):
  print("Please enter a valid Traffic Light colour in CAPITALS")
 else:
  value = light(signal) #function call to light()
 if (value == 0):
  print("STOP, Your Life is Precious.")
 elif (value == 1):
  print ("PLEASE GO SLOW.")
 else:
  print("GO!,Thank you for being patient.")
#function ends here
 
def light(colour):
 if (colour == "RED"):
  return(0);
 elif (colour == "YELLOW"):
  return (1)
 else:
  return(2)
#function ends here

trafficLight()
print("SPEED THRILLS BUT KILLS")

Logic:

  1. Define the function trafficLight().
  2. Prompt the user to enter the color of the traffic light.
  3. If the input is not “RED”, “YELLOW”, or “GREEN”, display an error message.
  4. If the input is valid, call the function light() with the input as the argument.
  5. Store the return value from the function light() in the variable “value”.
  6. Based on the value of “value”, display the appropriate message.
  7. Define the function light() which takes the color as an argument.
  8. If the color is “RED”, return 0.
  9. If the color is “YELLOW”, return 1.
  10. For any other color, return 2.
  11. Call the function trafficLight().
  12. Print the safety message “SPEED THRILLS BUT KILLS”.

Output:

>> Enter the colour of the traffic light: RED

>> STOP, Your Life is Precious.

>> SPEED THRILLS BUT KILLS

Read More
Learn how to access global and local variables in Python, and understand the concept of variable scope. See an example code and explanation.

Introduction:

In Python, variable scope refers to the accessibility of variables within different parts of a program. There are two types of variable scope: global and local. Global variables are accessible throughout the entire program, while local variables are only accessible within a specific function or block of code.

Code:

#To access any variable outside the function
num = 5

def myFunc1( ):
 y = num + 5
 print("Accessing num -> (global) in myFunc1, value = ",num)
 print("Accessing y-> (local variable of myFunc1) accessible, value=",y)
#function call myFunc1()
myFunc1()

print("Accessing num outside myFunc1 ",num)
print("Accessing y outside myFunc1 ",y)

Logic:

  1. Declare a global variable “num” and assign it a value of 5.
  2. Define a function called myFunc1().
  3. Inside myFunc1(), declare a local variable “y” and assign it the value of “num” plus 5.
  4. Print the values of “num” and “y” inside myFunc1().
  5. Call myFunc1().
  6. Print the values of “num” and “y” outside of myFunc1().

Output:

>> Accessing num -> (global) in myFunc1, value = 5

>> Accessing y-> (local variable of myFunc1) accessible, value= 10

>> Accessing num outside myFunc1 5

Note: NameError: name ‘y’ is not defined, because num is a global variable defined outside and y is a local variable that is defined inside user defined function – myFunc1()

Read More
In Python, this code demonstrates how the global variables allow us to access and update their values outside of functions.

Introduction:

In Python, we can declare variables as global so that they can be accessed and updated outside of functions. This allows us to use variables across different scopes within a program. In this code example, we demonstrate how to use the “global” keyword to access and update a global variable.

Code:

#To access any variable outside the function
num = 5
def myfunc1():
 #Prefixing global informs Python to use the updated global 
 #variable num outside the function
 global num 
 print("Accessing num =",num)
 num = 10
 print("num reassigned =",num)
#function ends here
myfunc1()
print("Accessing num outside myfunc1",num)

Logic:

  1. We start by declaring a global variable “num” and assigning it a value of 5.
  2. We define a function “myfunc1”.
  3. Inside the function, we use the “global” keyword to inform Python that we want to use the global variable “num”.
  4. We print the value of “num” inside the function, which is initially 5.
  5. We update the value of “num” to 10.
  6. We print the updated value of “num” inside the function

Output:

>> Accessing num = 5

>> num reassigned = 10

>> Accessing num outside myfunc1 10

 

Read More
Learn about the significance of force sensors and their applications. Discover how to interface a force sensor with Quarky using Pictoblox.

Introduction

A force sensor, also known as a load cell or force transducer, is a device designed to measure the force or load applied to it. It’s used in various applications to quantify the magnitude of forces in different directions. Force sensors are utilized in fields such as engineering, manufacturing, robotics, healthcare, and more.

 

Circuit Diagram

 

Setting up the stage

  1. Go to Sprite button and add bell as a ew sprite.
  2. change the backdrop to  “Sky blue 2”.
  3. Now you have two sprites on the stage “Tobi ” and “Bell”.  change 
  4.  Select “Bell” and set its x value to 0 and y to 150. and size to 50% at the bottom of the stage.
  5. Change the size of Tobi to 80%
  6. Now the final thing adding the sound effect. go to sound block, search for bell, and add ‘Doorbll”.

Code

  1. Open Pictoblox and create a new file.
  2. Go to the board menu and select Quarky.
  3. Now after setting up the stage, select Tobi and start writing the below code for Tobi.
  4. From event palette,  drag ” when flag clicked” block into th scripting area.
  5.  Let’s set the initial location for Tobi in the stage as x=0, y=0. Goto Motion palette and add “goto x() y()” block, feed the value for x and y.
  6. Create a variable as “Initial value ” to store the initial (or normal) value of the sensor.
  7. From Variable palette, drag “Set () to ()” and add after the goto block. select “initial value from the drop-down button.
  8. From Sensor palette of Quarky. place ” read analog sensor () at ()” block in place of 0. and choose generic from the list.
  9. Now add a forever block in the script and put “if-then-else” block inside the forever block.
  10. From operator palette, add grater then operator in the conditional part and compare the current value of the sensor with initial value, as shown below.
  11.  Inside the if section of the block, we have to map the sensor value in such a way that whatever the value sensor is generating, it must get converted from 0-150, so that our Tobi can jump to ring the bell. For this, we are going to use  “change y by ()” block from motion palette and “map () from () ~() to () ~()” block from quarky palette.
  12. place the sensor value in place of 50 and set the required range. as shown below.
  13. With this our Tobi can jump account to the data fetched from the sensor. Since we are trying to ring the bell, so we have to set the condition for this. add a if block after “change y by () block”.
  14.  Here we have to check if the Tobi touches the Bell or not. for this, Goto sensing palette and add “touching ()?” block in the second if block and select bell from the dropdown. as shown below.
  15. If the tobi touches the Bell, we have to play the doorbell sound that we have added during the stage settings. Go to sound palette add block “play () until done” and select doorbell from the list.
  16. In the else part, tobi must glide to its initial location that x=0 y=0, from Motion palette, add “glide for () secs to x() y()” block. 

with this, your script is complete now.

 

Output

Output Gif will be updated soon.

 

Read More
This module contains basic arithmetic operations like addition, subtraction, multiplication, and division that can be performed on numbers.

Introduction:

The “basic_math” module is designed to perform basic arithmetic operations on numbers. It contains user-defined functions for addition, subtraction, multiplication, and division. This module is useful for performing simple calculations in various applications.

Code:

#The requirement is:
 #1. Write a docstring describing the module.
 #2. Write user defined functions as per the specification.
 #3. Save the file.
 #4. Import at shell prompt and execute the functions.
"""
 basic_math Module
 ******************* 
This module contains basic arithmetic operations
that can be carried out on numbers
"""
#Beginning of module
def addnum(x,y):
 return(x + y)
def subnum(x,y):
 return(x - y)
def multnum(x,y):
 return(x * y)
def divnum(x,y):
 if y == 0:
  print ("Division by Zero Error")
 else:
  return (x/y) 
#End of module

Logic:

  1. The module defines four user-defined functions:
    addnum(x, y): This function takes two numbers as input and returns their sum.
    subnum(x, y): This function takes two numbers as input and returns their difference.
    multnum(x, y): This function takes two numbers as input and returns their product.
    divnum(x, y): This function takes two numbers as input and returns their quotient, except when the divisor is zero, in which case it prints a “Division by Zero Error” message.
  2. The “addnum” function adds the two input numbers and returns their sum.
  3. The “subnum” function subtracts the second input number from the first input number and returns the difference.
  4. The “multnum” function multiplies the two input numbers and returns their product.
  5. The “divnum” function checks if the second input number is zero. If it is zero, it prints a “Division by Zero Error” message. Otherwise, it returns the quotient of the first input number divided by the second input number.

Output:

  1. The output of calling any of the functions in the “basic_math” module will depend on the input provided.
  2. For example, calling the “addnum” function with inputs of 5 and 3 will return 8.
  3. Calling the “divnum” function with inputs of 10 and 2 will return 5.
  4. In other case, Calling the “divnum” function with inputs of 10 and 0 will print “Division by Zero Error”.

 

Read More
Learn how to check if a string is a palindrome or not in Python. Use the checkPalin function to validate if a given string is a palindrome.

Introduction:

This code checks whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. The logic of the code is to compare the characters at the beginning and end of the string and move towards the center, checking if they are equal. The output of the code will tell you whether the given string is a palindrome or not.

Code:

#Function to check if a string is palindrome or not
def checkPalin(st):
 i = 0
 j = len(st) - 1
 while(i <= j):
  if(st[i] != st[j]):
    return False
  i += 1
  j -= 1
 return True
#end of function
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
 print("The given string",st,"is a palindrome")
else:
 print("The given string",st,"is not a palindrome")

Logic:

  1. Define a function called “checkPalin” that takes a string as input.
  2. Initialize two variables, “i” and “j”, to keep track of the two ends of the string.
  3. Use a while loop to iterate until “i” is less than or equal to “j”.
  4. Inside the loop, check if the character at index “i” is not equal to the character at index “j”. If they are not equal, return False, indicating that the string is not a palindrome.
  5. If the characters are equal, increment “i” and decrement “j” to move towards the center of the string.
  6. If the loop completes without returning false, it means that the string is a palindrome. Return True.
  7. End the function.
  8. Prompt the user to enter a string.
  9. Call the “checkPalin” function with the input string and store the result in the “result” variable.
  10. Check if the “result” is True. If it is, print that the given string is a palindrome. If not, print that the given string is not a palindrome.

Output:

>> Enter a String: noon

>> The given string noon is a palindrome

>> Enter a String: racecar

>> The given string racecar is a palindrome

Read More
This code will prompt user to enter a string and a character, then it will display the number of occurrences of that character in the string.

Introduction:

In this code, we have a function called charCount() that takes two parameters: ch (the character to be counted) and st (the string in which we want to count the occurrences of the character). The function uses a for loop to iterate through each character in the string. If the character matches the character we are searching for, the count variable is incremented. Finally, the function returns the count. The main part of the code prompts the user to enter a string and a character, calls the charCount() function, and then displays the result.

Code:

#Function to count the number of times a character occurs in a 
#string
def charCount(ch,st):
 count = 0
 for character in st:
  if character == ch:
    count += 1
 return count
#end of function
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,"occurs in the string is:",count)

Logic:

  1. The code takes an input string and a character from the user.
  2. It then calls the charCount() function with these inputs.
  3. The charCount() function counts the number of times the given character occurs in the string using a for loop.
  4. If the character matches the given character, the count variable is incremented.
  5. Finally, the count is returned and displayed as the output.

Output:

Enter a string: Hello World

Enter the character to be searched: o

>> Number of times character o occurs in the string is: 2

Read More
Learn how to replace all the vowels in a string with '*' in Python with this code. Input a string and get the modified string as output.

Introduction:

In this Python code example, we will learn how to replace all the vowels in a given string with ‘*’. This is a common string manipulation task, and this code will provide a solution to achieve it.

Code:

#Function to replace all vowels in the string with '*'
def replaceVowel(st):
 #create an empty string
 newstr = '' 
 for character in st:
  #check if next character is a vowel
  if character in 'aeiouAEIOU':
    #Replace vowel with * 
    newstr += '*' 
  else: 
    newstr += character
 return newstr
#end of function
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:",st)
print("The modified String is:",st1)

Logic:

  1. The code uses a function called ‘replaceVowel’ which takes a string as input.
  2. It iterates through each character in the string and checks if it is a vowel.
  3. If it is a vowel, it replaces the vowel with ‘*’.
  4. Finally, it returns the modified string.
  5. The code then prompts the user to enter a string, calls the function with the input string, and prints the original and modified strings.

Output:

 

Enter a String: Hello World

>> The original String is: Hello World

>> The modified String is: H*ll* W*rld

Read More
This Python program allows users to enter a string and displays it in reverse order starting from the last character.

Introduction:

This program takes a string as input from the user and prints it in reverse order.

Code:

#Program to display string in reverse order
st = input("Enter a string: ")
for i in range(-1,-len(st)-1,-1):
 print(st[i],end='')

Logic:

The program uses a for loop to iterate through the given string in reverse order, starting from the last character, and prints each character using the end parameter of the print() function to avoid printing a new line after each character.

Output:

Enter a string: Hello World

>> dlroW olleH

Read More
Learn to Reverse a string in Python using string reversal function. Simply input a string and get the reversed string as output.

Introduction:

This Python code demonstrates how to reverse a given string using a string reversal function. By inputting a string, you will receive the reversed string as an output. This code is user-friendly and efficient.

Code:

#Function to reverse a string
def reverseString(st):
 newstr = '' #create a new string
 length = len(st)
 for i in range(-1,-length-1,-1):
  newstr += st[i]
 return newstr
#end of function
st = input("Enter a String: ")
st1 = reverseString(st)
print("The original String is:",st)
print("The reversed String is:",st1)

Logic:

  1. The code defines a function called “reverseString” that takes a string as an argument and returns the reversed string.
  2. Inside the function, it creates a new empty string. Calculates the length of the input string.
  3. Uses a for loop to iterate through the input string in reverse order.
  4. The loop starts from -1 and goes up to -length-1, with a step of -1.
  5. During each iteration, it appends the current character of the input string to the new string.
  6. The main code prompts the user to input a string.
  7. Then, it calls the “reverseString” function with the input string as an argument.
  8. Stores the returned reversed string in the variable “st1”.
  9. Finally, it prints the original string and the reversed string as output.

Output:

 

Enter a String: Hello

>>The original String is: Hello

>>The reversed String is: olleH

Read More
Learn how to increment the elements of a list in Python. See the effect of passing a list as a parameter to a function and modifying it.

Introduction:

This Python code demonstrates how to increment the elements of a list by a certain amount. The code defines a function called “increment” that takes a list as an argument and adds 5 to each element in the list. The main function creates a list and then calls the “increment” function, passing the list as a parameter. The code shows the list before and after the function call to demonstrate the effect of modifying a list in a function.

Code:

#Function to increment the elements of the list passed as argument
def increment(list2):
 for i in range(0,len(list2)): 
 #5 is added to individual elements in the list
  list2[i] += 5 
 print('Reference of list Inside Function',id(list2))
#end of function
list1 = [10,20,30,40,50] #Create a list
print("Reference of list in Main",id(list1))
print("The list before the function call")
print(list1)
increment(list1) #list1 is passed as parameter to function
print("The list after the function call")
print(list1)

Logic:

  1. The function “increment” takes a list (list2) as an argument.
  2. It iterates through the elements of the list using a for loop.
  3. Inside the loop, it adds 5 to each element in the list using the += operator.
  4. After modifying all the elements, it prints the reference of the modified list (list2) using the id() function.
  5. The main function creates a list called “list1” with initial values.
  6. It prints the reference of the original list using the id() function.
  7. It prints the original list before calling the “increment” function.
  8. It calls the “increment” function, passing the “list1” as a parameter.
  9. The “increment” function modifies the elements of “list1”.
  10. It prints the modified list after the function call.

Output:

>> Reference of list in Main 140446246092360

>> The list before the function call

>> [10, 20, 30, 40, 50]

>> Reference of list Inside Function 140446246092360

>> The list after the function call

>> [15, 25, 35, 45, 55]

The output shows the reference (id) of the original list before the function call and the reference of the modified list inside the function call. It also displays the original list before calling the function and the modified list after the function call. The elements of the list have been incremented by 5.

Read More
This Python code uses a function to increment the elements of a list and shows the before/after changes in the list ID.

Introduction:

This Python code demonstrates a function that takes a list as an argument and increments its elements. It shows the changes in the ID of the list before and after the function call.

Code:

#Function to increment the elements of the list passed as argument
def increment(list2):
 print("\nID of list inside function before assignment:", 
id(list2))
 list2 = [15,25,35,45,55] #List2 assigned a new list
 print("ID of list changes inside function after assignment:", 
id(list2))
 print("The list inside the function after assignment is:")
 print(list2)
#end of function
list1 = [10,20,30,40,50] #Create a list
print("ID of list before function call:",id(list1))
print("The list before function call:")
print(list1)
increment(list1) #list1 passed as parameter to function
print('\nID of list after function call:',id(list1))
print("The list after the function call:")
print(list1)

Logic:

  1. Define a function called “increment” that takes a list as an argument.
  2. Print the ID of the list inside the function before any assignment.
  3. Assign a new list [15, 25, 35, 45, 55] to the argument list2.
  4. Print the ID of the list after the assignment.
  5. Print the new list inside the function.
  6. Create a list called “list1” with values [10, 20, 30, 40, 50].
  7. Print the ID of the list before the function call.
  8. Print the list before the function call.
  9. Call the “increment” function with “list1” as the parameter.
  10. Print the ID of the list after the function call.
  11. Print the list after the function call.

Output:

>> ID of list before function call: [ID of list1]

>> The list before function call: [10, 20, 30, 40, 50]

>>

>> ID of list inside function before assignment: [ID of list1]

>> ID of list changes inside function after assignment: [ID of new list2]

>> The list inside the function after assignment is: [15, 25, 35, 45, 55]

>>

>> ID of list after function call: [ID of list1]

>> The list after the function call: [10, 20, 30, 40, 50]

Read More
Menu-driven program for list operations perform append, insert, delete (by position/value), modify, sort, and display operations on a list.

Introduction:

This is a menu-driven program written in Python that allows the user to perform various operations on a list. The user can choose options like appending an element, inserting an element at a desired position, deleting an element by its position or value, modifying an element, sorting the list, and displaying the list. The program provides a menu with numbered options for the user to select from.

Code:

#Menu driven program to do various list operations
myList = [22,4,16,38,13] #myList already has 5 elements
choice = 0
while True:
 print("The list 'myList' has the following elements", myList)
 print("\nL I S T O P E R A T I O N S")
 print(" 1. Append an element")
 print(" 2. Insert an element at the desired position")
 print(" 3. Append a list to the given list")
 print(" 4. Modify an existing element")
 print(" 5. Delete an existing element by its position")
 print(" 6. Delete an existing element by its value")
 print(" 7. Sort the list in ascending order")
 print(" 8. Sort the list in descending order")
 print(" 9. Display the list")
 print(" 10. Exit")
 choice = int(input("ENTER YOUR CHOICE (1-10): "))
 #append element
 if choice == 1: 
  element = int(input("Enter the element to be appended: "))
  myList.append(element)
  print("The element has been appended\n")
 #insert an element at desired position
 elif choice == 2: 
  element = int(input("Enter the element to be inserted: "))
  pos = int(input("Enter the position:"))
  myList.insert(pos,element)
  print("The element has been inserted\n")
 #append a list to the given list
 elif choice == 3:
  newList = eval(input( "Enter the elements separated by commas"))
  myList.extend(list(newList))
  print("The list has been appended\n")
 #modify an existing element
 elif choice == 4: 
  i = int(input("Enter the position of the element to be modified: "))
  if i < len(myList):
    newElement = int(input("Enter the new element: "))
    oldElement = myList[i]
    myList[i] = newElement
    print("The element",oldElement,"has been modified\n")
  else:
    print("Position of the element is more than the length of list")
 #delete an existing element by position
 elif choice == 5: 
  i = int(input("Enter the position of the element to be deleted: "))
  if i < len(myList):
    element = myList.pop(i)
    print("The element",element,"has been deleted\n")
  else:
    print("\nPosition of the element is more than the length of list")
 #delete an existing element by value
 elif choice == 6: 
  element = int(input("\nEnter the element to be deleted: "))
  if element in myList:
    myList.remove(element)
    print("\nThe element",element,"has been deleted\n")
  else:
    print("\nElement",element,"is not present in the list")
 #list in sorted order
 elif choice == 7: 
  myList.sort()
  print("\nThe list has been sorted")
 #list in reverse sorted order
 elif choice == 8: 
  myList.sort(reverse = True)
  print("\nThe list has been sorted in reverse order")
 #display the list
 elif choice == 9: 
  print("\nThe list is:", myList)
 #exit from the menu
 elif choice == 10: 
  break
 else:
  print("Choice is not valid")
  print("\n\nPress any key to continue..............")
  ch = input()

Logic:

  1. The program uses a while loop to continuously display the menu and accept the user’s choice.
  2. Based on the choice, the program executes the corresponding operation on the list.
  3. The program includes error handling for invalid choices and checks for the position of elements before modifying or deleting them.

Output:

The program provides feedback for each operation. For example, when appending an element, the program prompts the user to enter the element and informs them that it has been appended. Similarly, for operations like inserting, deleting, modifying, sorting, or displaying the list, the program provides appropriate feedback. If the user enters an invalid choice, the program displays a message stating that it is not valid.

Read More
This code takes input from the user for the number of students and their respective marks, then calculates and displays the average marks.

Introduction:

This Python code calculates the average marks of a given number of students using a function. It takes input from the user for the number of students and their respective marks, and then calculates and displays the average marks.

Code:

#Function to calculate average marks of n students
def computeAverage(list1,n): 
 #initialize total 
 total = 0 
 for marks in list1:
  #add marks to total 
  total = total + marks 
 average = total / n
 return average
#create an empty list 
list1 = [] 
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0,n):
 print("Enter marks of student",(i+1),":")
 marks = int(input())
 #append marks in the list
 list1.append(marks) 
average = computeAverage(list1,n)
print("Average marks of",n,"students is:",average)

Logic:

  1. Define a function ‘computeAverage’ that takes a list of marks and the number of students as input.
  2. Initialize a variable ‘total’ to 0.
  3. Iterate over each mark in the list and add it to the ‘total’ variable.
  4. Calculate the average by dividing the total by the number of students.
  5. Return the average.
  6. Create an empty list ‘list1’.
  7. Take input from the user for the number of students.
  8. Use a loop to iterate for ‘n’ students.
  9. Take input from the user for the marks of each student and append it to ‘list1’.
  10. Call the ‘computeAverage’ function with ‘list1’ and ‘n’ as arguments and store the result in the ‘average’ variable.
  11. Display the average marks to the user.

Output:

>> How many students marks you want to enter: 5

>> Enter marks of student 1 :100

>> Enter marks of student 2 :98

>> Enter marks of student 3 :89

>> Enter marks of student 4 :78

>> Enter marks of student 5 :65

>> Average marks of 5 students is: 86.0

Read More
Learn to write a Python function to check if a number is present in a list using linear search. Get code and understand the logic behind it.

Introduction:

In this Python code example, we’ll learn how to implement a linear search algorithm to check if a number is present in a list. Linear search is a basic search algorithm that sequentially checks each element in a list until a match is found or all the elements have been exhausted. We’ll define a function called `linearSearch()` that takes a number and a list as input and returns the position of the number if it is present in the list, or None if it is not.

Code:

#Function to check if a number is present in the list or not
def linearSearch(num,list1):
 for i in range(0,len(list1)):
  if list1[i] == num: #num is present
    return i #return the position
 return None #num is not present in the list
#end of function
list1 = [] #Create an empty list
print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
 n = int(input())
 list1.append(n) #append numbers to the list
num = int(input("Enter the number to be searched: "))
result = linearSearch(num,list1)
if result is None:
 print("Number",num,"is not present in the list")
else:
 print("Number",num,"is present at",result + 1, "position")

Logic:

  1. Define a function called `linearSearch()` that takes two parameters: `num` and `list1`.
  2. Iterate through the elements in the list using a `for` loop and the `range()` function.
  3. Check if the current element in the list is equal to the provided number (`num`).
  4. If a match is found, return the index (`i`) of the element in the list.
  5. If no match is found after iterating through all the elements, return None.
  6. Create an empty list called `list1`.
  7. Prompt the user for the maximum number of numbers they want to enter in the list.
  8. Use a `for` loop and the `input()` function to add the numbers to the list using the `append()` method.
  9. Prompt the user to enter the number they want to search for in the list.
  10. Call the `linearSearch()` function with the provided number and the list.
  11. Check if the result returned by the function is None.
  12. If it is, print a message stating that the number is not present in the list.
  13. If it is not None, print a message stating that the number is present at the position returned by the function.

Output:

>> How many numbers do you want to enter in the list:5

>> Enter a list of numbers:

1

2

3

4

5

Enter the number to be searched:4

Number 4 is present at 4 position

Read More
Learn how to store and print student records using tuples in Python. See the example code and understand the logic behind it.

Introduction:

This Python code shows how to store records of students in a tuple and print them. Each record contains the student’s serial number, roll number, name, and marks.

Code:

#To store records of students in tuple and print them
st=((101,"Aman",98),(102,"Geet",95),(103,"Sahil",87),(104,"Pawan",79))
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(st)):
 print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])

Logic:

  1. Create a tuple called ‘st’ that contains the student records.
  2. Each record is represented as a tuple itself, with the serial number, roll number, name, and marks as elements.
  3. Print the header of the table, specifying the column names.
  4. Use a for loop to iterate through each record in the ‘st’ tuple.
  5. Inside the loop, print the serial number, roll number, name, and marks of each student.

Output:

>> S_No Roll_No Name Marks

>> 1         101           Aman   98

>> 2        102          Geet       95

>> 3        103          Sahil      87

>> 4        104          Pawan   79

 

Read More
By taking user input for two numbers, the program showcases how to efficiently exchange their values using tuple assignments

Introduction:

This Python program takes two numbers as input and swaps their values using tuple assignments. The program then displays the numbers before and after swapping.

Code:

#Program to swap two numbers 
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print("\nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("\nNumbers after swapping:")
print("First Number:",num1)
print("Second Number:",num2)

Logic:

  1. Prompt the user to enter the first number.
  2. Prompt the user to enter the second number.
  3. Print the numbers before swapping.
  4. Swap the values of the two numbers using tuple assignments.
  5. Print the numbers after swapping.

Output:

Enter the first number: 10
Enter the second number: 5
>>

>> Numbers before swapping:

>> First Number: 10

>> Second Number: 5

>>

>> Numbers after swapping:

>> First Number: 5

>> Second Number: 10

 

Read More
Learn how to use a Python function to calculate the area and circumference of a circle by entering its radius.

Introduction:

This code defines a Python function that calculates the area and circumference of a circle. It takes the radius as input and returns a tuple containing the area and circumference. The user is prompted to enter the radius and the results are displayed on the console.

Code:

#Function to compute area and circumference of the circle.
def circle(r):
 area = 3.14*r*r
 circumference = 2*3.14*r
 #returns a tuple having two elements area and circumference
 return (area,circumference) 
#end of function
radius = int(input('Enter radius of circle: '))
area,circumference = circle(radius)
print('Area of circle is:',area)
print('Circumference of circle is:',circumference)

Logic:

  1. Define the function “circle” that takes the radius as an argument.
  2. Calculate the area using the formula: area = 3.14 * r * r.
  3. Calculate the circumference using the formula: circumference = 2 * 3.14 * r.
  4. Return a tuple containing the area and circumference.
  5. Prompt the user to enter the radius.
  6. Call the function circle with the entered radius and store the returned values in the variables area and circumference.
  7. Print the calculated area and circumference on the console.

Output:

Enter radius of circle: 4

>> Area of circle is: 50.24

>> Circumference of circle is: 25.12

Read More
This program takes n numbers as input from the user and stores them in a tuple, then prints the maximum and minimum numbers from the tuple.

Introduction:

This Python program takes user input for n numbers and stores them in a tuple. It then finds and prints the maximum and minimum numbers from the tuple.

Code:

#Program to input n numbers from the user. Store these numbers 
#in a tuple. Print the maximum and minimum number from this tuple.
numbers = tuple() #create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n): 
 num = int(input())
 #it will assign numbers entered by user to tuple 'numbers'
 numbers = numbers +(num,) 
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))

Logic:

  1. Create an empty tuple ‘numbers’.
  2. Take input from the user for the number of numbers (n) they want to enter.
  3. Use a for loop to iterate ‘n’ times and take input for each number from the user.
  4. Assign the entered numbers to the tuple ‘numbers’ using the tuple concatenation operation.
  5. Print the numbers stored in the tuple.
  6. Find and print the maximum and minimum numbers from the tuple using the max() and min() functions.

Output:

How many numbers you want to enter?: 5

10

15

20

25

30

>>

>> The numbers in the tuple are:

>> (10, 15, 20, 25, 30)

>>

>> The maximum number is:

>> 30

>> The minimum number is:

>> 10

Read More
This program allows you to input the number of employees, their names, and salaries, and then displays the data in a tabular format.

Introduction:

This Python program allows us to create a dictionary to store the names and salaries of employees. By inputting the number of employees, their names, and salaries, the program will display the data in a tabular format.

Code:

#Program to create a dictionary which stores names of the employee
#and their salary
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
 name = input("Enter the name of the Employee: ")
 salary = int(input("Enter the salary: "))
 employee[name] = salary
 count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
 print(k,'\t\t',employee[k])

Logic:

  1. Take input from the user for the number of employees.
  2. Create an empty dictionary called ’employee’.
  3. Use a while loop to iterate through each employee.
  4. Inside the loop, ask the user for the name and salary of each employee and store them in the dictionary.
  5. Increment the count variable.
  6. After the loop, display the data in a tabular format.

Output:

The program will display the names and salaries of the employees in a tabular format.

Enter the number of employees whose data to be stored: 3

Enter the name of the Employee: Ashish

Enter the salary: 20000

Enter the name of the Employee: Farman Ahmed

Enter the salary: 23000

Enter the name of the Employee: Maheshwari Peruri

Enter the salary: 22000

>>

>>

>> EMPLOYEE_NAME SALARY

>> Ashish 20000

>> Farman Ahmed 23000

>> Maheshwari Peruri 22000

 

Read More
This code allows you to input a string and then counts the number of times each character appears in the given string.

Introduction:

This code helps you count the number of times each character appears in a given string. By using a Python dictionary, the code creates a key-value pair where the character is the key and the frequency of its appearance is the corresponding value. The output is displayed by printing each key-value pair.

Code:

#Count the number of times a character appears in a given string
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
 if ch in dic: #if next character is already in the dictionary 
  dic[ch] += 1
 else:
  dic[ch] = 1 #if ch appears for the first time
for key in dic:
 print(key,':',dic[key])

Logic:

  1. Prompt the user to enter a string.
  2. Create an empty dictionary called “dic”.
  3. Iterate through each character in the given string using a for loop.
  4. Check if the character already exists in the “dic” dictionary. If yes, increase its corresponding value by 1.
  5. If the character is not yet in the dictionary, add it as a new key with a value of 1.
  6. Iterate through each key in the dictionary.
  7. Print the key-value pair, separating them with a colon.

Output:

The output of the code will be a list of key-value pairs, where each key represents a character from the input string, and the corresponding value represents the frequency of its appearance in the string.

Enter a string: Hello World

>> H : 1

>> e : 1

>> l : 3

>> o : 2

>> : 1

>> W : 1

>> r : 1

>> d : 1

Read More
All articles loaded
No more articles to load
Table of Contents
[PythonExtension]