Friday, January 11, 2019

Python - Learn by example - Variables and Function

# define variables
x=5
y=6
#x=y
y=x

print ("x = ", x)
print ("y =", y)

===============

a='Hello '
b='World !!!'

c=a + b
print("To put together a + b, we get:- ", c)

# Assigning numerical values
x=5
y=2
z=x+y
z1=x-y
z2=x*y
z3=x/2

print("The value stored on memory location is", id(a))
print("The Sum of", x, "and", y, "is", z)
print("The sub of x and y is", z1)
print ("The multiplicaiton of", x, "and", y, "is", z2)
print ("The division of x and y is", z3)

# Using function


def mymath1():
    # define variables
    x=5
    y=2
    z=x+y
    z1=x-y
    z2=x*y
    z3=x/2
    print("The Sum of", x, "and", y, "is", z)
    print("The sub of x and y is", z1)
    print ("The multiplicaiton of", x, "and", y, "is", z2)
    print ("The division of x and y is", z3)

# calling the function
mymath1()


# Input from user, accepts a input value from user
a=input('Please enter a value: ')

print("User input is",a )

# Use function to accept value from user input
def domath():
    a=input('Please enter a number you like: ')
    b=input('Please enter a second value: ')
    c=a+b
    print("Output is as a string ")
    print("The sum of", a, "and", a, "is: ", c)
 
domath()

# Here you will get out put like below
# Please enter a number you like: 5
# Please enter a second value: 2
# The sum of 5 and 5 is:  52
# The reason is it treats these value as string so
# the program put both value together.
# if you want to perform mathematical operation, do the following,
#
def domymath():
    a=int(input("Please enter a number: "))
    b=int(input("Please enter another number "))

    c=a+b
    print("Output as numerical value")
    print("The sum of", a, "and", b, "is: ", c)

domymath()


# ========================================
# Playing with string

a=input('Please enter a string you like: ')
print ("You entered: ", a)
# Use function to accept value from user input as string
def dostring():
    a=input('Please enter a string you like: ')
    b=input('Please enter a second value: ')
    c=a+b
    print("Output is as a string")
    print("The sum of", a, "and", a, "is: ", c)
 
dostring()

# Here we will use decimal value for mathematical operation.
#
def domyfloat():
    # enable 2 lines below and test it. it will throw error if you pass
    # letter because letters are treated as string...
    # a=int(input("Please enter a string: "))
    # b=int(input("Please enter another non-number: "))
    # so you have to change integer to fload to change number to string.
    a=float(input("Please enter a folating value here: "))
    b=float(input("Please enter another floating value link 3.2: "))

    c=a+b
    print("Output as floating point value")
    print("The sum of", a, "and", b, "is: ", c)

domyfloat()



No comments:

Post a Comment