Shell VS Python Examples


1. Use for loops to display the natural numbers from 1 to 50.
## Shell Script ##
for i in {1..50}
do 
   echo $i
done
--------------------------------------
for ((i=1; i<=50; i++))
do 
   echo $i
done

## Python Script ##
for i in range(1,51):
    print(i)

2. Read the input from user and print.
## Shell Script ##
read –p “Enter Your Name : ” name
echo “${name}”

## Python Script ##
name = input(“Enter Your Name : ”)
print(name)

3. Find the largest of three number.
## Shell Script ##
read -p "Enter Num1 : " num1
read -p "Enter Num2 : " num2
read -p "Enter Num3 : " num3

if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]
then
    echo "Largest number is ${num1} "
elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]
then
    echo "Largest number is ${num2} "
else
    echo "Largest number is ${num3} "
fi

## Python Script ##
num1 = int(input("Enter Num1 :))
num2 = int(input("Enter Num2 :))
num3 = int(input("Enter Num3 :))

if num1 > num2 and num1 > num3:
        largest = num1
elif num2 > num1 and num2 > num3:
        largest = num2
else:
        largest = num3
print("Largest number is : ", largest)

4. Find the given number is prime or not.
 ## Shell Script ##
read -p "Enter a number: " num
if [ $num -gt 1 ]
then
   for i in `seq 2 $(($num-1))`
   do
      if (($num % $i == 0 ))
      then
        echo "$num is not a prime number"
        exit
      fi
   done
     echo "$num is a prime number"
else
   echo "$num is a not prime number"
fi

## Python Script ##
num = int(input("Any number number : "))
if num > 1:
    for i in range(2,num):
        if (num%2)==0:
          print(num,"is not a prime number")
          break
    else:
       print(num,"is a prime number")
else:
    print(num,"is not a prime number")

5. Find the length of string and specific words from the given string.
## Shell Script ##
str="Hello World, This is Testing!"
length=${#str}
echo "Length of str is $length"
 
echo "Printing the 11 characters starting from 6th position"
echo ${str:6:11}
echo "Printing the 7 characters starting from 21st position"
echo ${str:21:7}
echo "Printing entire string"
echo ${str:0}

## Python Script ##
str = "Hello World, This is Testing!"
print("Lenght of str is ", len(str))
 
print("Printing charachetrs from 6th to 10th position ", str[6:11])
print("Printing charachetrs from 21st to 27th position ", str[21:27])
print("Printing entire string ", str[0:])

6. Use for loops to display the numbers from 0 to 50 incremented by 2.
## Shell Script ##
for i in {0..50..2}
do
   echo $i
done
--------------------------------------
for i in $(seq 0 2 50)
do
   echo $i
done
 
## Python Script ##
for i in range(0,51,2):
    print(i)