There wil be situations where your program has to interact with the user. For example, you would want to take input from the user and then print once result back.
We can achieve this using the input() and print() functions respectively. For output, we can also use the various methods of the str (string) class. see help(str) for more details. Another common type of input/output is dealing with files. The ability to create, read, and write files is essential to many programs and we will explore this aspect in the next chapter.
a = int(input("Enter a 1st value: ")) b = int(input("Enter a 2nd value: ")) print("Sum of 1st & 2nd value is: " + str(a + b))
Enter a 1st value: 10 Enter a 2nd value: 20 Sum of 1st & 2nd value is: 30
Note: input() function reads user input and store it in an str object so you have to cast the user input to int for the sum
def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input("Enter text:") if (is_palindrome(something)): print("Yes, it is a palindrome") else: print("No, it is not a palindrome")
Enter text:madam Yes, it is a palindrome
How It Works - We use the slicing feature to reverse the text. We've already seen how we can make slices from sequences using the seq[a:b] code starting from position a to position b. We can also provide a third argument that determines the step by which the slicing is done
The default step is 1 because of which it returns a continuous part of the text. Giving a negative step i.e., -1 will return the text in reverse.
The input() function takes a string as argument and displays it it the user. Then it waits for the user to type something and press the return key. Once the user has entered and pressed the return key, the input() function will then return that text the user has entered.
We take that text and reverse it. If the original text and reveresed text are equal, then the text is a palindrome
If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!