Practical Program Exercise 2 odd or even – reverse the string for 12th computer science
PY 2(a) – ODD OR EVEN
QUESTION:
Write a program using functions to check whether a number is even or odd.
AIM:
To check whether a number is even or odd using user defined function
CODING:
def oddeven(a):
if(a%2==0):
return 1
else:
return 0
num = int(input(“Eneter a number:”))
if(oddeven(num)==1):
print(“The given number is even”)
elif(oddeven(num)==0):
print(“The given number is odd”)
OUTPUT:
Enter a number: 7
The given number is odd
Enter a number: 6
The given number is even
RESULT:
The Output was verified successfully
Defining Functions:
- Functions must be defined, to create and use certain functionality.
- There are many built-in functions that comes with the language python (for instance, the print() function), but you can also define your own function.
- When defining functions there are multiple things that need to be noted;
- Function blocks begin with the keyword “def” followed by function name and parenthesis ().
- Any input parameters or arguments should be placed within these parentheses when you define a function.
- The code block always comes after a colon (:) and is indented.
- The statement “return [expression]” exits a function, optionally passing back an expression to the caller.
- A “return “with no arguments is the same as return None.
- To check the given number odd or even.
PY 2(b) – REVERSE THE STRING
QUESTION:
Write a program to create reverse of the given string. For example, “wel” = “lew“.
AIM:
To create a reverse of the given string
CODING:
def rev(str1):
str2=”
i=len(str1)-1
while i>=0:
str2+=str1[i]
i-=1
return str2
word=input(“\n Enter a string:”)
print(“\n The mirror of the string is:”, rev(word))
OUTPUT:
Enter a string: wel
The mirror of the string is: lew
RESULT:
The Output was verified successfully
Accessing characters in a String
- Once you define a string, python allocate an index value for its each character.
- These index values are otherwise called as subscript which are used to access and manipulate the strings.
- The subscript can be positive or negative integer numbers.
- The positive subscript 0 is assigned to the first character and n-1 to the last character, where n is the number of characters in the string.
- The negative index assigned from the last character to the first character in reverse order begins with -1.