You are on page 1of 93

Text Book

Let Us Python – 4th Edition Yashavant


Kanetkar, Aditya Kanetkar.
Python Syntax
Variable/ Identifier Naming
The first character of the variable must be an alphabet or underscore ( _ ).
Identifier name must not contain any white-space, or special character (!,
@, #, %, ^, &, *).
Identifier name must not be similar to any keyword defined in the
language.
Identifier names are case sensitive; for example, my name, and MyName
is not the same.
Examples of some valid variable names: Examples of some invalid variable names:
 employee
 roll_no
 Your age : invalid because variable cannot contain white space.
 average_score
 sep9_Bday  while : invalid because variable cannot be reserved keyword.
 _my_name
 9Sep_Bday : invalid variable name because variable is starting with
 x
 name_25 a digit.
 CollegeName
 student@ : invalid because of having a special character.
 Length
 _0_0_9  sum of square
 re_turn
 %_owed
 none
 x234  raise%
 global
Creating Variables

• Python has no command for declaring a variable.


• A variable is created the moment you first assign a value to it.

Variables do not need to be declared with any particular type and


can even change type after they have been set.
Assigning values to Variables in Python

1.Simple declaration and assignment of a value to the


Variable
In this type, the data values are directly assigned to the Variables in the declaration
statement. Example:
2.Changing the value of a Variable

Data values assigned to the variables can be changed at any time. 

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

# Calculating the percentage.


per = (marks_obtained * 100) / 300
# Displaying the marks obtained and percentage.
print("Marks obtained in three subjects: ", marks_obtained)
print("Percentage: ", per)
Write a Python program to find the perimeter and area of a circle having the
radius 5 cm. The formulas for finding the perimeter and area of a circle are 2πr
and πr², respectively, where π = 3.14.

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

Python # Calculating years


years = number_of_days // 365
program to
convert given # Calculating months

number of days months = (number_of_days - years *365) // 30

to years, # Calculating days


months and days = (number_of_days - years * 365 - months*30)

days # Displaying results


print("Years = ", years)
print("Months = ", months)
print("Days = ", days)
#Python program to calculate simple interest
Program to P = float(input("Enter the principal amount : "))
calculate N = float(input("Enter the number of years : "))
R = float(input("Enter the rate of interest : "))
simple #caculate simple interest by using this formula
interest SI = (P * N * R)/100
#print
print("Simple interest : ", SI)
p = float(input("Enter the principal amount : "))
Program to t = float(input("Enter the number of years : "))
calculate r = float(input("Enter the rate of interest : "))
compound #compute compound interest
interest ci = p * (pow((1 + r / 100), t))
#print
print("Compound interest : ", ci)
# Python code to swap two numbers
# without using another variable

x=5
y=7
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)

# code to swap 'x' and 'y'


x, y = y, x

print ("After swapping: ")


print("Value of x : ", x, " and y : ", y)
# Python Program to convert temperature in celsius to fahrenheit

# change this value for a different result


celsius = 37.5

# 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:

A comment does not have to be text that explains the code, it


can also be used to prevent Python from executing code:
Multiline Comments

Python does not really have a syntax for multiline comments.


To add a multiline comment you could insert a # for each line:

Or, not quite as intended, you can use a multiline string.


Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code,
and place your comment inside it:
Literals
a = (1 == True) x = (1 == True)
a is True y = (2 == False)
b = (1 == False) b is False
c = True + 3 z = (3 == True)
c: 4 r = (1 == True)
d = False + 7 d: 7 a = True + 10
print("a is", a) b = False + 10
print("b is", b)
print("c:", c) print("x is", x)
print("d:", d) print("y is", y)
print("z is", r)
print("a:", a)
print("b:", b)

x is True
y is False
z is True
a: 11
b: 10
Numeric Literals

The different types of integers are-

•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. 

Example: Here  geekforgeeks  is a string literal that is assigned to a variable(s). 

OUTPUT
Character literal

It is also a type of string literal where a single character is surrounded by single or


double quotes.

OUTPUT
str1 = “python"
print(str1)

# Multi-line string
str2 = """ This,
is it!
"""
print(str2)

str3= "i am\


a good\
girl"
print(str3)
Literal Collections

In Python, there are 4 different types of Literal Collections. They represent


more complicated and complex data and assist Python scripts to be more
extensible. Let us look at each one of them in detail.

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

The data is stored in the dictionary as a key-value pair. It is surrounded by curly


braces ‘{}‘, and each pair is separated by commas (,). A dictionary can hold various
types of data. Dictionaries are subject to change.
4. Set Literals
Set is an unordered data set collection. It is surrounded by {} and each element is
separated by a comma (,).
Example:

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

•Sequence of execution of instructions in a


program can be altered using:

•(a) Decision control instruction


•(b) Repetition control instruction
Logical Operators

cond1 and cond2 - returns True if both are True, otherwise False

cond1 or cond2 - returns True if one of them is True, otherwise False


1. WAP in python to check whether the entered number is positive number or not

2. WAP in python to check whether the entered number is even number or odd
number

3. WAP in python to find maximum of two numbers entered by user

4. If ages of Ram, Shyam and Ajay are input through the keyboard, write a program to
determine the youngest of the three.

5. WAP in python to check whether the person is eligible to vote or not.

6. While purchasing certain items, a discount of 10% is offered if the quantity


purchased is more than 1000. If quantity and price per item are input through the
keyboard, write a program to calculate the total expenses.

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.

9. A company insures its drivers in the following cases:


1. If the driver is married.
2. If the driver is unmarried, male & above 30 years of age.
3. If the driver is unmarried, female & above 25 years of age.

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

The algorithm to determine if a year is a leap year is as follows:


Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these
centurial years are leap years, if they are exactly divisible by 400.
For example, the years 1700, 1800, and 1900 were not leap years, but the years 1600 and 2000 were.
Question Number 6
qty = int(input('Enter value of quantity: '))
price = float(input('Enter value of price: '))
if qty > 1000 :
dis = 10
else :
dis = 0
totexp = qty * price - qty * price * dis / 100
print('Total expenses = Rs. ', totexp)

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

per = int(input('Enter value of percentage: '))


if per >= 60 :
print('First Division')
elif per >= 50 :
print('Second Division')
elif per >= 40 :
print('Third Division')
else :
print('Fail’)

Question No. 9

ms = input('Enter marital status:')


g = input('Enter gender: ')
age = int(input('Enter age: '))
if ( ms == 'm' ) or ( ms == 'u' and g == 'm' and age > 30 ) or ( ms == 'u' and g == 'f' and age > 25 ) :
print('Insured')
else :
print("not insured")
Question No. 10

year = 2000

# To get year (integer input) from the user


# year = int(input("Enter a year: "))

# divided by 100 means century year (ending with 00)


# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print(“this is leap year)

# not divided by 100 means not a century year


# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print(“this is leap year)

# 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.

s1 = int(input("Enter the Triangle Side-1 :"))


s2 = int(input("Enter the Triangle Side-2 :"))
s3 = int(input("Enter the Triangle Side-3 :"))
sum = s1+s2+s3
if(sum==180):
print("Triangle Valid..")
else:
print("Triangle Not Valid..")
1. Given the length and breadth of a rectangle, write a program to find whether the area of the
rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and
breadth = 4 is greater than its perimeter.

l = int(input("Enter the length:"))


b = int(input("Enter the breadth"))
area= l*b
perm= 2*l + 2*b
if(area>perm):
print("area is greater than perim")
else:
print("no area is not greater than perim")
Given the coordinates (x, y) of center of a circle and its radius, write a program that will determine whether a point
lies inside the circle, on the circle or outside the circle. (Hint: Use sqrt( ) and pow( ) functions)

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

Unlike many other languages there is no do-while loop in Python.


count = 0
while count < 10 :
print(count, count * count, count * count * count)
count += 1

num = int(input('Enter a number: '))


while num != 5 :
print(num, num * num)
num = int(input('Enter a number: '))
Usage of for loop

A for loop can be used in following two situations:

- Repeat a set of statements a finite number of times.


- Iterate through a string, list, tuple, set or dictionary.

To repeat a set of statements a finite number of times a built-in function range( ) is used.

range( ) function generates a sequence of integers.


range(10) - generates numbers from 0 to 9.
range(10, 20) - generates numbers from 10 to 19.
range(10, 20, 2) - generates numbers from 10 to 19 in steps of 2.
range(20, 10, -3) - generates numbers from 20 to 9 in steps of -3.

Note that range( ) cannot generate a sequence of floats.


WAP in python to check whether the
entered number is prime number or not
How will you write an equivalent for loop for the following:
count = 1
while count <= 10 :
print(count)
count = count + 1

for i in range (1,11):


print(i)
Write a program to print first 25 odd numbers using range( ).
Write a program to count the number of alphabets and number of digits in the string 'Nagpur-440010
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.
Write a program to find the factorial value of any number entered through the keyboard.
Write a program to print first 25 odd numbers using range( ).
# iterating each number in list
for num in range(0, 26):
if num % 2 != 0:
print(num)

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.

# change the value for a different result


num = 7

# To take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
# Program to check if a number is prime or not

num = 29

# To take input from the user


#num = int(input("Enter a number: "))
# define a flag variable
flag = False

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

# check if flag is True


if flag:
print(num, "is not a prime number")

You might also like