0% found this document useful (0 votes)
17 views11 pages

CH 5 Getting Started With Python Part 2

Uploaded by

ullaskphu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views11 pages

CH 5 Getting Started With Python Part 2

Uploaded by

ullaskphu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 11

Getting Started with Python (continue )

Precedence of Operators
• In Python, operators have different levels of precedence, which determine the order in
which they are evaluated.

• Higher precedence operator is evaluated before the lower precedence operator

 Unary Operator is an operator that operates on a single operand, meaning it affects


only one value or variable. Ex: ++a , a--

 Binary Operator is an operator that operates on two operands, meaning it affects


two values or variables, ex: a+b , num = a-b

Usage of Python Data Types


• List: if we store the names of students of a class in a list, then it is easy to update the
list when some new students join or some leave the course

• Tuples: Tuples are used when we do not need any change in the data. For example,
names of months in a year.

• Set: When we need uniqueness of elements and to avoid duplicacy it is preferable to


use set, For example, a group of players in a cricket team is a set.

• Dictionary :If our data is being constantly modified or we need a fast lookup based
on a custom key ,A mobile phone book is a good application of dictionary.

EXPRESSIONS
• An expression is defined as a combination of constants, variables, and operators.

• A value or a standalone variable is also considered as an expression but a standalone


operator is not an expression.

Examples of valid expressions are given below.


OPERATORS
An operator is used to perform specific mathematical or logical operation on values. The
values that the operators work on are called operands.

• OPERATORS: These are the special symbols. Eg- + , * , /, etc.

• OPERAND: It is the value on which the operator is applied. Ex- 10,num .

Types of operators

 Arithmetic Operators
 Relational Operators
 Assignment Operators
 Logical Operators
 Identity Operators
 Membership Operators

Arithmetic Operators
Arithmetic operators that are used to perform the four basic arithmetic operations as well as
modular division, floor division and exponentiation.

Example

a=7

b=2

str1= "Hello"

str2= "Sjpuc"

# addition

print ('Sum: ', a + b)

print("Add :" , str1 + str2)

# subtraction

print ('Subtraction: ', a - b)

# multiplication

print ('Multiplication: ', a * b)


print("Multiplication of str1 is :" , str1*a)

# division

print ('Division: ', a / b)

# floor division

print ('Floor Division: ', a // b)

# modulo

print ('Modulo: ', a % b)

# a to the power b

print ('Power: ', a ** b)

print ('Power: ', a **3)

Relational Operators
• Relational operator compares the values of the operands on its either side and
determines the relationship among them

• It either returns True or False as an output

• It is also called as comparison operations

example

a=5

b=2

str1="Happy"

str2="DAY"

# equal to operator

print('a == b =', a == b)
print("Is str1 equal to str2:", str1==str2 ,"\n")

# not equal to operator

print('a != b =', a != b)

print("Is str1 not equal to str2:", str1!=str2,"\n")

# greater than operator

print('a > b =', a > b)

print("Is str1 greater than str2:", str1 > str2,"\n")

Assignment Operators
• Assignment operator assigns or changes the value of the variable on its left.

Examples

# assign 10 to num1

num1 = 10

# assign 5 to num2

num2 = 5

# assign the sum of a and b to a

num1 += num2 # num1 = num1 + num2

print(num1)

Logical Operators
• There are three logical operators supported by Python. These operators (and, or, not)

• Logical Operators are written in lower case only.

• The logical operator evaluates to either True or False based on the logical operands on
either side.
Example

• x=5

print(x > 3 and x < 10)

# returns True because 5 is greater than 3 AND 5 is less than 10

o/p:True

• x=5

print(x > 3 or x < 4)

# returns True because one of the conditions are true (5 is greater than 3, but 5 is not
less than 4)

o/p: True

• x=5

print(not(x > 3 and x < 10))

# returns False because not is used to reverse the result

o/p: False

Identity Operators
• Is and is not are used to check if two values are located at the same memory location

• variables are referring to the same object or not. There are two identity operators
Example

Num1=5

Type(num1) is int

o/p True

Num 1 =5

num2 = 20

num2 is not Num1

o/p True

Membership Operators
Membership operators are used to check if a value is a member of the given sequence or
not

(in , not in )

Example

message = 'Hello world'

dict1 = {1:'a', 2:'b'}

 # check if 'H' is present in message string

print('H' in message) # prints True

 # check if 'hello' is present in message string

print('hello' not in message) # prints True

 # check if '1' key is present in dict1

print(1 in dict1) # prints True

 # check if 'a' key is present in dict1

print('a' in dict1) # prints False

Input and Output

Input() function
• we have the input() function for taking values entered by input device such as a
keyboard.

• It accepts all user input (whether alphabets, numbers or special character) as string.

• The syntax for input() is: variable = input([Prompt])

• Prompt is the string we may like to display on the screen prior to taking the input, but
it is optional.

• .The input() takes exactly what is typed from the keyboard, converts it into a string

Example

fname = input("Enter your first name: ")

o/p Enter your first name: ram

age = input("Enter your age: ")


o/p Enter your age: 19

datatype ( ) function
• We can change the datatype of the string data accepted from user to an appropriate
numeric value.

• For example, the int() function will convert the accepted string to an integer

age = int(input("Enter your age: "))

o/p Enter your age: 19

Print(type(age)

Output function()
 Print( )
 Python uses the print() function to output data to standard output device — the
screen.
 The function print() evaluates the expression before displaying it on the screen.
 The syntax for print() is: print(value [, ..., sep = ' ', end = '\n'])

• sep='separator' (optional): The objects are separated by sep. The default value of
sep is ' '.

• end='end' (optional): it determines which object should be print at last.\n

ex:

STATEMENT

In Python, a statement is a unit of code that the Python interpreter can execute
Tokens in Python / lexical units
• Tokens or lexical units are the smallest units in the python program.

• A token is a set of one or more characters having a meaning together.

• There are 5 types of tokens in python which are listed below:

 Keywords

 Identifiers

 Literals

 String literals
 Numeric literal
 Boolean literal
 literal collections

 Operators

 Punctuators

Python Constants

• A Python Constant is a variable whose value cannot be changed throughout the


program.
Type conversion
• Changing the data type of a python variable, from one data type to another data type
is called type conversion.

Type conversion can happen in two ways:

Explicit conversion
 Explicit conversion, also called type casting
 Explicitly (forced)
 programmer specifies for the interpreter to convert a data type to another type
 Risk of loss of information since we are forcing an expression to be of a specific
type
 int(x) , str(x) ,float(x), chr(x)
 General format: (new_data_type) (expression)

Example:

Program of explicit type conversion from int to float.

#Explicit type conversion from int to float


num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output:
30
<class 'int'>
30.0
<class 'float'>

 The interpreter cannot convert an integer value to string implicitly.


 It may appear quite intuitive that the program should convert the integer value to a
string depending upon the usage.
 the interpreter may not decide on its own when to convert as there is a risk of loss
of information.
 Python provides the mechanism of the explicit type conversion so that one can
clearly state the desired outcome
Program to show explicit type casting.
#Explicit type casting

priceIcecream = 25

priceBrownie = 45

totalPrice = priceIcecream + priceBrownie

print("The total in Rs." + str(totalPrice))

Output:

The total in Rs.70

Implicit Conversion
 data type conversion is done automatically by Python and is not instructed by the
programmer.
 Implicit conversion also known as coercion
 converting data into a wider-sized data type without any loss of information.

Program to show implicit conversion from int to float.


#Implicit type conversion from int to float
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float
and an integer
print(sum1)
print(type(sum1))
Output:
30.0
<class 'float'>

DEBUGGING
• The process of identifying and removing such mistakes, also known as bugs or errors,
from a program is called debugging.
• Errors occurring in programs can be categorised as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors

i) Syntax errors
• Syntax is a rules of a language
• If any syntax error is present, the interpreter shows error message(s) and stops the
execution there.
• Ex : parentheses must be in pairs
 9+(3-1 error occurs
 9+(3-1) so the expression is syntactically correct.

ii) Logical Errors

A logical error produces an undesired output


program interprets successfully even when logical errors are present in it
The only evidence to the existence of logical errors is the wrong output.
Logical errors are also called semantic errors
Ex: (10 + 12)/2 to give the correct output as 11.

iii) Runtime errors


• Occurs only when the program is executed.
• Syntax will be correct but cannot be executed by interpreter
• When user give incorrect input
Ex:
Var=int(input(“Enter the number : ”))
o/p : Enter the number : apple # runtime error
o/p : Enter the number : 45 #valid

-------------END--------------

You might also like