[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

Implicit type conversion demonstrates how Python automatically converts integers to floats and displays the result and data type.

Introduction:

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.

Code:

#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))

Logic:

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.

Output:

>> 30.0

>> <class ‘float’>

 

Read More
Learn how to handle runtime errors in Python with an example code. Understand how to avoid runtime errors caused by strings or zero inputs.

Introduction:

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.

Code:

#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)

Logic:

  1. The code snippet in this example takes a user input, which is assigned to the variable num2.
  2. The code then tries to divide num1 by num2 and prints the result.
  3. However, if the user inputs a string or a zero, it would lead to a runtime error.
  4. This code is used to demonstrate how to handle such runtime errors.

Output:

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

Read More
Python program to find the sum of all the positive numbers entered by the user till the user enters a negative number.

Introduction:

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.

Code:

#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)

Logic:

  1. Initialize the variables ‘entry’ and ‘sum1’ to 0.
  2. Print a message asking the user to enter numbers to find their sum, and inform them that a negative number will end the loop.
  3. Start an infinite loop using ‘while True’.
  4. Use the ‘int()’ function to convert the user’s input into an integer and assign it to the variable ‘entry’.
  5. Check if ‘entry’ is less than 0. If it is, break out of the loop.
  6. Add the value of ‘entry’ to the current value of ‘sum1’.
  7. Repeat steps 4-6 until a negative number is entered.
  8. Print the final sum using the ‘print()’ function.

Output:

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

Read More
Find the difference between two input numbers prompts the user to enter two numbers and then calculates and displays their difference."

Introduction:

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.

Code:

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
diff = num1 - num2
print("The difference of",num1,"and",num2,"is",diff)

Logic:

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]”.

Output:

The difference of [num1] and [num2] is [diff]

>>Enter first number: 10

>>Enter second number: 11

>> The difference of 10 and 11 is -1

Read More
We take two numbers as input from user and find their positive difference - absolute value of subtraction between larger and smaller number

Introduction:

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.

Code:

#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)

Logic:

  1. Take the first number as input from the user and convert it to an integer.
  2. Take the second number as input from the user and convert it to an integer.
  3. Use an if-else condition to check if the first number is greater than the second number.
  4. If it is, subtract the second number from the first number and assign the result to the variable “diff”.
  5. If it is not, subtract the first number from the second number and assign the result to the variable “diff”.
  6. Print the message “The difference of [num1] and [num2] is [diff]” to display the positive difference between the two numbers.

Output:

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

Read More
Four functional calculator prompts the user to enter two values and an operator, performs the specified operation and displays the result.

Introduction:

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.

Code:

#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)

Logic:

  1. Initialize the variables result, val1, and val2 to 0.
  2. Prompt the user to enter the first value and store it in the variable val1.
  3. Then Prompt the user to enter the second value and store it in the variable val2.
  4. Also Prompt the user to enter an operator and store it in the variable op.
  5. Use an if-elif-else structure to determine the operation to perform based on the operator:
    1. If the operator is “+”, add the values val1 and val2 together and assign the result to the variable result.
    2. If the operator is “-“, subtract the smaller value from the larger value and assign the result to the variable result.
    3. If the operator is “*”, multiply the values val1 and val2 together and assign the result to the variable result.
    4. If the operator is “/”, check if val2 is not zero. If it is zero, display an error message stating that division by zero is not allowed. Otherwise, divide val1 by val2 and assign the result to the variable result.
    5.  If the operator is not one of the valid options, display an error message stating that the input was wrong and terminate the program.
  6. Display the result to the user.

Output:

Enter value 1: val1
Enter value 2: val2
Enter any one of the operator (+,-,*,/):
>> The result is result

Read More
This Python program compares two numbers and prints the larger one using if-else statements, the program will output which number is larger

Introduction:

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”.

Code:

#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")

Logic:

  1. We define two variables “num1” and “num2” and assign them the values 5 and 6 respectively.
  2. We use an if-else statement to check if “num1” is greater than “num2”.
  3. If it is, we print “first number is larger” and “Bye”.
  4. If not, we print “second number is larger” and “Bye Bye”.

Output:

>> second number is larger

>> Bye Bye

 

Read More
Learn how to use Python to print the first five natural numbers & what we do if we are asked to print the first 100,000 natural numbers?

Introduction:

In this Python code snippet, we will use a simple program to print the first five natural numbers.

Code:

#Print first five natural numbers
print(1)
print(2)
print(3)
print(4)
print(5)

Logic:

  1. The code uses the print() function to display the first five natural numbers.
  2. The numbers are printed one by one in ascending order, starting from 1 and ending at 5.
What should we do if we are asked to print the first 100,000 natural numbers?

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).

Output:

>> 1

>> 2

>> 3

>> 4

>> 5

 

Read More
This code demonstrates a simple way to iterate through the letters of a string and print them individually.

Introduction:

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.

Code:

#Print the characters in word PYTHON using for loop
for letter in 'PYTHON':
 print(letter)

Logic:

  1. The code uses a for loop to iterate through the letters in the string “PYTHON”.
  2. For each letter, the print statement is executed to display it on the console.

Output:

>> P

>> Y

>> T

>> H

>> O

>> N

 

Read More
Learn how to use the for loop in Python to print a sequence of numbers, understand its logic with step-by-step explanations.

Introduction:

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.

Code:

#Print the given sequence of numbers using for loop
count = [10,20,30,40,50]
for num in count:
 print(num)

Logic:

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.

Output:

>> 10

>> 20

>> 30

>> 40

>> 50

Read More
Print all the even numbers in a given sequence. This code uses a for loop and modulus operator to determine if each number is even or odd."

Introduction:

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.

Code:

#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')

Logic:

  1. The code uses a for loop to iterate through each number in the given sequence.
  2. Inside the loop, it uses the modulus operator to check if the number is divisible by 2.
  3. If the remainder is 0, then the number is even, and it is printed along with the message indicating that it is an even number.

Output:

>> 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

 

Read More
Learn how to use Python's assert statement with this program. See its implementation through a function that checks for negative numbers and raises an error if the condition is not met.

Introduction:

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.

Code:

print("use of assert statement")
def negativecheck(number):
  assert(number>=0), "OOPS... Negative Number"
  print(number*number)
print(negativecheck(100))
print(negativecheck(-350))

Logic:

  1. The first line is a simple print statement that displays the text “use of assert statement.”
  2. The function negativecheck(100) is called with the argument 100. The assert statement in this case passes since 100 is greater than or equal to zero.
  3. The function proceeds to calculate the square of 100 (100 * 100) and prints the result: 10000.
  4. Next, the function negativecheck(350) is called with the argument -350. The assert statement fails because -350 is not greater than or equal to zero.
  5. As a result, the AssertionError is raised, and the custom error message “OOPS… Negative Number” is displayed.

Output:

 >>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

Read More
Learn how to implement try and except blocks in Python to gracefully handle division errors. This tutorial guides you through a practical example where we calculate the quotient of two numbers while safeguarding against zero denominators.

Introduction:

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.

Code:

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")

Logic:

  1. The line practicing for try block is printed, which is just an initial message.
  2. The try block is introduced, and the code within this block is attempted to be executed. The user is prompted to input the value of the denominator. if the user provides a valid integer value for the denominator, the program calculates the quotient (numerator/denom).
  3. If the value of denom is not zero, the quotient is printed along with the message Division Performed Successfully.
  4. if the user inputs 0 as the value of denom, the division by zero occurs, resulting in a ZeroDivisionError.
  5. Then denominator as zero not allowed printed.

Output:

>>Practicing for try block

>>Enter the denominator: 0

>>Denominator as ZERO…. not allowed

>>OUTSIDE try..except block

Read More
Learn how to effectively handle division errors in Python using multiple except clauses. This tutorial demonstrates the use of try-except blocks to gracefully manage division by zero and non-integer input scenarios.

Introduction:

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.

Code:

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")

Logic:

  1. The program starts by printing a message indicating that we are practicing with the try block.
  2. The program then prints the message “Handling multiple exceptions” to indicate the topic of this code section.
  3. The try block is introduced, encapsulating the code that may raise error during execution.
  4. The variable numerator is assigned the value 50. The program prompts the user to input the value of the denominator using the input function. The input is then converted to an integer using int(), and the result is stored in the variable denom.
  5. If the user enters a valid integer value for the denominator, the program proceeds to calculate the quotient (numerator/denom). The quotient is printed using print(numerator/denom). The message “Division performed successfully” is printed using print(“Division performed successfully”).

Output:

  >> 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

 

Read More
Master the art of Python exception handling using the try-except-else construct. Learn how to gracefully manage division errors while leveraging the power of the else clause.

Introduction:

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.

Code:

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)

Logic:

  1. Display the message “Handling exception using try…except…else” to indicate the purpose of this code section.
  2. The try block is introduced to encapsulate the code that may raise exceptions during execution.
  3. the variable numerator The program prompts the user to input the value of the denominator using the input function. The input is converted to an integer using int() , and the result is stored in the variable denom .is assigned the value 50
  4. If the user enters a valid integer value for the denominator, the program proceeds to calculate the quotient (numerator/denom).The message “Division performed successfully” is printed, indicating the successful execution of the try block.
  5. if the user enters 0 as the denominator, resulting in a ZeroDivisionError during the division operation.
  6. The except ZeroDivisionError block catches this exception and gracefully.

Output:

    >>Handling exception using try…except…else

>>Enter the denominator: 5

>>Division performed successfully

>>The result of the division operation is 10.0

Read More
Learn how to use Python code to print multiples of 10 in a specified range using "For loop" to iterate through the numbers in a given range

Introduction:

In this Python code, we will be printing multiples of 10 within a specified range.

Code:

#Print multiples of 10 for numbers in a given range
for num in range(5):
 if num > 0:
  print(num * 10)

Logic:

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.

Output:

The code will print the multiples of 10 for all numbers in the given range that are greater than 0.

>>10

>>20

>>30

>>40

Read More
Print the first 5 natural numbers using a while loop, uses a counter variable to control the loop and increment it until the count reaches 5.

Introduction:

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.

Code:

#Print first 5 natural numbers using while loop
count = 1
while count <= 5:
 print(count)
 count += 1

Logic:

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.

Output:

>> 1

>> 2

>> 3

>> 4

>> 5

Read More
Find the factors of a number using a while loop in Python. This code example will help you understand the logic and provide the output.

Introduction:

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.

Code:

#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

Logic:

  1. Accept a number from the user as input.
  2. Initialize the factor variable to 2.
  3. While the factor is less than or equal to half of the number:
    a. Check if the number is divisible by the factor using the modulo operator.
    b. If the number is divisible, print the factor.
    c. Increment the factor by 1.
  4.  Print the number itself as a factor.

Output:

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

Read More
Learn how to use the break statement in a for loop in Python, with a simple program demonstrating its usage.

Introduction:

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.

Code:

#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')

Logic:

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.

Output:

>> 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

 

Read More
This Python program checks whether a given number is prime or not. If the number is less than or equal to 1: we need to execute again!"

Introduction:

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.

Code:

#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!")

Logic:

  1. Take a number as input.
  2. Assume the number is a prime number (flag = 0).
  3. Check if the number is greater than 1.
  4. If yes, iterate from 2 to half of the number.
  5. If the number is divisible by any iteration, update the flag to 1 (not prime) and break the loop.
  6. After the loop, check the flag value:
    a. If flag is 1, print that the number is not a prime number.
    b. If flag is 0, print that the number is a prime number.
  7. If the number is less than or equal to 1, print a message asking the user to enter a different number.

Output:

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!

Read More
Lets write a Python code that prints values from 0 to 6, excluding the number 3. Understand the logic behind the code and see the output."

Introduction:

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.

Code:

#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')

Logic:

  1. We start by initializing the variable “num” to 0.
  2. Using a for loop, we iterate through the range of numbers from 0 to 5 (range(6)).
  3. Inside the loop, we increment the value of “num” by 1 using the expression “num = num + 1”.
  4. We then use an if statement to check if “num” is equal to 3.
  5. If “num” is equal to 3, the continue statement is executed, which skips the remaining lines of code in the loop and moves on to the next iteration of the loop.
  6. If “num” is not equal to 3, the print statement is executed, which displays the value of “num” with the string ‘Num has value ‘.
  7. After the loop ends, the print statement ‘End of loop’ is executed.

Output:

>> Num has value 1

>> Num has value 2

>> Num has value 4

>> Num has value 5

>> Num has value 6

>> End of loop

 

Read More
Learn how to use nested for loops in Python. Understand the logic, see the code output, explore different iterations of the outer/inner loops

Introduction:

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.

Code:

#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")

Logic:

  1. The code starts with an outer loop that iterates three times.
  2. In each iteration, it prints the current iteration number.
  3. Inside the outer loop, there is a nested inner loop that iterates twice.
  4. In each iteration of the inner loop, it prints the current iteration number.
  5. After each inner loop iteration, it prints “Out of inner loop”.
  6. Once all iterations of the inner loop are completed, it continues to the next iteration of the outer loop.
  7. After all iterations of both the outer and inner loops are completed, it prints “Out of outer loop”.

Output:

>> 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

 

Read More
Generating a pattern consists of rows starting from 1 and increasing by 1 with each row for a number input by the user.

Introduction:

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.

Code:

#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()

Logic:

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.

Output:

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

 

Read More
Learn to use nested loops to find prime numbers between 2 to 50. Prime numbers are numbers that are divisible only by 1 and themselves.

Introduction:

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.

Code:

#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!!")

Logic:

  1. The code initializes a variable “num” with a value of 2.
  2. It then uses a for loop to iterate through the numbers from 2 to 50.
  3. Within the for loop, a variable “j” is set to 2.
  4. The code then enters a while loop that checks if “j” is less than or equal to half of “i”.
  5. If the condition is true, it checks if “i” is divisible by “j”.
  6. If a factor is found, the code breaks out of the while loop.
  7. If the loop completes without finding a factor, it means that “i” is a prime number.

Output:

>> 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!!

Read More
This Python program uses a for loop nested inside an if...else block to calculate the factorial of a given number.

Introduction:

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.

Code:

#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)

Logic:

  1. Prompt the user to enter a number.
  2. Initialize a variable “fact” to 1.
  3. Check if the number is negative. If so, print a message stating that the factorial does not exist for negative numbers.
  4. If the number is 0, print a message stating that the factorial of 0 is 1.
  5. If the number is positive, use a for loop to iterate from 1 to the given number and calculate the factorial by multiplying the current value of “fact” with the loop variable “i”.

Output:

Enter a number: 3

>> factorial of 3 is 6

Read More
This program calculates the canvas area based on tent dimensions, computes the canvas cost, adds tax, and determines the net payable amount.

Introduction:

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.

Code:

#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)

Logic:

  1. The program takes inputs for the dimensions of the tent (height, radius, and slant height of the conical part) and
  2. Calculates the area of the canvas needed by adding the areas of the conical and cylindrical parts.
  3. It then takes input for the cost of 1 square meter of canvas and calculates the total cost of the canvas.
  4. Finally, it adds tax to the total cost to determine the net amount payable by the customer.

Output:

>> 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

Read More
Python program to compute tent cost with cylindrical and conical parts. Calculates total canvas area and final payable amount including tax.

Introduction:

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.

Code:

#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))

Logic:

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.

Output:

>> 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^2

Enter cost of 1 m^2 canvas in rupees: 50
>> Total cost of canvas before tax = 4082.0

>> Net amount payable (including tax) = 4816.76

Read More
Learn how to write a Python function that accepts two numbers, calculates their sum, and displays the result.

Introduction:

This Python code demonstrates how to create a function that accepts two numbers from the user, calculates their sum, and displays the result.

Code:

#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()

Logic:

  1. Define the function addnum() to add two numbers.
  2. Inside the addnum() function:
    1. Prompt the user to enter the first number and store it in the variable fnum.
    2. Prompt the user to enter the second number and store it in the variable snum.
    3. Calculate the sum of fnum and snum and store it in the variable sum.
    4. Display the sum with a message showing the values of fnum, snum, and the result sum.
  3. Call the addnum() function, which will execute the above steps when the code is run.

Output:

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

Read More
Sum of first n natural numbers. Efficient and concise solution to calculate and display the sum. Ideal for developers of all levels.

Introduction:

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.

Code:

#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

Logic:

  1. The program defines a function sumSquares that takes n as a parameter.
  2. It initializes a variable sum to 0.
  3. Then, it uses a for loop to iterate from 1 to n and adds each number to the sum.
  4. After the loop, it displays the sum of the first n natural numbers.
  5. The main part of the program prompts the user to enter the value for n, reads it using the input function, and calls the sumSquares function with the provided value of n.

Output:

 

Enter the value for n: 12

>> The sum of first 12 natural numbers is: 78

Read More
Python code: Adds 5 to user input using a function. Displays id() before and after the call to check memory location change.

Introduction:

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.

Code:

#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)

Logic:

  1. The code defines a function named incrValue that takes a parameter num.
  2. It first displays the value and id() of the parameter before incrementing it by 5.
  3. Then, it displays the new value and id() of the parameter to check if it has been assigned a new memory location.
  4. The main part of the code prompts the user to enter a number
  5. Then displays the id() of the argument, and calls the incrValue function with the number as the argument.

Output:

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

 

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