Professional Documents
Culture Documents
Text Book: Let Us Python - 4th Edition Yashavant Kanetkar, Aditya Kanetkar
Text Book: Let Us Python - 4th Edition Yashavant Kanetkar, Aditya Kanetkar
In the above program, initially the value of Variable ‘val’ was 50. Later it
was reassigned to a value of 100.
3. Assign multiple values to multiple Variables
In Python, we can assign multiple values to multiple variables in the same declaration
statement by using the following method –
We can also assign a single value to multiple variables. Let us look at the below
example to understand this,
Python provides two built-in methods
to read the data from the keyboard.
These methods are given below.
Taking input(prompt)
input from
user
raw_input(prompt) // for older
version
name = input("Enter your name: ")
print(name)
name = input("Enter your name: ") # String Input
age = int(input("Enter your age: ")) # Integer Input
marks = float(input("Enter your marks: ")) # Float Input
print("The name is:", name)
print("The age is:", age)
print("The marks is:", marks)
• By default, the input() function takes input as a string so if we need to
enter the integer or float type input then the input() function must be
type casted.
age = int(input("Enter your age: ")) # Integer Input
marks = float(input("Enter your marks: ")) # Float Input
Write a Python program to create three integer variable and assign values and print them
on screen.
# Integer assignments.
x = 20
y = 50
z = 100
# Print the values of variables on the console.
print(x)
print(y)
print(z)
Write a program to add marks of three subjects: physics, chemistry, and maths and print the
marks obtained and percentage.
phy = 89
chem = 86
maths = 90
# Adding the marks of three subjects.
marks_obtained = phy + chem + maths
radius = 5
pi = 3.14
perimeter = 2 * pi * radius
area = 3.14 * radius * radius
print("Perimeter of the circle = ", perimeter)
print("Area of the circle = ", area)
Exercise
• Program to add and multiply two numbers
• Program to add and multiply two complex numbers
• Python program to convert given number of days to years, months and days
• Program to calculate simple and compound interest (x = pow(4, 3))
• Write a program that swaps the values of variables a and b. You are not allowed to use a third
variable. You are not allowed to perform arithmetic on a and b.
• Write a program that swaps the values of variables a and b. use temp variable.
• WAP to convert the temperature from Celsius into Fahrenheit
Fahrenheit = (celsius * 1.8) + 32
num_1 = 2
Program to num_2 = 3
add and sum = num_1 + num_2
multiply two product = num_1 * num_2
numbers print(" sum is : " , sum , "product is : ",
product))
Program to num_1 = 2+3j
add and num_2 = 3+2j
multiply two sum = num_1 + num_2
complex product = num_1 * num_2
numbers print(" sum is : " , sum , "product is : ",
product)
# Reading number of days from user
number_of_days = 450
x=5
y=7
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
Delete a
variable in
python
Syntax: del variableName
Deleting Multiple Variables in Python
Python Comments
1 2 3
Comments can be Comments can be Comments can be
used to explain used to make the used to prevent
Python code. code more execution when
readable. testing code.
Creating a Comment
Comments starts with a #, and Python will ignore them:
Comments can be placed at the end of a line, and Python will ignore
the rest of the line:
x is True
y is False
z is True
a: 11
b: 10
Numeric Literals
•Decimal- It contains digits from 0 to 9. The base for decimal values is 10.
•Binary- It contains only two digits- 0 and 1. The base for binary values is 2 and prefixed with “0b”.
•Octal- It contains the digits from 0 to 7. The base for octal values is 8. In Python, such values are prefixed
with “0o”.
•Hexadecimal- It contains digits from 0 to 9 and alphabets from A to F. In Python, such values are prefixed
with “0x”.
Float
These are real numbers having both integer and fractional parts.
Example:
24.8 and 45.0 are floating-point literals because both 24.8 and 45.0 are floating-point
numbers.
Complex
The numerals will be in the form of a + bj, where ‘a‘ is the real part. And the entire ’b’ part, along with ’j’, is the imaginary
or complex part. j here represents the square root of -1 which is nothing.
Example:
a= 5+6j
print("value of a is", a.real, a.imag)
• # Python program to convert decimal into other number systems
dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
String literals
A string literal can be created by writing a text(a group of Characters ) surrounded by a single(”), double(“”), or triple
quotes. By using triple quotes we can write multi-line strings or display them in the desired way.
OUTPUT
Character literal
OUTPUT
str1 = “python"
print(str1)
# Multi-line string
str2 = """ This,
is it!
"""
print(str2)
1.List Literals
The elements in a list are of many data types. The values in the List are
surrounded by square brackets ([]) and separated by commas (,). List
values can be changed i.e., they are mutable.
2.Tuple Literals
Just like a List, a tuple is also a collection of various data types. It is surrounded
by parentheses ‘(),’ and each element is separated by a comma (,). It is
unchangeable (immutable).
3. Dictionary Literals
OUTPUT
Special literal
Python contains one special literal (None). ‘None’ is used to define a null variable.
If ‘None’ is compared with anything else other than a ‘None’, it will return false.
Example:
Python Data
Types
PYTHON
OPERATORS
1. Arithmetic Operators
Arithmetic operators are used for mathematical computations like addition, subtraction, multiplication, etc. They
generally operate on numerical values and return a numerical value. They’re also referred to as mathematical
operators.
2. Comparison Operators
Comparison operators are used for comparing two values. As an output, they return a Boolean value, either
True or False.
3. Logical Operators
These operators are used to perform logical and, or, and not operations. They operate on boolean values and
return a boolean value.
4. Assignment Operators
Python assignment operators are used to assign values to variables. These operators include simple
assignment operator, addition assign, subtraction assign, multiplication assign, division and assign operators
etc.
5. Identity Operators
Identity operators are special operators in python which are used to compare two operands based on the
memory location they refer to. is and is not are the two identity operators used in python.
6. Membership Operators
Membership operators are also special operators in python which are used to determine whether a value or
variable is present in a sequence (string, list, tuple, set, and dictionary). in and not in are the membership
operators used in Python.
x=2
y = [1, 2, 3]
# in operator
print("x in y =", x in y)
# not in operator
print("x not in y =", x not in y)
x in y = True
x not in y = False
7. Bitwise Operators
Bitwise operators operate on the binary values of the operands bit-by-bit. For example, a Bitwise AND
operation on 9(0000 1001 in binary) and 3(0000 0011 in binary), that is, 9 & 3 results in 1(0000 0001).
Whereas, a Bitwise Or operation, 9 | 3 results in 11(0000 1011).
Example: Assuming x=9 and y=3, the following table illustrates examples for each of the Bitwise operators.
Operator
Precedence
Control Statements
cond1 and cond2 - returns True if both are True, otherwise False
2. WAP in python to check whether the entered number is even number or odd
number
4. If ages of Ram, Shyam and Ajay are input through the keyboard, write a program to
determine the youngest of the three.
7. In a company an employee is paid as under: If his basic salary is less than Rs. 1500,
then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is
either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic
salary. If the employee's salary is input through the keyboard write a program to
8. Percentage marks obtained by a student are input through the keyboard. The student gets a division as
per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained by the student.
In all other cases, the driver is not insured. If the marital status, gender and age of the driver are the inputs,
write a program to determine whether the driver should be insured or not.
10. WAP in python to check whether the entered year is leap year or not
Question 7
bs = int(input('Enter value of bs: '))
if bs > 1000 :
hra = bs * 15 /100
da = bs * 95 / 100
ca = bs * 10 / 100
else:
hra = bs * 10 / 100
da = bs * 90 / 100
ca = bs * 5 / 100
gs = bs + da + hra + ca
print('Gross Salary = Rs. ' + str(gs)
Question No. 8
Question No. 9
year = 2000
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print(“this is not leap year)
1. Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the
keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.
The idea is compute distance of point from center. If distance is less than or equal to radius. the point is inside, else
outside.
1. Given a point (x, y), write a program to find out if it lies on the Xaxis, Y-axis or on the origin.
2. A year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical
operators and and or.
3. If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid
or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.
4. If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is
isosceles, equilateral,scalene or right angled triangle
Repetition control instruction
Repeat a set of statements in a program. There are two types of repetition control instructions:
(a) while
(b) For
To repeat a set of statements a finite number of times a built-in function range( ) is used.
Write a program to count the number of alphabets and number of digits in the string 'Nagpur-440010'
# given string
string = "Nagpur-440010"
# initialized value
total_digits = 0
total_letters = 0
# iterate through all characters
for s in string:
# if character is digit (return True)
if s.isnumeric():
total_digits += 1
# if character is letter (return False)
else:
total_letters += 1
print("Total letters found :-", total_letters)
print("Total digits found :-", total_digits)
A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to
determine whether the original and reversed numbers are equal or not.
num = 1221
num1=num
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: ",reversed_num)
if (reversed_num==num1):
print("both are equal")
else:
print("not equal")
# Python program to find the factorial of a number provided by the user.
factorial = 1
num = 29
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break