0% found this document useful (0 votes)
33 views50 pages

Class - 1

The document discusses Python concepts like comments, print function, variables, data types, operators, input function and arithmetic operations. Comments are used to explain code and make it readable. The print function displays output and can format text. Variables store values that can be changed using assignment operators. Data types include integers, floats, strings and booleans. Operators are used to perform arithmetic, comparison, assignment and other operations on variables.

Uploaded by

udayatuk1240
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views50 pages

Class - 1

The document discusses Python concepts like comments, print function, variables, data types, operators, input function and arithmetic operations. Comments are used to explain code and make it readable. The print function displays output and can format text. Variables store values that can be changed using assignment operators. Data types include integers, floats, strings and booleans. Operators are used to perform arithmetic, comparison, assignment and other operations on variables.

Uploaded by

udayatuk1240
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Class - 1

Class Overview
1. Python Installation
2. Writing Comments to your program code
3. Print()
4. Variables
5. Input()
6. Operators
Python Comments
Commenting our code helps explain our thought process, and
help us to understand later on the intention of our code.

1. Comments can be used to explain Python code.


2. Comments can be used to make the code more readable.

Creating a Comment

Comments starts with a #, and Python will ignore them


print() function
Syntax: print(object(s), sep=separator, end=end)

Parameter Description

object(s) Any object, and as many as you like. Will be converted to string before printed

sep='separator' Optional. Specify how to separate the objects, if there is more than one.
Default is SPACE

end='end' Optional. Specify what to print at the end. Default is NEW LINE

11
Ex1. print("Hello")
print(‘Hello’)
print(‘’’Hello’’’)
Print(“””Hello”””)
Ex2. name= ‘Johny’
print(name)

13
Ex3. name= ‘Johny’
print(“Hello “,name)
print(“Hello”,name, sep=‘***’)
Ex4. print(1, 2, 3, 4,sep=‘X’,end=‘\n\n\n’)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end=‘THE END')

15
Ex5
x = 100
.
y = 200
print(“x is”, x , ”y is” , y)
print(“x is”, x , ”y is” , y, sep=‘\n’)
print(“x is”, x, ”y is”, y, sep=‘$’, end=‘THE END’)
str.format()
Formatters work by putting in one or more replacement fields and placeholders
defined by a pair of curly braces { } into a string and calling the str.format()
S y n t a x : ‘ S t r i n g h e r e { } t h e n a l s o { } ’. f o r m a t ( ‘ s o m e t h i n g 1 ′ ,’s o m e t h i n g 2 ’ )

print('In our college {} and {} are good friends'.format('x','y'))

a,b=10,20
c=a+b
print('A is {0} B is {1} C is {2}'.format(a,b,c))

#We can insert objects using assigned keywords


print('a: {a}, b: {b}, c: {c}'.format(a = 1, b = 'Two', c = 12.3))
17
Variables
Variables are names of places that store information.
Making variables in Python: Var = 10

Var is a variable.
Var has value 10.
Var can have a different value later.

= is called the assignment operator.


It allows you to change the value of a variable.
Variables
The right hand side of the assignment can be any expression.

Var1 = 10
Var2 = 5 + Var1
Var3 = 4 * Var2
Var1 = (Var1 + Var3)
print(Var1, Var2, Var3)

Whenever a variable is on the right hand side of an expression,


it will be replaced by whatever value is currently stored in that variable.
Rules for Naming Variables
✓ Variable names are case sensitive.

Hello different from hello

✓ Only contain alphabetic letters, underscores or numbers.

✓ Should not start with a number.

✓ Cannot be any other python keyword (if, while, def, etc).

Note: Habituate to give your variables meaningful names!


Data Types
There are many different types of values !

Strings X = 1.12
Integer
Y = True
DataTypes Numbers
Float Z = 100
Boolean S = ‘Hello everyone’
Exercise
What will the following code snippet print?
Var1 = 10
Var2 = 5 + Var1
Var3 = 4 * Var2
Var1 = (Var1 + Var3)/2
print(Var1, Var2, Var3)
Exercise
What will the following code snippet print?

a = 10
b=a*5
c = "Your result is: "
print(c, b)
Exercise
What will the following code snippet print?

a = 10
b=a
a=3
print(b)

Any guesses?
Exercise
What will the following code snippet print?

glass_of_water=
print("I drank", glass_of_water, "glasses of water today.")
27
input() function
✓ Python input() function is used to take user input.
✓ input() returns a string object.
✓ Even if the input value is an integer/float, input() takes it as a string.

Syntax: input(Prompt Message)

Ex1: name = input()


Ex2: name = input(“Enter Name”)

28
Input
Sometimes, we’d like the user to participate! We can
also get input from the user.
value = input("Please enter a number ")
print(value)

The output will look like this:


Please enter a number 10
10
Ex. 1: Input the Name and Age of the user and Display it

name = input("Please Enter Your Name: ")

age = input("Please Enter Your Age: ")

print("The name of the user is {0} and his/her age is {1}".format(name, age))

Ex. 2: Input two integers and Display Sum

n1 = int(input("Please Enter First Number: "))

n2 = int(input("Please Enter Second Number: "))

print(“Sum of {0} and {1} is {2}”.format(n1,n2,n1+n2) ) 30


Python - Basic Operators
Python language supports following type of operators.

• Arithmetic Operators
• Comparison Operators
• Assignment Operators
• Bitwise Operators
• Logical Operators
• Conditional (or ternary) Operators

31
Python Arithmetic Operators:
Assume a=10 b=20
Operator Description Example
+ Addition - Adds values on either side of the operator a + b will give 30

Subtraction - Subtracts right hand operand from left hand


- operand
a - b will give -10

* Multiplication - Multiplies values on either side of the operator a * b will give 200

/ Division - Divides left hand operand by right hand operand b / a will give 2.0

Modulus - Divides left hand operand by right hand operand


% and returns remainder
b % a will give 0

Exponent - Performs exponential (power) calculation on


** operators
a**b will give 10 to the power 20

Floor Division - The division of operands where the result is 9//2 is equal to 4
// the quotient in which the digits after the decimal point are and
removed. 9.0//2.0 is equal to 4.0
32
Python Comparison Operators:
Operator Description Example
Checks if the value of two operands are equal or not,
== if yes then condition becomes True. (a == b) is False.

Checks if the value of two operands are equal or not,


!= if values are not equal then condition becomes True. (a != b) is True.

Checks if the value of left operand is greater than the value of


> right operand, if yes then condition becomes True. (a > b) is False.

Checks if the value of left operand is less than the value of


< right operand, if yes then condition becomes True. (a < b) is True.

Checks if the value of left operand is greater than or equal to


>= the value of right operand, if yes then condition becomes True. (a >= b) is False.

Checks if the value of left operand is less than or equal to the


<= value of right operand, if yes then condition becomes True. (a <= b) is True.

33
Python Assignment Operators:
Operator Description Example
c = a + b will assign
= Assigns values from right side operands to left side operand value of a + b into c
It adds right operand to the left operand and assign the result c += a is equivalent to
+= to left operand c=c+a
It subtracts right operand from the left operand and assign the c -= a is equivalent to
-= result to left operand c=c-a

It multiplies right operand with the left operand and assign the c *= a is equivalent to
*= result to left operand c=c*a

It divides left operand with the right operand and assign the c /= a is equivalent to
/= result to left operand c=c/a
It takes modulus using two operands and assign the result to c %= a is equivalent to
%= left operand c=c%a
Performs exponential (power) calculation on operators and c **= a is equivalent to
**= assign value to the left operand c = c ** a
Performs floor division on operators and assign value to the c //= a is equivalent to
//= left operand c = c // a
34
Python Logical Operators:
a=True b=True
Operator Description Example

Called Logical AND operator. If both the operands are


and (a and b) is True.
True then then condition becomes True.

Called Logical OR Operator. If any of the two operands


or (a or b) is True.
are non zero then then condition becomes True.

Called Logical NOT Operator. Use to reverses the


not logical state of its operand. If a condition is True then not(a and b) is false.
Logical NOT operator will make false.

36
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
Complement, unary plus and minus
~+- (method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators


in not in Membership operators
not or and Logical operators 37
Operator Precedence
Like algebra, multiply and divide before adding and subtracting:
5 + 3 * 4
is 17, not 32.

Python has many more operators.


33Precedence allows this expression to make sense without
parentheses:
3 * 4 + 5 > 2 + 2 * 4 and 17 + 9 > 31 - 22
Associativity

Associativity does not hold


(4.05 - 4.05) + 0.0000000000000001
does not equal
4.05 – (4.05 + 0.0000000000000001)
are not the same.

Most operations associate left to right by


default: a + b + c means (a + b) + c
More operators
Exponentiation:
2**3 is 8
2.5**2 is 6.25
Division :
5/2 IS 2.5
Integer division (rounds down):
5//2 is 2
Modulus (gives the remainder):
28 % 5 is 3
Exercise
What is the value of the expression 1 + 2 ** 3 * 4?
Event Details Sample Input and Output:
"DC Events" is a recently launched start-up
Event Management company. The company
Enter the name of the event 1
Food Fest 2017
gained a good reputation within a short span
because of its highly reliable service Enter the type of the event
delivery. Public
Enter the number of people expected
Amith, the founder of this company wished 5000
to take the company’s services to the next Is it a paid entry? (Type Y or N)
step and decided to design an Event
Management System that would let its N
Customers plan and host events seamlessly Enter the projected expenses (in lakhs) for
via an online platform. this event
Write a program that will get the input of the 5.7
event details like name of the event, type of Event Name : Food Fest 2017
the event, number of people expected, a
string value (Y/N) telling whether the event Event Type : Public
is going to be a paid entry and the projected Expected Count : 5000
expenses (in lakhs) for the event. The Paid Entry : N
program should then display the input Projected Expense : 5.7L
values as a formatted output. 42
Mid-Point
A, B, C are studying in a school and close friends. Their house are in
2
a straight line. B’s house is exactly in the middle. Given the coordinates of the 2
end points of a line (x1, y1) and (x2, y2), write a program to find the midpoint of the
line. Find where B’s house is.
Sample Input and Output:
X1
2
Y1
4
X2
10
Y2
15

B's house is located at (6.0, 9.5) 43


Talent Show
Of the total audience who had come for the show, 1/3 were boys, 3
3/6 were girls and the rest of them were adults. If there were 'X' more girls
than adults, how many people were there in total? Help the School
authorities to find the total people who visited their show.
Sample Input and Output1:
Enter X
50
150 people were there in total

Sample Input and Output2:


Enter X
70
210 people were there in total
44
Change:
Consider a currency system in which there are notes of seven 4
denominations, namely, Rs. 1, Rs. 2, Rs. 5, Rs. 10, Rs. 50, Rs. 100.
If the change given to him Rs. N is input, write a program to
compute smallest number of notes that will combine to give Rs. N.

Sample Input 1:
1200
Sample Output1:
12

Sample Input 2:
242
Sample Output2:
7 45
Lucky Gifts
Krishna is Chocolate lover.
In an event, he was asked to distribute chocolates to few lucky attendees.
5
There are 'N' chocolates available. He need to decide how many Chocolates (P) to place in each pack. Each
pack must contain the same number of chocolates. Place exactly P chocolates into each pack. He should
make as many packs as possible.
Write a program that will calculate the pack size P so that he can eat as many chocolates as possible.
If multiple pack size will result in the same number of leftover candies, then print the largest pack size.

Sample Input 1: Sample Input 2:


2 5
Sample Output 1:
2 Sample Output 2:
3
Note: N is 2
1(size) * 2(No. of packs) = 2 (0 Remaining) Note: N is 5
2(size) * 1(No. of packs) = 2 (0 Remaining) 1(size) * 5(No. of packs) = 5 (0 Remaining)
Largest pack size 2 2(size) * 2(No. of packs) = 4 (1 Remaining)
3(size) * 1(No. of packs) = 3 (2 Remaining)
4(size) * 1(No. of packs) = 4 (1 Remaining).
46
Three renowned magicians were invited to mystify and thrill the crowd with their world’s
6
spectacular magic tricks. At the end of each of the 3 magicians’ shows, the audience were
requested to give their feedback in a scale of 1 to 10. Number of people who watched
each show and the average feedback rating of each show is known. Write a program to find the
average feedback rating of the Magic show.
Sample Input and Output:
Enter the number of people who watched show 1
400
Enter the average rating for show 1
9.8
Enter the number of people who watched show 2
500
Enter the average rating for show 2
Magic Show
9.6
Enter the number of people who watched show 3
100
Enter the average rating for show 3
5
The overall average rating for the show is 9.22 47
Part-Time Employees
A company hired few part-time employees to work and the agreed salary paid to 7
them are as given below:
Weekdays --- Rs. 120 / hour
Weekends --- Rs. 100 / hour

Number of hours Employee-X has worked in the weekdays is 10 more than the number of
hours he had worked during weekends. If the total salary paid to him in this month is
known, write a program to estimate the number of hours he had worked during weekdays
and the number of hours he had worked during weekends.

Sample Input and Output: WD=WE+10


Enter the total salary paid TS=WE*100+WD*120
4500
Number of weekday hours is 25 TS=WE*100+(WE*120+10*120)
Number of weekend hours is 15 WE=(TS-1200)/220
48
Total Expenses for the Event
The program should get the branding expenses, travel expenses, food expenses and
logistics expenses as input from the user and calculate the total expenses for an event
8
and the percentage rate of each of these expenses.

Sample Input and Output:


Enter branding expenses
20000
Enter travel expenses
40000
Enter food expenses
15000
Enter logistics expenses
25000
Total expenses : Rs.100000.00
Branding expenses percentage : 20.00%
Travel expenses percentage : 40.00%
Food expenses percentage : 15.00%
Logistics expenses percentage : 25.00%
49
Tickets sold for Charity Event
A famous NGO has been selective in identifying events to raise funds for charity. 9
Naveena is a volunteer from the NGO who was selling tickets to the public for
the charity event. She sold 'X' more adult tickets than children tickets and she sold twice
as many senior tickets as children tickets. Assume that an adult ticket costs Rs. 50, children
ticket costs Rs. 20 and senior ticket costs Rs. 30.
Naveena made 'Y' Rupees from ticket sales. Find the number of adult tickets, children
tickets, and senior tickets sold.

Sample Input and Output:


Enter the value of X
10
Enter the value of Y
7000
Number of children tickets sold: 50
Number of adult tickets sold: 60
Number of senior tickets sold: 100
50
Trade Fair
Number of people who attended the event on the first day was x. But as days 10
progressed, the event gained good response and the number of people who attended the
event on the second day was twice the number of people who attended on the first day.
Unfortunately due to heavy rains on the third day, the number of people who attended
the event was exactly half the number of people who attended on the first day.

Given the total number of people who have attended the event in the first 3 days, find the
number of people who have attended the event on day 1, day 2 and day 3.

Sample Input and Output:


Enter the total number of people
10500
Number of attendees on day 1 : 3000
Number of attendees on day 2 : 6000
Number of attendees on day 3 : 1500
51

You might also like