Python Basic programs
print("Hello, World!") #This is a comment.
print("Hello, World!")
"""This is a
Variables
multiline docstring.""" x=5
print("Hello, World!") y = "John"
print(x)
print(y)
x = "Python"
x = "Python "
y = "is" y = "is "
z = "awesome" z = "awesome"
print(x, y, z) print(x + y + z)
o/p :Python is awesome o/p :Python is awesome
verify type of object
Convert from one type to another:
x=1
x = 1 # int
y = 2.8 y = 2.8 # float
z = 1j # complex
z = 1j
#convert from int to float:
a = float(x)
print(type(x))
print(type(y)) #convert from float to int:
b = int(y)
print(type(z))
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
arithmetical operations
# Taking input
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Addition
sum = float(num1) + float(num2)
# Subtraction
min = float(num1) - float(num2)
# Multiplication
mul = float(num1) * float(num2)
#Division
div = float(num1) / float(num2)
#Modulus
mod = float(num1) % float(num2)
#Exponentiation
exp = float(num1) ** float(num2)
# Floor Division
floordiv = float(num1) // float(num2)
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
print('The subtraction of {0} and {1} is {2}'.format(num1, num2, min))
print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul))
print('The division of {0} and {1} is {2}'.format(num1, num2, div))
print('The modulus of {0} and {1} is {2}'.format(num1, num2, mod))
print('The exponentiation of {0} and {1} is {2}'.format(num1, num2, exp))
print('The floor division between {0} and {1} is {2}'.format(num1, num2,floordiv))
swap two variables
Naïve Approach comma operator
1. P = int( input("Please enter value for P: "))1. P = int( input("Please enter value for P: "))
2. Q = int( input("Please enter value for Q: "))
2. Q = int( input("Please enter value for Q: "))
3.
3.
4. # To Swap the values of two variables
4. # To swap the value of two variables
5. P, Q = Q, P
5. # we will user third variable which is a tem
porary variable 6.
6. temp_1 = P 7. print ("The Value of P after swapping: ", P)
7. P = Q 8. print ("The Value of Q after swapping: ", Q)
8. Q = temp_1
9.
10. print ("The Value of P after swapping: ", P)
11. print ("The Value of Q after swapping: ", Q
)
XOR method arithmetic operators
1. P = int( input("Please enter value for P: "))1. P = int( input("Please enter value for P: "))
2. Q = int( input("Please enter value for Q: "))
2. Q = int( input("Please enter value for Q: "))
3.
3.
4. # To Swap the values of two variables using Addition and
4. # To Swap the values of two variables usin subtraction operator
g XOR
5. P=P+Q
5. P=P^Q
6. Q=P-Q
6. Q=P^Q
7. P=P-Q
7. P=P^Q
8.
8.
9. print ("The Value of P after swapping: ", P)
9. print ("The Value of P after swapping: ", P)