Skip to main content

Featured

Write a Python Program to find palindrome of a given string

If you reverse the word then you get the same word that word is palindrome. def   palindrome ( str ):     pointer =  str       rev_str =  reversed (pointer)       if   list (pointer) ==  list (rev_str):         print ( "It is palindrome" )       else :         print ( "It is not palindrome" )  palindrome( 'level' ) palindrome( 'madam' ) palindrome( 'life' ) palindrome( 'refer' ) Output:  It is palindrome It is palindrome It is not palindrome It is palindrome

Typecasting

 Helloo!! Everyone todays topic is bit smaller but its very important lets get into it

TYPECASTING:

                  Sometimes we will get a value in a datatype that we can't work with properly example 10+10 the output must be 20 but we sometimes get 1010 here the interpreter takes the values as string and just combine the values

value = "10"

number = int (value)

Typecasting is done by using the specific data type function. In this case we are converting a string to an integer by using the int keyword.  This is a very important thing and we will need it quite often.

num = str(value)

change int to string

USER INPUT:

Up until now, the only thing we did is to print out text onto the screen. we can also do is to input our own data into the script. In this post, we are going to take a look at user input and how to handle it.

INPUT FUNCTION

In Python we have the function input , which allows us to get the user input from the console application.

name = input ( "Please enter your name:" )
print (name)
Typecasting


Here, the user can input his name and it gets saved into the variable name .We can then call this variable and print it

n1 = input ( "Enter first number: " )
n2 = input ( "Enter second number: " )
sum = n1 + n2
print ( "Result: " , sum)


Typecasting

This example is a bit misleading. It seems like we are taking two numbers
as an input and printing the sum. The problem is that the function input
always returns a string. So when you enter 10, the value of the variable is
“10” , it’s a string.

So, what happens when we add two strings? We just append one to the
other. This means that the sum of “10” and “20” would be “1526”. If we
want a mathematical addition, we need to typecast our variables first.

n1 = input ( "Enter first number: " )
n2 = input ( "Enter second number: " )
n1 = int (n1)
n2 = int (n2)
sum = n1 + n2
print ( "Result: " , sum)

Typecasting

lets see what happens when we don't use typecasting


n1 = input ( "Enter first number: " )
n2 = input ( "Enter second number: " )
sum = n1 + n2
print ( "Result: " , sum)

Typecasting


Always remember that the input function returns a string and you need to typecast it, if you want to do calculations with it.



Comments

Popular Posts