389560663-python
389560663-python
389560663-python
Easy to learn and use: It is much easier to learn than any other programming
languages like C, C++, Java, Ruby and Swift. It has few keywords and thus
very less syntactical constraints. Thus the language is very developer friendly
and easy to pick up.
Free and Open Source → Python is a open sourced language. Thus it is
publicly available to download and use and even anyone can contribute to its
development.
Easy to maintain → Python code base is very easy to maintain.
Object Oriented Language → Python is an Object Oriented language. Thus is
provides all the key features of an Object Oriented Programming language
like Encapsulation, Inheritance, Abstraction and Polymorphism.
Nevertheless, Python also offers a scope to write code as in a Procedural
Programming Language.
Extensibility → Python is very extensible. We can write and integrate some
Python code into C and C++ and hence compile it using its irrespective
compilers.
Portability → Python provides high portability. Thus same piece of code can
be run in all platforms of Windows, UNIX and Linux.
Large Standard Library → Python has a large set of large standard library
which possess some inbuilt rich set of functions such that we need not to
write code for every single thing.
Dynamically Typed Language → Python is a dynamically typed language.
Here, we need not to declare the type of the variable like int, float and char. It
is also auto-set as we assign a value to the variable.
Garbage Collection → Python also supports auto garbage collection.
Comments:
A good piece of code is the one which a reader can understand. Comments are
mainly used for this purpose.
In Python, comments are ignored by the interpreter and hence they are used to make
the code more readable. By putting comments in or around any block of code, we
can explain the functionality of that piece of code.
A comment in Python always begins with "#" sign. These are mainly single line
comments. In Python, there is no concept of multiline comments, but you can realize
a multiline comment by using docstrings.
'''
'''
Variable
Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin
with a letter or an underscore.
Rules to define Variables are:
Declaring Variable:
Python does not bind us to declare a variable before using it in the application. It
allows us to create a variable at the required time.
Example:
1. a = 50
2. a = 50
b=a
The variable b refers to the same object that a points to because Python does not
create another object.
Example 2:
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4. print(name)
5. print(age)
6. print(marks)
Multiple Assignments
Python allows us to assign a value to multiple variables in a single statement, which
is also known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value
to multiple variables or assigning multiple values to multiple variables
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Variables can hold values, and every value has a data-type. Python is a dynamically
typed language; hence we do not need to define the type of the variable while
declaring it. The interpreter implicitly binds the value with its type.
a=5
The variable a holds integer value five and we did not define its type. Python
interpreter will automatically interpret variables a as an integer type.
Example:
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can hold different types of values. For example, a person's name must be
stored as a string whereas its id must be stored as an integer.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
Number stores numeric values. The integer, float, and complex values belong
to a Python Numbers data-type
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It
is accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x
and y denote the real and imaginary parts, respectively. The complex
numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
List
Python Lists are similar to arrays in C. However, the list can contain data of
different types. The items stored in the list are separated with a comma (,)
and enclosed within square brackets [].
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the
collection of the items of different data types. The items of the tuple are
separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value
of the items of a tuple.
Example:
tup = ("hi", "Python", 2)
print (tup)
Dictionaries
Dictionaries are basically unordered collection of key-value pairs.
Dictionaries are defined within braces and contain key:value pairs. Keys and
values can be of any data type.
Example:
Set
Python Set is the unordered collection of the data type. It is iterable, mutable
(can modify after creation), and has unique elements.
Boolean
Boolean type provides two built-in values, True and False. These values are
used to determine the given statement true or false.
Python Operators
The operator is a symbol that performs a certain operation between two operands.
The different operators that Python offers are listed here.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operations between two operands are carried out using arithmetic
operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b
(Multiplication) = 4 => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.
Comparison operator
Comparison operators compare the values of the two operands and return a true or
false Boolean value in accordance.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes
true.
<= The condition is met if the first operand is smaller than or equal to the
second operand.
>= The condition is met if the first operand is greater than or equal to the
second operand.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.
Assignment Operators
The right expression's value is assigned to the left operand using the assignment
operators. The following table provides a description of the assignment operators.
Operator Description
+= By multiplying the value of the right operand by the value of the left
operand, the left operand receives a changed value. For example, if a =
10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right
operand and assigns the modified value back to left operand. For
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore,
a = 10.
*= It multiplies the value of the left operand by the value of the right
operand and assigns the modified value back to then the left operand.
For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand
and assigns the reminder back to the left operand. For example, if a = 20,
b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. Consider
the case below.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same
and) location are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.
^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0,
the next bit will be 1, and vice versa.
<< (left The number of bits in the right operand is multiplied by the leftward
shift) shift of the value of the left operand.
>> (right The left operand is moved right by the number of bits present in the
shift) right operand.
Logical Operators
The assessment of expressions to make decisions typically makes use of the logical
operators. The following logical operators are supported by Python.
Operator Description
and The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the
two expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
The membership of a value inside a Python data structure can be verified using
Python membership operators. The result is true if the value is in the data structure;
otherwise, it returns false.
Operator Description
not in If the first operand is not present in the second operand, the evaluation is
true (list, tuple, or dictionary).
Identity Operators
Operator Description
is not If the references on both sides do not point at the same object, it is
determined to be true.
Reading Input
In Python, input() function is used to gather data from the user. The syntax for input
function is,
variable_name = input([prompt])
prompt is a string written inside the parenthesis that is printed on the screen. The
prompt statement gives an indication to the user of the value that needs to be entered
through the keyboard. When the user presses Enter key, the program resumes and input
returns what the user typed as a string. Even when the user inputs a number, it is
treated as a string which should be casted or converted to number explicitly using
appropriate type casting function.
Example1:
When input() function executes program flow will be stopped until the user has
given input.
The text or message displayed on the output screen to ask a user to enter an input
value is optional i.e. the prompt, which will be printed on the screen is optional.
Whatever you enter as input, the input function converts it into a string. if you
enter an integer value still input() function converts it into a string. You need to
explicitly convert it into an integer in your code using typecasting.
Ex 2
num =input("Enter number :")
print(num)
There are various function that are used to take as desired input few of them are : –
int(input())
float(input())
Output Statement :
The print() function allows a program to display text onto the console. The print
function will print everything as strings and anything that is not already a string is
automatically converted to its string representation. For example,
prints the string Hello World!! onto the console. Notice that the string Hello World is
enclosed within double quotes inside the print() function.
Python Casting
Type Casting is the method to convert the variable data type into a certain data
type in order to the operation required to be performed by users. In this article, we
will see the various technique for typecasting.
Mainly in type casting can be done with these data type function:
Int() : Int() function take float or string as an argument and return int
type object.
float() : float() function take int or string as an argument and return float
type object.
str() : str() function take float or int as an argument and return string type
object.
Type Casting int to float:
Here, we are casting integer object to float object with float() function.
a =5
# typecast to float
n =float(a)
print(n)
print(type(n))
Output:
5.0
<class 'float'>
# int variable
a =5.9
# typecast to int
n =int(a)
print(n)
print(type(n))
Output:
5
<class 'int'>
There comes situations in real life when we need to make some decisions and
based on these decisions, we decide what should we do next. Similar situations
arise in programming also where we need to make some decisions and based on
these decisions we will execute the next block of code. Decision-making statements
in programming languages decide the direction of the flow of program execution.
if statement
if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not.
As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:
if condition:
statement1
statement2
Flowchart of Python if statement
Example:
i=10
if(i>15):
print("10 is less than 15")
output:
Output
Enter a number 67
The number entered by the user is a positive number
# condition is true
else:
# condition is false
if number_1 >number_2:
print(f"{number_1} is greater than {number_2}")
else:
print(f"{number_2} is greater than {number_1}")
Output
Enter the first number 8
Enter the second number 10
10 is greater than 8
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
.else:
statement
nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, Python allows us
to nest if statements within if statements. i.e, we can place an if statement inside
another if statement.
Syntax:
if (condition1):
if (condition2):
i=10
if(i==10):
# First if statement
if(i<15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if(i<12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Output:
i is smaller than 15
The while loop starts with the while keyword and ends with a colon. With a while
statement, the first thing that happens is that the Boolean expression is evaluated
before thestatements in the while loop block is executed. If the Boolean expression
evaluates to False,then the statements in the while loop block are never executed. If
the Boolean expressionevaluates to True, then the while loop block is executed. After
each iteration of the loopblock, the Boolean expression is again checked, and if it is
True, the loop is iterated again.
Syntax:
while expression:
statement(s)
Variable iis assigned with 0 outside the loop ➀. The expression i<10 is evaluated ➁.
If thevalue of iis less than 10 (i.e., True) then the body of the loop is executed. Value
of iis printed ➂and iis incremented by 1 ➃. This continues until the expression in
while loop becomes False.
Program 3.9: Write a Program to Find the Average of n Natural NumbersWhere nIs
the Input from the User
number = int(input("Enter a number up to which you want to find the average"))
i=0
sum = 0
count = 0
while i<number:
i = i+ 1
sum = sum + i
count = count + 1
average = sum/count
print(f"The average of {number} natural numbers is {average}")
Output
Enter a number up to which you want to find the average 5
The average of 5 natural numbers is 3.0
Program to Find the GCD of Two Positive Numbers
m = int(input("Enter first positive number"))
n = int(input("Enter second positive number"))
if m == 0 and n == 0:
print("Invalid Input")
if m == 0:
print(f"GCD is {n}")
if n == 0:
print(f"GCD is {m}")
while m != n:
if m >n:
m=m–n
if n >m:
n=n–m
print(f"GCD of two numbers is {m}")
Output
Enter first positive number8
Enter second positive number12
GCD of two numbers is 4
Read the value for m and n ➀–➁. If both m and n are zero then it is invalid input
because
zero cannot be divided by zero which is indeterminate ➂–➃. If either m or n is zero
then
the other one is gcd➄–➇. If the value of m >n then m = m – n or if n >m then n = n –
m.
The logic in line _– is repeated until the value of m is equal to the value of n ➈. Then
gcd
will be either m or n .
Program 3.11: Write Python Program to Find the Sum of Digits in a Number
number = int(input('Enter a number'))
result = 0
remainder = 0
while number != 0:
remainder = number % 10
Program to Repeatedly Check for the Largest Number Until theUser Enters
“done”
largest_number = int(input("Enter the largest number initially"))
check_number = input("Enter a number to check whether it is largest or not")
while check_number != "done":
if largest_number>int(check_number):
print(f"Largest Number is {largest_number}")
else:
largest_number = int(check_number)
print(f"Largest Number is {largest_number}")
check_number = input("Enter a number to check whether it is largest or not")
Output
Enter the largest number initially 5
Enter a number to check whether it is largest or not 1
Largest Number is 5
Enter a number to check whether it is largest or not 10
Largest Number is 10
Enter a number to check whether it is largest or not 8
Largest Number is 10
Enter a number to check whether it is largest or not done
Output:
b
a
n
a
n
a
Example 2
languages = ['Swift', 'Python', 'Go', 'JavaScript']
output:
Swift
Python
Go
JavaScript
The range () function:
We can generate a sequence of numbers using range() function. range (10)
will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range
(start,stop,step_size). step_size defaults to 1, start to 0 and stop is end of
object if not provided.
This function does not store all the values in memory; it would be
inefficient. So, it remembers the start, stop, step size and generates the next
number on the go.
Write a Program to Find the Sum of All Odd and Even Numbers
up to a Number Specified by the User.
number = int(input("Enter a number"))
even = 0
odd = 0
for i in range(number):
if i% 2 == 0:
even = even + i
else:
odd = odd + i
print(f"Sum of Even numbers are {even} and Odd numbers are {odd}")
Output
Enter a number 10
Sum of Even numbers are 20 and Odd numbers are 25
The break and continue statements provide greater control over the execution of
codein a loop. Whenever the break statement is encountered, the execution control
immediately jumps to the first instruction following the loop. To pass control to the
next iteration without exiting the loop, use the continue statement. Both continue and
break statements can be used in while and for loops.
Ex1:
ex 3
# program to find first 5 multiples of 6
i=1
while (i<=10):
print('6 * ',(i), '=',6 * i)
if i>= 5:
break
i=i+1
Output
6* 1=6
6* 2 = 12
6* 3 = 18
6* 4 = 24
6* 5 = 30
Example
n=0
while True:
print(f"The latest value of n is {n}")
n=n+1
if n >5:
print(f"The value of n is greater than 5")
break
Output
The latest value of n is 0
The latest value of n is 1
The latest value of n is 2
The latest value of n is 3
The latest value of n is 4
The latest value of n is 5
The value of n is greater than 5
1. # Python program to find the largest number among the three input numbers
2. # take three numbers from user
3. num1 =float(input("Enter first number: "))
4. num2 =float(input("Enter second number: "))
5. num3 =float(input("Enter third number: "))
6.
7. if(num1 > num2)and(num1 > num3):
8. largest = num1
9. elif(num2 > num1)and(num2 > num3):
10. largest = num2
11. else:
12. largest = num3
13. print("The largest number is",largest)
Function in python
Functions in python are basically a block of code which gets executed when it is
invoked.
Syntax:
Def function_name(arguments):
Statements
return (values)
def greet():
print('Hi')
This example shows the simplest structure of a function. A function has two main
parts: a function definition and body.
1) Function definition
A function definition starts with the def keyword and the name of the function
(greet). If the function needs some information to do its job, you need to specify it
inside the parentheses (). The greet function in this example doesn’t need any
information, so its parentheses are empty.
The function definition always ends in a colon (:).
2) Function body
All the indented lines that follow the function definition make up the function’s
body. The line print('Hi') is the only line of actual code in the function body. The
greet() function does one task: print('Hi').
Calling a function
When you want to use a function, you need to call it. A function call instructs
Python to execute the code inside the function.
To call a function, you write the function’s name, followed by the information that
the function needs in parentheses.
The following example calls the greet() function. Since the greet() function doesn’t
need any information, you need to specify empty parentheses like this: