Unit-1 Notes (1)
Unit-1 Notes (1)
COMPILER INTERPRETER
A compiler takes the entire An interpreter takes the single
program in one go. line of code at a time.
A compiler generates an An interpreter never produces
intermediate machine code. any intermediate code.
Error are displayed after entire Errors are displayed for every
program is checked. (If any) instruction is interpreted. (If
any)
Memory requirements is more. Memory requirement is less.
•The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
•In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
•In January1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
•In October 2000, Python 2.0 added new features such as list comprehensions, garbage
collection systems.
•On December 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
•ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
The programmer writes the code, The programmer writes the code and
compiles it, and executes it. then runs it.
The code is compiled into an The code is directly interpreted by the
executable file. Python interpreter.
The programmer must declare The programmer does not need to
variables before using them. declare variables before using them.
The programmer needs to specify the The programmer does not need to
data type of the variables. specify the data type of the variables.
Python Indentations
Where in other programming languages the
indentation in code is for readability only, in Python
the indentation is very important.
Python uses indentation to indicate a block of code.
Example:- if 5 > 2:
print("Five is greater than two!")
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python
will ignore the rest of the line:
Example
print("Hello, World!") #This is a comment
Python Comment
Multi Line Comments
Python does not really have a syntax for multi line
comments.
To add a multiline comment you could insert a # for each
line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.
Python Comment
Multi Line Comments
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 you comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the
code, but then ignore it, and you have made a multiline comment.
Python USER INPUT
User Input:
•Python allows for user input.
•That means we are able to ask the user for input.
•The method is a bit different in Python 3.X than Python 2.7.
•Python 3.6 uses the input() method.
•Python 2.7 uses the raw_input() method.
Python 3.6
username = input("Enter username:")
print("Username is: " + username)
Python 2.7
username = raw_input("Enter username:")
print("Username is: " + username)
Python Variables
Creating Variables
Variables are containers for storing data values.
Unlike other programming languages, Python has no
command for declaring a variable.
A variable is created the moment you first assign a
value to it.
Example
x=5
y = "John"
print(x)
print(y)
Python Variables
Variables do not need to be declared with any
particular type and can even change type after they
have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
String variables can be declared either by using single
or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Python Variables
Variable Names
A variable can have a short name (like x and y) or a
more descriptive name (age, carname, total_volume).
Rules for Python variables:
A variable name must start with a letter or the
underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE
are three different variables)
*Remember that variable names are case-sensitive
Python Variables
Assign Value to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one
line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Python Variables
Output Variables
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Python Numbers
Int
Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length.
Example
Integers:
x ,y, z = 1, 35656222554887711, 54646543
print(x)
print(y)
print(z)
Python Numbers
Float
Float, or "floating point number" is a number, positive
or negative, containing one or more decimals.
Example
Floats:
x ,y, z = 1.0, 1.015, -0.25
print(x)
print(y)
print(z)
Python Numbers
Float can also be scientific numbers with an "e" to
indicate the power of 10.
Example
Floats:
x , y ,z= 35e3, 12E4, -87.7e100
print(x)
print(y)
print(z)
Python Numbers
Complex
Complex numbers are written with a "j" as the
imaginary part:
Example
Complex:
x, y, z = 3+5j, 5j, -5j
print(x)
print(y)
print(z)
Python Numbers
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
Example
Convert from one type to another:
x = 1 # int y = 2.8 # float z = 1j # complex
a = float(x) #convert from int to float
b = int(y) #convert from float to int
c = complex(x) #convert from int to complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
Python Numbers
Random Number
Python does not have a random() function to make a
random number, but Python has a built-in module
called random that can be used to make random
numbers:
Example
Import the random module, and display a random
number between 1 and 9:
import random
print(random.randrange(1,10))
Python Numbers
Reserved Words (Keywords):
Keywords in Python are reserved words that can not be used as a
variable name, function name, or any other identifier.
Python Expression
A combination of operands and operators is called
an expression. The expression in Python produces some value or
result after being interpreted by the Python interpreter.
Ex:
x = 25 # a statement
x = x + 10 # an expression
print(x)
•Python creates a variable name the first time when they are assigned a
value.
Augmented assignment :
x=2
x += 1 # equivalent to: x = x + 1
print(x)
Python Operators
Python divides the operators in the following
groups:
•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators
Python Operators (Arithmetic)
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
(Result in float)
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Operators (Assignment)
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Python Operators (Comparison)
Operator Name Example
== Equal x == y
!= Not equal x != y
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
Python Operators (Identity)
Identity operators are used to compare the objects, not if they are equal, but
if they are actually the same object, with the same memory location:
a=5
b="hello"
c=1.2
d=1+5j
print("The type of a is : ",type(a))
print("The type of b is : ",type(b))
print("The type of c is : ",type(c))
print("The type of d is : ",type(d))
OUTPUT
PROGRAMS:
PROGRAMS 2: WAP to find the square root of a number.
OUTPUT
CONDITIONAL STATEMENTS
Decision making is anticipation of conditions occurring while execution
of the program and specifying actions taken according to the conditions.
Following is the general form of a typical decision making structure found
in most of the programming languages −
Python programming language
assumes any non-
zero and non-null values as
TRUE,
and
if it is either zero or null, then
it is assumed as FALSE value.
CONDITIONAL STATEMENTS
Python programming language provides following
types of decision making statements:
•If statements:
•An if statement consists of a boolean expression
followed by one or more statements.
•If-else statements:
•An if statement can be followed by an optional else
statement, which executes when the boolean expression
is FALSE.
•Nested if else statements:
•You can use one if or else if statement inside
another if or else if statement(s).
CONDITIONAL STATEMENTS
If statements:
Syntax:
if (expression):
statement(s)
Ex:
val=5
if (val==5):
print("I am five")
OUTPUT:
CONDITIONAL STATEMENTS
If statements:
EX: Program to check the given number is Negative
if num<0:
OUTPUT:
CONDITIONAL STATEMENTS
If-else statements:
Syntax:
if (expression):
statement(s)
else:
Ex: statement(s)
val=6
if (val==5):
print("I am five")
else:
print(“I am not five”)
OUTPUT:
CONDITIONAL STATEMENTS
If-else statements:
EX: Program to check the given number is Positive or Negative
if num<0:
print("The number {} is Negative: ".format(num))
else:
print("The number {} is Positive: ".format(num))
OUTPUT:
CONDITIONAL STATEMENTS
If-elif-else statements:
Syntax: if (expression):
statement(s)
elif (exp):
statement(s)
else:
statement(s)
Ex:
val=10
if val>10:
print("Value is greater than 10")
elif (val<10):
print("value is less than 10")
else:
print("Value is equal to 10")
OUTPUT:
CONDITIONAL STATEMENTS
If-elif-else statements:
EX: Program to check the given Year is Leap or Not
year=int(input("Enter the year:: "))
else:
print("The year {0} is NOT Leap year. ".format(year))
OUTPUT:
CONDITIONAL STATEMENTS
Nested If-else statements:
Syntax: var = 100
if expression1: if var < 200:
statement(s) print (“Value is less than 200”)
else: else :
statement(s) print (“This is inner else”)
else:
else: print (“This is out else part”)
statement(s)
CONDITIONAL STATEMENTS
Nested If-else statements:
EX: Program to check the largest number of given three numbers
num1=float(input("Enter the First number:: "))
num2=float(input("Enter the Second number:: "))
num3=float(input("Enter the Third number:: "))
if num1>num2:
if (num1>num3):
print("The number {} is the largest number.".format(num1))
else:
print("The number {} is the largest number.".format(num3))
elif (num2>num3):
print("The number {} is the largest number.".format(num2))
else:
print("The number {} is the largest number.".format(num3))
Example:
1. Write a program to find small number of two numbers (if)
2. Write a Program to input age and check whether the person is eligible to vote or not.
3. Write a program to find biggest number among three numbers.
Python For Loops
Python For Loops
• A for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set, or a
string).
• This is less like the for keyword in other
programming languages, and works more like an
iterator method as found in other object-orientated
programming languages.
• With the for loop we can execute a set of
statements, once for each item in a list, tuple, set
etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "kiwi", "cherry"]
for x in fruits:
print(x)
Python While Loops
Looping Through a String
Even strings are iterable objects, they contain a sequence of
characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
The pass Statement
• if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to
avoid getting an error.
• Example
a = 33
b = 200
if b > a:
pass
The break Statement
• With the break statement we can stop the loop even if the
while condition is true:
• Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The break Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
The continue Statement
• With the continue statement we can stop the current iteration,
and continue with the next:
• Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The continue Statement
fruits = ["apple", "banana", "cherry"]
The continue Statement
for x in fruits:
if x == "banana":
continue
print(x)
The range() Function
Example
Using the range() function:
for x in range(6):
print(x)
for x in range(2, 6):
print(x)
Nested Loops
for x in adj:
for y in fruits:
print(x, y)