The function initialize the pick and place robot with the specified orientation:
- Horizontal:
- Vertical:
Function Definition: initialisepickplace(orientation = "HORIZONTAL")
Name | Type | Description | Expected Values | Default Value |
---|---|---|---|---|
orientation | string | The orientation of the robot. | "HORIZONTAL" or "VERTICAL" | "HORIZONTAL" |
The function initialize the pick and place robot with the specified orientation:
This Python code illustrates the concept of implicit type conversion in Python. It showcases how Python converts integers to floats automatically and displays the result along with the data type.
#Implicit type conversion from int to float
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float and an integer
print(sum1)
print(type(sum1))
1. The code initializes two variables: ‘num1’ with the value 10 (an integer) and ‘num2’ with the value 20.0 (a float).
2. The code performs addition on ‘num1’ and ‘num2’ and assigns the result to ‘sum1’.
3. The code then prints the value of ‘sum1’ and its data type.
>> 30.0
>> <class ‘float’>
In this tutorial, we will discuss an example of handling runtime errors in Python. Specifically, we will look into how to handle errors caused by user inputs of strings or zero values. We will provide a code snippet that demonstrates the issue and discuss ways to avoid such runtime errors.
#Runtime Errors Example
num1 = 10.0
num2 = int(input("num2 = "))
#if user inputs a string or a zero, it leads to runtime error
print(num1/num2)
The output of this code snippet will vary depending on the user input. If the user inputs a valid non-zero number, the program will divide num1 by num2 and print the result. If the user inputs a zero or a string, a runtime error will occur.
if user inputs a string, say apple
ValueError: invalid literal for int() with base 10: ‘apple’
if user inputs a zero
ZeroDivisionError: float division by zero
if user inputs a float, say 3.0
ValueError: invalid literal for int() with base 10: ‘3.0’
if user inputs an int, say 3
3.3333333333333335
In this Python program, we will find the sum of all positive numbers entered by the user until the user enters a negative number. We will use a while loop to continuously input numbers from the user and add them to the sum1 variable until a negative number is entered.
#Find the sum of all the positive numbers entered by the user till the user enters a negative number.
entry = 0
sum1 = 0
print("Enter numbers to find their sum, negative number ends the loop:")
while True:
#int() typecasts string to integer
entry = int(input())
if (entry < 0):
break
sum1 += entry
print("Sum =", sum1)
Sum = (sum of positive numbers entered by the user)
> Enter numbers to find their sum, negative number ends the loop:1
2
3
4
5
6
7
8
9
0
-1
>> Sum = 45
In this Python program, we prompt the user to enter two numbers and then calculate the difference between them. The program then displays the calculated difference.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
diff = num1 - num2
print("The difference of",num1,"and",num2,"is",diff)
1. Prompt the user to enter the first number.
2. Prompt the user to enter the second number.
3. Calculate the difference between the two numbers using the subtraction operator.
4. Print the message “The difference of [num1] and [num2] is [diff]”.
The difference of [num1] and [num2] is [diff]
>>Enter first number: 10
>>Enter second number: 11
>> The difference of 10 and 11 is -1
In this Python program, we are going to find the positive difference between two numbers. We will take these two numbers as input from the user and calculate their positive difference using an if-else condition. The positive difference is the absolute value of the subtraction between the larger number and the smaller number.
#Program to print the positive difference of two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference of",num1,"and",num2,"is",diff)
Enter first number: 19
Enter second number: 17
>> The difference of 19 and 17 is 2
Enter first number: 17
Enter second number: 19
>> The difference of 17 and 19 is 2
This Python program allows users to perform basic arithmetic calculations using a four function calculator. It prompts the user to enter two values and an operator (+, -, *, or /), performs the specified operation, and displays the result. If the user inputs an invalid operator or attempts to divide by zero, an appropriate error message is displayed.
#Program to create a four function calculator
result = 0
val1 = float(input("Enter value 1: "))
val2 = float(input("Enter value 2: "))
op = input("Enter any one of the operator (+,-,*,/): ")
if op == "+":
result = val1 + val2
elif op == "-":
if val1 > val2:
result = val1 - val2
else:
result = val2 - val1
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 == 0:
print("Error! Division by zero is not allowed. Program terminated")
else:
result = val1/val2
else:
print("Wrong input,program terminated")
print("The result is ",result)
Enter value 1: val1
Enter value 2: val2
Enter any one of the operator (+,-,*,/):
>> The result is result
In this Python program, we will compare two numbers and determine the larger of the two. We will use an if-else statement to check if the first number is larger than the second number. If it is, the program will print “first number is larger”. Otherwise, it will print “second number is larger”.
#Program to find larger of the two numbers
num1 = 5
num2 = 6
if num1 > num2: #Block1
print("first number is larger")
print("Bye")
else: #Block2
print("second number is larger")
print("Bye Bye")
>> second number is larger
>> Bye Bye
In this Python code snippet, we will use a simple program to print the first five natural numbers.
#Print first five natural numbers
print(1)
print(2)
print(3)
print(4)
print(5)
Writing 100,000 print statements would not be an efficient solution. It would be tedious and not the best way to do the task. Writing a program having a loop or repetition is a better solution.
The program logic is given below:
1. Take a variable, say count, and set its value to 1.
2. Print the value of count.
3. Increment the variable (count += 1).
4. Repeat steps 2 and 3 as long as count has a valueless than or equal to 100,000 (count <= 100,000).
>> 1
>> 2
>> 3
>> 4
>> 5
This Python code snippet shows you how to use a for loop to print each character of the word PYTHON separately. It is a simple example that demonstrates the process of iterating through a string and accessing each character.
#Print the characters in word PYTHON using for loop
for letter in 'PYTHON':
print(letter)
>> P
>> Y
>> T
>> H
>> O
>> N
In this Python code example, we will demonstrate how to use a for loop to print a sequence of numbers. The given sequence of numbers is [10, 20, 30, 40, 50]. We will iterate over each number in the sequence using the for loop and print it.
#Print the given sequence of numbers using for loop
count = [10,20,30,40,50]
for num in count:
print(num)
1. We start by defining a list of numbers called “count” with the values [10, 20, 30, 40, 50].
2. We use a for loop to iterate over each number in the “count” list.
3. On each iteration, the current number is assigned to the variable “num”.
4. We use the “print” function to output the current number.
5. The loop continues until all numbers in the “count” list have been printed.
>> 10
>> 20
>> 30
>> 40
>> 50
In this Python code, we will be printing all the even numbers in a given sequence. We will use a for loop to iterate through each number and check if it is divisible by 2 (which means it is even). If the number is even, we will print it along with a message indicating that it is an even number.
#Print even numbers in the given sequence
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
if (num % 2) == 0:
print(num,'is an even Number')
>> 2 is an even Number
>> 4 is an even Number
>> 6 is an even Number
>> 8 is an even Number
>> 10 is an even Number
In Python, the assert statement is a powerful debugging tool used to check if a condition is true during the execution of a program. It allows you to catch errors early by validating assumptions and helps in debugging the code effectively. In this tutorial, we’ll explore the practical use of the assert statement by creating a function that checks for negative numbers and raises an error with a custom message if the condition is not met.
print("use of assert statement")
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print(negativecheck(100))
print(negativecheck(-350))
>>use of assert statement
>>10000
>>None
Traceback (most recent call last):
File “<file_name>”, line 6, in <module>
print(negativecheck(-350))
File “<file_name>”, line 4, in negativecheck
assert(number>=0), “OOPS… Negative Number”
AssertionError: OOPS… Negative Number
In Python, the try and except blocks provide a way to handle exceptions and errors gracefully. They allow you to protect your code from crashing when an unexpected situation arises. In this tutorial, we will explore the use of try and except blocks through a program that calculates the quotient of two numbers. We will ensure that the denominator is not zero and handle the ZeroDivisionError gracefully. By the end of this guide, you’ll have a solid understanding of how to use try and except to make your Python programs more robust.
print("Practicing for try block")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print(quotient)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO.... not allowed")
print("OUTSIDE try..except block")
>>Practicing for try block
>>Enter the denominator: 0
>>Denominator as ZERO…. not allowed
>>OUTSIDE try..except block
Exception handling is a crucial skill for writing reliable Python code. In this tutorial, we will explore the use of multiple except clauses within try-except blocks to handle various types of exceptions. Specifically, we’ll focus on division operations and demonstrate how to handle zero denominators and invalid input (non-integer values) gracefully. By the end of this guide, you’ll be equipped to handle multiple exceptions efficiently in your Python programs.
print("Handling multiple exceptions")
try:
numerator=50
denom=int(input("Enter the denominator: "))
print(numerator/denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
>> Handling Multiple Exceptions
>>Enter the denominator: 5
>>10.0
>>Division performed successfully
>>Enter the denominator: 0
>>Denominator as ZERO is not allowed
>>Enter the denominator: abc
>>Only INTEGERS should be entered
Exception handling is a crucial skill in Python programming, ensuring smooth execution and robustness. In this tutorial, we will explore the use of try-except-else to manage division errors effectively. By incorporating the else clause, you can execute code blocks that depend on successful try blocks. Follow along with the provided example to gain a deeper understanding of handling exceptions in Python.
print("Handling exception using try...except...else")
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
else:
print("The result of division operation is ", quotient)
>>Handling exception using try…except…else
>>Enter the denominator: 5
>>Division performed successfully
>>The result of the division operation is 10.0
In this Python code, we will be printing multiples of 10 within a specified range.
#Print multiples of 10 for numbers in a given range
for num in range(5):
if num > 0:
print(num * 10)
We will use a for loop to iterate through the numbers in the given range.
Then, we will check if the number is greater than 0.
If it is, we will multiply it by 10 and print the result.
The code will print the multiples of 10 for all numbers in the given range that are greater than 0.
>>10
>>20
>>30
>>40
This Python code demonstrates how to use a while loop to print the first 5 natural numbers. A counter variable is initialized to 1 and incremented by 1 in each iteration until it reaches 5.
#Print first 5 natural numbers using while loop
count = 1
while count <= 5:
print(count)
count += 1
1. Initialize the counter variable ‘count’ to 1.
2. Use a while loop to iterate until ‘count’ is less than or equal to 5.
3. Inside the while loop, print the current value of ‘count’.
4. Increment ‘count’ by 1 in each iteration.
>> 1
>> 2
>> 3
>> 4
>> 5
This code example demonstrates how to find the factors of a given number using a while loop in Python. By entering a number, the program will display all the factors of that number.
#Find the factors of a number using while loop
num = int(input("Enter a number to find its factor: "))
print (1, end=' ') #1 is a factor of every number
factor = 2
while factor <= num/2 :
if num % factor == 0:
#the optional parameter end of print function specifies the delimeter
#blank space(' ') to print next value on same line
print(factor, end=' ')
factor += 1
print (num, end=' ') #every number is a factor of itself
The program will display all the factors of the entered number. The factors will be printed on a single line, separated by a blank space.
>> 1 2 3 4 6 12
In this program, we are demonstrating the use of the break statement in a loop in Python. The break statement allows us to exit the loop prematurely if a certain condition is met.
#Program to demonstrate the use of break statement in loop
num = 0
for num in range(10):
num = num + 1
if num == 8:
break
print('Num has value ' + str(num))
print('Encountered break!! Out of loop')
1. Initialize the variable “num” with a value of 0.
2. Start a for loop with the range of 10, indicating that it will run for 10 iterations.
3. Inside the loop, increment the value of “num” by 1.
4. Check if the value of “num” is equal to 8.
5. If the condition is met, use the break statement to exit the loop.
6. Print the current value of “num” inside the loop.
7. After the loop, print a message indicating that the break statement has been encountered and the program is out of the loop.
>> Num has value 1
>> Num has value 2
>> Num has value 3
>> Num has value 4
>> Num has value 5
>> Num has value 6
>> Num has value 7
>> Encountered break!! Out of loop
In this Python program, we take a number as input from the user and check whether it is a prime number or not. We assume that the number is a prime number by default and then iterate from 2 to half of the number. If the number is divisible by any of the iterations, we flag it as not prime. Finally, we output whether the number is prime or not.
#Write a Python program to check if a given number is prime or not.
num = int(input("Enter the number to be checked: "))
flag = 0 #presume num is a prime number
if num > 1 :
for i in range(2, int(num / 2)):
if (num % i == 0):
flag = 1 #num is a not prime number
break #no need to check any further
if flag == 1:
print(num , "is not a prime number")
else:
print(num , "is a prime number")
else :
print("Entered number is <= 1, execute again!")
Enter the number to be checked: 5
>> 5 is a prime number
Enter the number to be checked: 9
>> 9 is not a prime number
Enter the number to be checked: 1
>> Entered number is <= 1, execute again!
In this Python code, we will learn how to use a for loop to print values from 0 to 6, excluding the number 3. We will explain the logic behind the code and show the output.
#Prints values from 0 to 6 except 3
num = 0
for num in range(6):
num = num + 1
if num == 3:
continue
print('Num has value ' + str(num))
print('End of loop')
>> Num has value 1
>> Num has value 2
>> Num has value 4
>> Num has value 5
>> Num has value 6
>> End of loop
This Python code demonstrates the use of nested for loops to perform iterations and looping. The code includes an outer loop and an inner loop, showcasing the logic of how they work together to execute a series of print statements. The output of the code is provided to help understand the flow of the loops.
#Demonstrate working of nested for loops
for var1 in range(3):
print( "Iteration " + str(var1 + 1) + " of outer loop")
for var2 in range(2): #nested loop
print(var2 + 1)
print("Out of inner loop")
print("Out of outer loop")
>> Iteration 1 of outer loop
>> 1
>> 2
>> Out of inner loop
>> Iteration 2 of outer loop
>> 1
>> 2
>> Out of inner loop
>> Iteration 3 of outer loop
>> 1
>> 2
>> Out of inner loop
>> Out of outer loop
This Python program takes a number input from the user and generates a pattern based on the given number. The pattern starts with 1 and increases by 1 with each row.
#Program to print the pattern for a number input by the user
#The output pattern to be generated is
#1
#1 2
#1 2 3
#1 2 3 4
#1 2 3 4 5
num = int(input("Enter a number to generate its pattern = "))
for i in range(1,num + 1):
for j in range(1,i + 1):
print(j, end = " ")
print()
The program uses nested for loops to print the pattern. The outer loop iterates from 1 to the given number. The inner loop iterates from 1 to the current value of the outer loop. In each iteration, the inner loop prints the value of the inner loop counter with a space, and at the end of each inner loop, a new line is printed.
The program generates the pattern based on the user’s input. The pattern consists of rows starting from 1 and increasing by 1 with each row. Each row contains the numbers from 1 to the current row number separated by spaces.
Enter a number to generate its pattern = 5
>> 1
>> 1 2
>> 1 2 3
>> 1 2 3 4
>> 1 2 3 4 5
This Python code demonstrates the use of nested loops to find prime numbers between the range of 2 to 50. Prime numbers are numbers that are divisible only by 1 and themselves.
#Use of nested loops to find the prime numbers between 2 to 50
num = 2
for i in range(2, 50):
j= 2
while ( j <= (i/2)):
if (i % j == 0): #factor found
break #break out of while loop
j += 1
if ( j > i/j) : #no factor found
print ( i, "is a prime number")
print ("Bye Bye!!")
>> 2 is a prime number
>> 3 is a prime number
>> 5 is a prime number
>> 7 is a prime number
>> 11 is a prime number
>> 13 is a prime number
>> 17 is a prime number
>> 19 is a prime number
>> 23 is a prime number
>> 29 is a prime number
>> 31 is a prime number
>> 37 is a prime number
>> 41 is a prime number
>> 43 is a prime number
>> 47 is a prime number
>> Bye Bye!!
This Python program calculates the factorial of a given number using a for loop nested inside an if…else block. It first checks if the number is negative, positive, or zero, and then calculates the factorial accordingly.
#The following program uses a for loop nested inside an if..else
#block to calculate the factorial of a given number
num = int(input("Enter a number: "))
fact = 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):
fact = fact * i
print("factorial of ", num, " is ", fact)
Enter a number: 3
>> factorial of 3 is 6
This Python program calculates the payable amount for a tent based on the dimensions provided. It calculates the area of the canvas needed, the cost of the canvas, and adds tax to determine the net amount payable by the customer.
#Program to calculate the payable amount for the tent without
#functions
print( "Enter values for the cylindrical part of the tent in meters\n")
h = float(input("Enter height of the cylindrical part: "))
r = float(input("Enter radius: "))
l = float(input("Enter the slant height of the conical part in meters: "))
csa_conical = 3.14*r*l #Area of conical part
csa_cylindrical = 2*3.14*r*h #Area of cylindrical part
#Calculate area of the canvas used for making the tent
canvas_area = csa_conical + csa_cylindrical
print("The area of the canvas is",canvas_area,"m^2")
#Calculate cost of the canvas
unit_price = float(input("Enter the cost of 1 m^2 canvas: "))
total_cost= unit_price * canvas_area
print("The total cost of canvas = ",total_cost)
#Add tax to the total cost to calculate net amount payable by the customer
tax = 0.18 * total_cost;
net_price = total_cost + tax
print("Net amount payable = ",net_price)
>> Enter values for the cylindrical part of the tent in meters
>> Enter height of the cylindrical part: 3
>> Enter radius: 6
>> Enter the slant height of the conical part in meters: 8
>> The area of the canvas is 263.76 m^2
>> Enter the cost of 1 m^2 canvas: 26
>> The total cost of canvas = 6857.76
>> Net amount payable = 8092.156800000001
This Python program calculates the cost of a tent using the dimensions of its cylindrical and conical parts. The program prompts the user to enter the height and radius of the cylindrical part, as well as the slant height of the conical part. It then calculates the total canvas area and the total cost of the canvas before tax. Finally, it calculates the final amount payable, including tax.
#Program to calculate the cost of tent
#function definition
def cyl(h,r):
area_cyl = 2*3.14*r*h #Area of cylindrical part
return(area_cyl)
#function definition
def con(l,r):
area_con = 3.14*r*l #Area of conical part
return(area_con)
#function definition
def post_tax_price(cost): #compute payable amount for the tent
tax = 0.18 * cost;
net_price = cost + tax
return(net_price)
print("Enter values of cylindrical part of the tent in meters:")
h = float(input("Height: "))
r = float(input("Radius: "))
csa_cyl = cyl(h,r) #function call
l = float(input("Enter slant height of the conical area in meters: "))
csa_con = con(l,r) #function call
#Calculate area of the canvas used for making the tent
canvas_area = csa_cyl + csa_con
print("Area of canvas = ",canvas_area," m^2")
#Calculate cost of canvas
unit_price = float(input("Enter cost of 1 m^2 canvas in rupees: "))
total_cost = unit_price * canvas_area
print("Total cost of canvas before tax = ",total_cost)
print("Net amount payable (including tax) = ",post_tax_price(total_cost))
The program uses three functions: cyl() calculates the area of the cylindrical part, con() calculates the area of the conical part, and post_tax_price() computes the final amount payable including tax. The program takes user input for the dimensions and cost of the canvas. It then calls the functions and performs the necessary calculations to output the canvas area, the total cost before tax, and the final amount payable including tax.
>> Enter values of cylindrical part of the tent in meters:
Height: 5
Radius: 2
Enter slant height of the conical area in meters: 3
>> Area of canvas = 81.64 m^2Enter cost of 1 m^2 canvas in rupees: 50
>> Total cost of canvas before tax = 4082.0>> Net amount payable (including tax) = 4816.76
This Python code demonstrates how to create a function that accepts two numbers from the user, calculates their sum, and displays the result.
#Function to add two numbers
#The requirements are listed below:
#1. We need to accept 2 numbers from the user.
#2. Calculate their sum
#3. Display the sum.
#function definition
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of ",fnum,"and ",snum,"is ",sum)
#function call
addnum()
addnum()
to add two numbers.addnum()
function:
fnum
.snum
.fnum
and snum
and store it in the variable sum
.fnum
, snum
, and the result sum
.addnum()
function, which will execute the above steps when the code is run.The sum of [first number] and [second number] is [sum]
Enter first number: 10
Enter second number: 5
>> The sum of 10 and 5 is 15
This Python program calculates and displays the sum of the first n natural numbers. The value of n is passed as an argument to the program. The program uses a for loop to iterate from 1 to n and adds each number to the sum. Finally, it prints the sum of the first n natural numbers.
#Program to find the sum of first n natural numbers
#The requirements are:
#1. n be passed as an argument
#2. Calculate sum of first n natural numbers
#3. Display the sum
#function header
def sumSquares(n): #n is the parameter
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is: ",sum)
num = int(input("Enter the value for n: "))
#num is an argument referring to the value input by the user
sumSquares(num) #function call
Enter the value for n: 12
>> The sum of first 12 natural numbers is: 78
This Python code shows how to add 5 to a user input number using a function. It also displays the id() of the argument before and after the function call to check if the parameter is assigned a new memory location.
#Function to add 5 to a user input number
#The requirements are listed below:
#1. Display the id()of argument before function call.
#2. The function should have one parameter to accept the argument
#3. Display the value and id() of the parameter.
#4. Add 5 to the parameter
#5. Display the new value and id()of the parameter to check whether the parameter is assigned a new memory location or not.
def incrValue(num):
#id of Num before increment
print("Parameter num has value:",num,"\nid =",id(num))
num = num + 5
#id of Num after increment
print("num incremented by 5 is",num,"\nNow id is ",id(num))
number = int(input("Enter a number: "))
print("id of argument number is:",id(number)) #id of Number
incrValue(number)
Enter a number: 10
> id of argument number is: 140732724484144
> Parameter num has value: 10
> id = 140732724484144
> num incremented by 5 is 15
> Now id is 140732724484304
Copyright 2025 – Agilo Research Pvt. Ltd. All rights reserved – Terms & Condition | Privacy Policy