Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Chapter 11 Python Powerpoint Explanation

The document provides an introduction to Python, covering interactive and script modes, as well as fundamental concepts such as tokens, keywords, variables, literals, and data types. It explains how to take user input, handle errors, and perform type conversion. Additionally, it outlines operators in Python, including unary, binary, and bitwise operators, with examples for clarity.

Uploaded by

hayzkids
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Chapter 11 Python Powerpoint Explanation

The document provides an introduction to Python, covering interactive and script modes, as well as fundamental concepts such as tokens, keywords, variables, literals, and data types. It explains how to take user input, handle errors, and perform type conversion. Additionally, it outlines operators in Python, including unary, binary, and bitwise operators, with examples for clarity.

Uploaded by

hayzkids
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

PYTHON

STARTING PYTHON

To work in interactive mode, follow the process given below:

Click start button All Programs Python 3.6.x IDLE Or

Click start button All Programs Python 3.6.x Python


(command line)
Modes in Python
Interactive Mode

• Interactive modes – one command at a time


• Python executes the given command and gives the output.
• In interactive mode we type command at IDLE prompt ( >>> )
• For e.g if you type 20 + 30 in from of IDLE prompt

>>> 20 + 30 (command give by user)


50 (output given by python)

From the above example you can see than at >>> we have to
just give the command to execute and python we execute it if it
is error free otherwise gives an error.
Script Mode

In Python IDLE :

Click File New


In new window type the commands you want to save in program

For example:

print(“Hello World!”)

File Save to save file. Give extension .py to execute it as python


script
• Script Mode – multiple commands can be saved in a file as a

• program and then we can execute the entire program

• we type Python program in a file and then use the interpreter to


execute the content from the file.

• Working in interactive mode is convenient for beginners and for


testing small pieces of code, as we can test them immediately.
But for coding more than few lines, we should always save our
code so that we may modify and reuse the code
Save the
program
and press
F5
( )
TOKENS
In a passage of text, individual words and punctuation
marks are called tokens or lexical units or lexical
elements. The smallest individual unit in a program is
known as Tokens. Python has following tokens:

 Keywords
 Identifiers(Name)
 Literals
 Operators
 Punctuators
KEYWORDS
Keywords are the reserved words and have special
meaning for python interpreter. Every keyword is
assigned specific work and it can be used only for that
purpose.
A partial list of keywords in Python is

VINOD KUMAR VERMA, PGT(CS), KV OEFKANPUR&


SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
VAR IABLES

Variables are the names storage location in the memory

Rules for Naming a Python Variable:

 Is an arbitrarily long sequence of letters and digits


 The first character must be letter or underscore
 Upper and lower case are different
 The digits 0-9 are allowed except for first character
 It must not be a keyword
 No special characters are allowed other than underscore is
allowed.
 Space not allowed
The following are some valid Variables
GradePay File_12_2018 JAMES007
GRADEPAY _ismarried _to_update

The following are some invalid Variables


Literals / Values

 Literals are data items that have a fixed


value. Python supports several kinds of
literals:
🞑 String Literal
🞑 Numeric Literals
🞑 Boolean Literals
🞑 Special Literals – None
String Literals
 It is a collection of character(s) enclosed in a
double or single quotes
 Examples of String literals
🞑 “Python”
🞑 “Mogambo”
🞑 "123456‟
🞑 "Hello How are your‟
🞑 "$‟, "4‟,”@@”
 In Python both single character or multiple
characters enclosed in quotes such as “kv”, “ kv
‟, ‟ * ‟ , ”+” are treated as same
Non-Graphic (Escape) characters

 They are the special characters which cannot


be type directly from keyboard like
backspace, tabs, enter etc. When the
characters are typed they perform some
action. These are represented by escape
characters. Escape characters are always
begins from backslash(\) character.
List of Escape characters
Escape Sequence What it does Escape Sequence What it does
\\ Backslash \r Carriage return
\‟ Single quotes \t Horizontal tab
\” Double quotes \uxxxx Hexadecim
al value(16
bit)
\a ASCII bell \Uxxxx Hexadecim
al value(32
bit)
\b Back Space \v vertical tab
\n New line \ooo Octal value
String type in Python
 Python allows you to have two string types:
🞑 Single Line Strings
 The string we create using single or double quotes are
normally single-line string i.e. they must terminate in one line.
 For e.g if you type as
 Name="KV and pressenter
 Python we show you an error “EOL while scanning string literal”
 The reason is quite clear, Python by default creates single-line
string with both single quotes and it must terminate in the same
line by quotes
String type in Python
 Multiline String
🞑 Sometimes we need to store sometext acrossmultiple
lines. For that Python offers multiline string.
🞑 Tostore multiline string Python provides two ways:
(a) By adding a backslash at the end ofnormal Single / Double
quoted string. For e.g.
>>> Name="1/6 Mall Road \
Kanpur"
>>> Name
'1/6 Mall RoadKanpur'
>>>
String type in Python
 Multiline String
(b) By typing text in triple quotation marks
for e.g.
>>> Address="""1/7 Preet Vihar
New Delhi
India"""
>>> print(Address)
1/7 Preet Vihar
New Delhi
India
>>> Address
'1/7 Preet Vihar\nNew Delhi\nIndia'
Size of String
 Python determines the size of string as the count of characters in the string.
For example size of string “xyz” is 3 and of “welcome” is 7. But if your
string literal has an escape sequence contained in it then make sure to count
the escape sequence as one character. For e.g.

String Size
“\\‟ 1
“abc‟ 3
“\ab‟ 2
“Meera\‟s Toy” 11
“Vicky‟s” 7

 You can check these size using len() function of Python. For example
 >>>len(„abc‟) and press enter, it will show the size as 3
Size of String
 For multiline strings created with triple quotes : while calculating size
the EOL character as the end of line is also counted in the size. For
example, if you have created String Address as:
>>> Address="""Civil lines
Kanpur"""
>>> len(Address)
18
 For multiline string created with single/double quotes the EOL is not
counted.
>>> data="ab\
bc\
cd"
>>> len(data)
6
Numeric Literals
 The numeric literals in Python can belong to any of
the following numerical types:
1)Integer Literals: it contain at least one digit and must
not contain decimal point. It may contain (+) or (-) sign.
🞑 Typesof Integer Literals:
a) Decimal : 1234, -50, +100
b)Octal : it starts from symbol 0o (zero followed by
letter ‘o’)
 For e.g. 0o10 represent decimal 8
Numeric Literals
>>> num = 0o10
>>> print(num)
It will print the value 8

c) Hexadecimal : it starts from 0x (zero followed by


letter ‘x’)
>>> num = 0oF
>>> print(num)
it will print the value 15
Numeric Literals
 2) Floating point Literals: also known as real
literals. Real literals are numbers having fractional
parts. It is represented in two forms Fractional Form
or Exponent Form
 Fractional Form: it is signed or unsigned with decimal point
🞑 For e.g. 12.0, -15.86, 0.5, 10. (will represent 10.0)
 Exponent Part: it consists of two parts “Mantissa” and
“Exponent”.
🞑 For e.g. 10.5 can be represented as 0.105 x 102 = 0.105E02 where
0.105 is mantissa and 02 (after letter E) is exponent
Points to remember
 Numeric values with commas are not considered int or float value, rather Python
treats them as tuple. Tuple in a python is a collection of values or sequence of values.
(will be discussed later on)
 You can check the type of literal using type() function. For e.g.
>>> a=100
>>> type(a)
<class 'int'>
>>> b=10.5
>>> type(b)
<class 'float'>
>>> name="hello“
>>> type(name)
<class 'str'>
>>> a=100,50,600
>>> type(a)
<class 'tuple'>
Boolean Literals
A Boolean literals in Python is used to represent one of the two
Boolean values i.e. True or False
These are the only two values supported for Boolean Literals
For e.g.

>>> isMarried=True
>>> type(isMarried)
<class 'bool'>
Special Literals None
Python has one special literal, which is None. It indicate absence
of value. In other languages it is knows as NULL. It is also used
to indicate the end of lists in Python.

>>> salary=None
>>> type(salary)
<class 'NoneType'>
Complex Numbers
Complex: Complex number in python is made up of two floating point values,
one each for real and imaginary part. For accessing different parts of
variable (object) x; we will use x.real and x.image. Imaginary part of the
number is represented by “j” instead of “I”, so 1+0j denotes zero imaginary.
part.
Example
>>> x = 1+0j
>>> print x.real,x.imag
1.0 0.0
Example
>>> y = 9-5j
>>> print y.real, y.imag
9.0 -5.0
Conversion from one type to another
 Python allows converting value of one data type to another data
type. If it is done by the programmer then it will be known as type
conversion or type casting and if it is done by compiler automatically
then it will be known as implicit type conversion.
Example of Implicit type conversion
>>> x = 100
>>> type(x)
<type 'int'>
>>> y = 12.5
>>> type(y)
<type 'float'>
>>> x=y
>>> type(x)
<type 'float'> # Here x is automatically converted to float
Conversion from one type to another
Explicit type conversion
Toperform explicit type conversion Python provide functions like
int(), float(), str(), bool()
>>> a=50.25
>>> b=int(a)
>>> print b
50
Here 50.25 is converted to int value 50
>>>a=25
>>>y=float(a)
>>>print y
25.0
Simple Input and Output
 In python we can take input from user using the built-in function
input().
 Syntax
variable = input(<message to display>)
Note: value taken by input() function will always be of String type, so by
default you will not be able to perform any arithmetic operation on variable.
>>> marks=input("Enter your marks ")
Enter your marks 100
>>> type(marks)
<class 'str'>
Hereyoucanseeevenwe are enteringvalue100 butit will be treated as
string and will not allow any arithmetic operation
Simple Input and Output
>>> salary=input("Enter your salary ")
Enter your salary 5000
>>> bonus= salary*20/100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Reading / Input of Numbers
 Now we are aware that input() function value will
always be of string type, but what to do if we want
number to be entered. The solution to this problem is
to convert values ofinput() to numeric type usingint()
or float() function.
Possible chances of error while taking
input as numbers
1. Entering float value while converting to int
>>> num1=int(input("Enter marks "))
Enter marks 100.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '100.5‘

2. Entering of values in words rather than numeric


>>> age=int(input("What is your age "))
What is your age Eighteen
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: Eighteen'
Possible chances of error while taking
input as numbers
3. While input for float value must be compatible. For e.g.
Example 1
>>> percentage=float(input("Enter percentage "))
Enter percentage 12.5.6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '12.5.6'

Example 2
>>> percentage=float(input("Enter percentage "))
Enter percentage 100 percent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: „100 percent'
Program 1
Open a new script file and type the following code:

num1=int(input("Enter Number 1 "))


num2=int(input("Enter Number 2 "))
num3 = num1 + num2
print("Result =",num3)

Save and execute by F5 and observe the result


Operators
 are symbol that perform specific operation when
applied on variables. Take a look at the expression:
(Operator)
10 + 25 (Operands)
Above statement is an expression (combination
of operator and operands)
i.e. operator operates on operand. some operator requires two
operand and some requires only one operand to operate
Types of Operators
 Unary operators: are those operators that require
one operand to operate upon. Following are some
unary operators:

Operator Purpose
+ Unary plus
- Unary minus
~ Bitwise
complement
Not Logical negation
Types of Operators
 Binary Operators: are those operators that require two
operand to operate upon. Following are some Binary
operators:
1. Arithmetic Operators
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
// Floor division
Example
>>> num1=20
>>> num2=7
>>> val = num1 % num2
>>> print(val)
6
>>> val = 2**4
>>> print(val)
16
>>> val = num1 / num2
>>> print(val)
2.857142857142857
>>> val = num1 / / num2
>>> print(val)
2
Bitwise operator
Operator Purpose Action
Bitwise operator works
& Bitwise AND Return 1 if both on the binary value of
inputs are 1 number not on the actual
^ Bitwise XOR Return 1, if value. For example if 5
the number is passed to these
of 1 in input operator it will work on
101 not on 5. Binary of
is in odd
5 is 101, and return the
| Bitwise OR Return 1 if result in decimal not in
any input is binary.
1
Example
Binary of 12 is 1100 and 7 is 0111, so applying &
1100
0111
-------
Guess the output with
0100 Which is equal to decimal value 4
| and ^ ?

Let us see one practical example, To check whether entered number is divisible of 2 (or in
a power of 2 or not) like 2, 4, 8, 16, 32 and so on
Tocheck this, no need of loop, simplyfind the bitwise & ofnand n-1, if the result is0 it
meansit is in power of 2 otherwise not

Here we can see


Later on by using „if‟ we can print Here we can see 0,
16, it means 24 is
it means 32 is in
meaningful message power of 2 not in power of 2
Operators Purpose
<< Shift left
>> Shift right

Identity Operators
Operators Purpose
is Is the Identity same?
is not Is the identity not same?
Relational Operators
Operators Purpose
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not equal to
Logical Operators
Operators Purpose
and Logical AND
or Logical OR
not Logical NOT
Assignment Operators
Operators Purpose
= Assignment
/= Assign quotient
+= Assign sum
-= Assign difference
*= Assign product
**= Assign Exponent
//= Assign Floor division
Membership Operators
Operators Purpose
in Whether variable in
sequence
not in Whether variable not in
sequence
Comments
 Comments are additional information written in a
program which is not executed by interpreter i.e.
ignored by Interpreter. Comment contains information
regarding statements used, program flow, etc.
 Comments in Python begins from #

 Python supports 3 ways to enter comments:

1. Full line comment


2. Inline comment
3. Multiline comment
Comments
 Full line comment
Example:
#This isprogram of volume of cylinder
 Inline comment

Example
area = length*breadth # calculating area of rectangle
 Multiline comment

Example 1 (using #)
# Program name: area of
circle # Date: 20/07/18
#Language : Python
Comments
Multiline comment (using “ “ “) triple quotes
Example
“““
Program name : swapping of two number
Date : 20/07/18
Logic : by using third variable
FFF
Output through print()

 Python allows to display output using print().


 Syntax:
print(message_to_print[,sep=“string”,end=“string”])
Example 1
print(“Welcome”)
Example 2
Age=20
print(“Your age is “, Age)
Output through print()
Example 3
r = int(input("Enter Radius "))
print("Area of circle is ",3.14*r*r)

Note: from the Example 2 and Example 3 we can


observe that while printing numeric value print() convert
it into equivalent string and print it. In case of expression
(Example 3) it first evaluate it and then convert the result
to string before printing.
Output through print()
Note:
print() automatically insert space between different values
given in it. The default argument of sep parameter of
print() is space(‘ ‘) .
Example
print(“Name is”,”Vicky”)
Output
Name is Vicky
Output through print()
Note:
Python allows to change the separator string.
Example
print(“Name is”,”Vicky”,”Singh”,sep=“##”)
Output
Name is ##Vicky##Singh
Output through print()
Note:
Be default each print statement print the value to next
line. The default value of end is “\ n”
Example
print(“Learning Python”)
print(“Developed by Guido Van Rossum”)
Output
Learning Python
Developed by Guido Van Rossum
Output through print()
Note:
We can change the value of end to any other value.
Example
print(“Learning Python”,end=“ “)
print(“Developed by Guido Van Rossum”)
Output
Learning Python Developed by Guido Van Rossum
Output through print()
Can you Guess the output
Name=“James”
Salary=20000
Dept=“IT”
print(“Name is “,Name,end=“@”)
print(Dept)
print(“Salary is “,Salary)
Just a minute…
 What is the difference between keywords and
identifiers
 What are literals in Python? How many types of
literals in python?
 What will be the size of following string

„\a‟ , “\a” , “Reena\‟s”, „\”‟, “It‟s”, “XY\ , “ “ “XY⮠


YZ” YZ”””
 How many types of String in python?
Just a minute…

 What are the different ways to declare multiline String?


 Identify the type of following literal:

41.678, 12345, True, „True‟,“False”, 0xCAFE, 0o456,0o971


 Difference between Expression and Statement

 What is the error inn following python program:

print(“Name is “, name)

Suggest a solution
Just a minute…

 Which of the following string will be the syntactically


correct? State reason.
1. “Welcome to IndiaF
2. „Heannounced “Start the matchF very loudly‟
3. “Sayonara‟
4. „Revise PythonChapter 1‟
5. “Bonjour
6. “Honesty isthe „best‟policyF
Just a minute…

 The following code is not giving desired output. We


want to enter value as 100 and obtain output as 200.
Identify error and correct the program

num= input("enter any number")


double_num= num* 2
Print("Double of",num,"is",double_num)
Just a minute…

 Why the following code is giving error?

Name="James"
Salary=20000 Dept="IT"
print("Name is ",Name,end='@') print(Dept)
print("Salary is ",Salary)
Just a minute…

 WAP to obtain temperature in Celsius and convert it into


Fahrenheit.
 What will be the output of following code:
x, y = 6,8
x,y = y, x+2
print(x,y)
 What will be the output of following code:
x,y = 7,2
x,y,x = x+4, y+6, x+100
print(x,y)

You might also like