0% found this document useful (0 votes)
21 views54 pages

4 Basic Elements of Python

Uploaded by

229x1a3256
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)
21 views54 pages

4 Basic Elements of Python

Uploaded by

229x1a3256
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/ 54

Basic Elements of Python

COMMENTING IN PYTHON
• Comments in Python are preceded by a hash
symbol (#) on a line and called a line
comment.
• Three consecutive single quotation marks ‘’’
are used to give multiple comments or
comments on several lines at once and called
paragraph comment.
#Learn How to Comment in Python
print(‘I Learnt How to Comment in Python’)
‘’’ Amazing tool
in Python called Comment’’’
print(‘Bye’)
PYTHON CHARACTER SET
Python uses the following character set:
• Letters: Upper case and lower case letters
• Digits: 0,1,2,3,4,5,6,7,8,9
• Special Symbols: Underscore (_), (,), [,], {,}, +, -,
*, &, ^, %, $, #, !, Single quote(‘), Double
quotes(“), Back slash(\), Colon(:), and Semi
Colon (;)
• White Spaces: (‘\t\n\x0b\x0c\r’), Space, Tab.
Python Tokens

Keywords

Identifiers/
Variables

Tokens Operators

Delimiters

Literals
Literals
• Literals are numbers or strings or characters that
appear directly in a program.
• values used for giving inputs to the program.
• A list of some literals in Python is as follows:
78 #Integer Literal
21.98 #Floating Point Literal
‘Q’ #Character Literal
“Hello” #String Literal
True/False #Boolean Literal
• Python also contains other literals, such as lists,
tuple and dictionary.
• Display Literals in Interactive Mode
>>> ‘Hello World’
‘Hello World’
Value and Type on Literals

• To know the exact type of any value, Python


offers an in-built method called type.
• The syntax to know the type of any value is
type (value)
>>> type(‘Hello World’)
<class ‘str’>
>>> type(123)
<class ‘int’>
Keywords
• Keywords are reserved words with fixed
meanings assigned to them.
• Keywords cannot be used as identifiers or
variables.
• The complete list of keywords supported by
Python.
Operators
Operator Type Operators

+ - * / // % ** Arithmetic Operator

== != <> <= >= Relational Operator

and not or Logical Operator

& | ~ ^ << >> Bitwise Operator


Delimiters
• Delimiters are symbols that perform a special
role in Python like grouping, punctuation and
assignment.
• Python uses the following symbols and symbol
combinations as delimiters.
()[]{}
,:.‘=;
+= -= *= /= //= %=
&= |= ^= >>= <<= **=
Identifier/Variable
• Identifier is the name used to find a variable,
function, class or other objects.
• All identifiers must obey the following rules.
An identifier:
– Is a sequence of characters that consists of letters,
digits and underscore
– Can be of any length
– Starts with a letter which can be either lower or upper
case
– Can start with an underscore ‘_’
– Cannot start with a digit
– Cannot be a keyword.
– All the Variables in Python are Case Sensitive.
PYTHON CORE DATA TYPE
• The main purpose of Fundamental Category
Data Types is that "To store Single Value".
• In Python Programming, we have 4 types in
Fundamental Category. They are
1) int
2) float
3) bool
4) complex
Integer
• 'int' is one of the pre-defined class and treated as
Fundamental Data Type.
• The purpose of 'int' is that "To store Integral /
whole numbers / Integer data (data without
decimal values)".
• Python Statements Outputs
>>> a=19
>>> print(a, type(a))--------19 <class 'int'>
>>> a=999
>>> print(a,type(a), id(a))--999 <class 'int'> 1802394655120
Integer
• With 'int' data, we can also store different types
of Values like Decimal Numbers, Binary Numbers,
Octal and Hexa Decimal Numbers.
• In Python Programming, We have 4 Number
Systems and whose values can be stored by using
int data type. They are
a) Decimal Number System (default):
• The Digits in Decimal Number are: 0 1 2 3 4 5 6
7 8 9
• The total Number of digits= 10
• The Base of Decimal Number System is 10
Integer
b) Binary Number System :
• The Digits in Binary Number System are: 0 1
• The total Number of digits= 2
• The Base of Binary Number System is 2
Storing Binary Number System data in Python Program
• To store binary number system data in python
Environment, the binary data must be preceded with
either '0b' or '0B'.
Syntax:- varname=0b Binary Data
(OR)
Syntax:- varname=0B Binary Data
• Even though we represent the binary data , internally, it
is converted into default number system (Decimal )
Integer
a) Binary Number System:
>>> a=0b1010
>>> print(a,type(a))--------10 <class 'int'>
>>> a=0B1111
>>> print(a,type(a))---------15 <class 'int'>
>>> a=ob1010--------NameError: name 'ob1010' is not defined
>>> a=0b10102-----SyntaxError: invalid digit '2' in binary literal
Integer
c) Octal Number System :
• The Digits in Octal Number System are: 0 1 2 3 4 5 6 7
• The total Number of digits= 8
• The Base of Octal Number System is 8
Storing Octal Number System data in Python Programming
• To store Octal number system data in python Environment,
the octal data must be preceded with either '0o' or '0O'.

Syntax:- varname=0o Octal Data


(OR)
Syntax:- varname=0O Octal Data

• Even though we represent the Octal data , internally, it is


converted into default number system (Decimal )
Integer
a) Octal Number System:
>>> a=0o15
>>> print(a,type(a))--------------13 <class 'int'>
>>> a=0o17
>>> print(a,type(a))------------15 <class 'int'>
>>> a=0o682----SyntaxError: invalid digit '8' in octal literal
Integer
d) Hexa Deciaml Number System :
• The Digits in Hexa Decimal Number System are: 0 1 2 3 4 5 6 7
8 9 A(10) B(11) C(12) D(13) E(14) F(15)
• The total Number of digits= 16
• The Base of Hexa Decimal Number System is 16

Storing Hexa Deciaml Number System data in Python Programming


• To store Hexa Deciaml number system data in python Environment,
the Hexa Deciaml data must be preceded with either '0x' or '0X'.

Syntax:- varname=0x Hexa Decimal Data


(OR)
Syntax:- varname=0X Hexa Decimal

• Even though we represent the Hexa Decimal data , internally, it is


converted into default number system (Decimal )
Integer
a) Hexa Decimal Number System:
>> a=0xAC
>>> print(a,type(a))--------172 <class 'int'>
>>> b=0XBEE
>>> print(b,type(b))---------3054 <class 'int'>
>>> c=0xFaCE
>>> print(c,type(c))--------64206 <class 'int'>
>>> a=0xACE
>>> print(a,type(a))---------2766 <class 'int'>
>>> a=0xACER---------SyntaxError: invalid hexadecimal literal
Base Conversion Functions
• The purpose of base conversion functions is that
"To convert one base value into another base
value".
(OR)
• The purpose of base conversion functions is that
"To convert One Number System into Another
Number System value".
• In Python Programming, we have 3 types of base
conversion Functions. They are
1) bin()
2) oct()
3) hex()
bin()
• This function is used for converting any base (
8, 16, 10 ) into Binary Number System data
(base 2)
Syntax: varname=bin(decimal / octal / Hexa decimal value)
>>> a=15
>>> print(a,type(a))--------15 <class 'int'>
>>> b=bin(a)
>>> print(b,type(b))-------0b1111 <class 'str'>
bin()
>>> a=0o14
>>> b=bin(a)
>>> print(b,type(b))-----------0b1100 <class 'str'>
-------------------------------------------------------------------
>>> a=0xAC
>>> b=bin(a)
>>> print(b,type(b))----------0b10101100 <class 'str'>
>>> a=0xF
>>> b=bin(a)
>>> print(b,type(b))-------------0b1111 <class 'str'>
oct()
• This function is used for converting any base ( 2, 16, 10 ) into Octal
Number System data (base 8)
Syntax:- varname=oct(decimal / binary / Hexa decimal value)

>>> a=15
>>> b=oct(a)
>>> print(b,type(b))----0o17 <class 'str'>
>>> a=0b1111
>>> b=oct(a)
>>> print(b,type(b))--------0o17 <class 'str'>
>>> a=0xF
>>> b=oct(a)
>>> print(b,type(b))----0o17 <class 'str'>
>>> a=0XBEE
>>> b=oct(a)
>>> print(b,type(b))----0o5756 <class 'str'>
hex()
• This function is used for converting Any Base ( 2, 8, 10 ) into
Hexa Decimal Number System data (base 16)
Syntax: varname=hex(decimal / binary / Octal value)
>>> a=10
>>> b=hex(a)
>>> print(b,type(b))------------0xa <class 'str'>
>>> a=8
>>> b=hex(a)
>>> print(b,type(b))-----------0x8 <class 'str'>
>>> a=9
>>> b=hex(a)
>>> print(b,type(b))--------0x9 <class 'str'>
>>> a=0b1111
>>> b=hex(a)
>>> print(b,type(b))----------0xf <class 'str'>
>>> a=0o17
>>> b=hex(a)
>>> print(b,type(b))---------0xf <class 'str'>
float
• 'float' is one of the pre-defined class and it is
treated as fundamental data type.
• The purpose of 'float' data type is that "To store
floating Point / Real Constant values ".
• float data type allows us to store only decimal
number system values but not support to store
Binary , Octal and Hexa Decimal Number System
Values.
• float data type also supports to store “Scientific
Notation" whose general format is "Mantissa e
Exponent".
• "Mantissa e Exponent" can be converted into
general float point values as "Mantissa x 10 to
the power of Exponent“.
float
>>> a=34.99
>>> print(a,type(a))--------34.99 <class 'float'>
>>> a=0.009
>>> print(a,type(a))--------0.009 <class 'float'>
>>> a=22/7
>>> print(a,type(a))---------3.142857142857143 <class 'float'>
> a=0b1111.0b1010---------SyntaxError: invalid decimal literal
>>> a=0xF.0b1010--------SyntaxError: invalid decimal literal
>>> a=0o17.0o12---------SyntaxError: invalid decimal literal
---------------------------------------------------------------
>>> a=3e2
>>> print(a,type(a))---------300.0 <class 'float'>
>>> a=43e-2
>>> print(a,type(a))--------0.43 <class 'float'>
>>> a=0.00000000000000000000000000000000000000000004
>>> print(a,type(a))------4e-44 <class 'float'>
bool
• 'bool' is one of the pre-defined class and treated
as fundamental data type.
• The purpose of bool data type is that "To store
True / False Values (Logical Values)"
• Internally the value True is considered as 1
• Internally the value False is considered as 0
Examples:
>>> a=True
>>> print(a,type(a))----------True <class 'bool'>
>>> b=False
>>> print(b,type(b))---------False <class 'bool'>
bool
Special Examples:
>>> a=True
>>> b=True
>>> print(a+b)-------------2
>>> print(True+False)---------1
>>> print(True*False)----------0
>>> print(False+0b1111)---------15
>>> print(2*False+True)----------1
complex
• 'complex' is one of the pre-defined class and treated as
fundamental data type.
• The purpose of complex data type is that "to store complex
values".
• The General Format of complex value is:
a+bj (or) a-bj
here 'a' is called Real Part
here 'b' is called Imaginary Part
and 'j' is called sqrt(-1)
• To extract the real part we use a pre-defined attribute
called "real" present complex object
• To extract the imaginary part we use a pre-defined attribute
called "imag" present complex object
Syntax:- complexobj.real ---->Gives real part
complexobj.imag--->Gives imaginary part
Internally real and imaginary parts are treated as float.
complex
>>> a=2+3j
>>> print(a,type(a))------------(2+3j) <class 'complex'>
>>> b=2.3+4.6j
>>> print(b,type(b))------------(2.3+4.6j) <class 'complex'>
>>> c=2-3j
>>> print(c,type(c))------------(2-3j) <class 'complex'>
>>> d=-2.5-3.5j
>>> print(d,type(d))----------(-2.5-3.5j) <class 'complex'>
>>> e=23+4.5j
>>> print(e,type(e))-----------(23+4.5j) <class 'complex'>
>>> x=2+3i---------SyntaxError: invalid decimal literal
>>> a=2+j3-------NameError: name 'j3' is not defined
complex
>> a=2+3j
>>> print(a,type(a))---------(2+3j) <class 'complex'>
>>> a.real---------2.0
>>> a.imag-----3.0
>>> b=2.3+4.5j
>>> print(b.real)--------2.3
>>> print(b.imag)-----4.5
>>> print((2+3.4j).real)---------2.0
>>> print((2+3.4j).imag)--------3.4
String Type
• Strings in Python are arrays of bytes representing
unicode characters.
• However, Python does not have a character data
type, a single character is simply a string with a
length of 1.
• A string literal or string in Python can be created
using single, double and triple quotes.
>>> D = ‘Hello World’
>>> D
‘Hello World’
>>> D=”Good Bye”
>>> D
‘Good Bye’
String Type
• The triple single quotes are used to write a
multiline string.
>>> Sentence=‘’’Hello, How are you? Welcome to
the world of Python Programming. It is just the
beginning. Let us move on to the next topic.’’’
>>> Sentence
‘Hello, How are you? Welcome to the world of
Python Programming. It is just the beginning. Let us
move on to the next topic.’
The str Function
• The str function is used to convert a number
into a string. The following example illustrates
the same.
>>> 12.5 #Floating Point Number
12.5
>>> type(12.5)
<class ‘float’>
>>> str(12.5) #Convert floating point number to string
‘12.5’
The String Concatenation (+) Operator

• ‘+’ operator is used to concatenate two


different strings.

>>> “Python” + “Programming”


‘PythonProgramming’ #Concatenates two different strings
THE print() FUNCTION
• The task of print function is to display the contents on
the screen.
Syntax of print() function: print(argument)
• The argument of the print function can be a value of
any type int, str, float etc.
• It can also be a value stored in a variable.
• print() function executed in interactive mode of
Python are:

Display messages using print()


>>> print(‘Hello Welcome to Python Programming’)
Hello Welcome to Python Programming
>>> print(10000)
10000
>>>print(“Display String Demo”)
Display String Demo
Python escape sequences/Backslash characters
The print()Function with end Argument
• The print function automatically prints a linefeed (\n) to cause
the output to advance to the next line.
• However, if you want to display the messages in one line without
using a single print statement, then you can invoke the print
function by passing a special argument named end=’ ‘.

print(‘Hello’) print(‘ Hello’,end=’ ‘)


print(‘World’) print(‘ World’,end=’ ‘)
print(‘Good Bye’)
print(‘ Good Bye’)
Output
Hello Output
World Hello World Good Bye
Good Bye
ASSIGNING VALUE TO A VARIABLE
• Variable = expression

• Z=1 # Assign value 1 to variable Z


• radius = 5 #Assign value 5 to the variable radius
• R = radius + Z #Assign the addition of radius and Z to R
• E =(5 + 10 * (10 + 5)) #Assign the value of the expression to E
• P = Q = R = 100 #Assign 100 to P, Q and R
Scope of a Variable
• A variable must be assigned a value before it
can be used in an expression.
• The scope of a variable is a part of the
program where a variable can be referenced
MULTIPLE ASSIGNMENTS

• Var1, Var2, Var3, … = Exp1, Exp2, Exp3, ... ExpN


P, Q = 10,20
• By using the concept of multiple assignment,
you can simplify the task of swapping two
numbers.
P, Q = Q, P #Swap P with Q & Q with P
THE input() FUNCTION
• The input( ) function is used to accept an
input from a user
• Even if the user enters a numeric, i.e. integer
value, Python returns the type of input value
as string
• Syntax:
• Variable_Name = input( )
OR
• Variable_Name = input(‘String’)
Reading String from the Console
THE eval() FUNCTION
• It takes a string as parameter and returns it
as if it is a Python expression
eval(‘print(“Hello”)’) Hello
X = eval(‘123’) 123

Name = (input(‘Enter Name :’))


Age = eval(input(‘Enter Age :’)) #eval() determine input type
Gender = (input(‘Enter gender:’))
Height = eval(input(‘Enter Height:’)) #eval() determine input type
print(‘ User Details are as follows: ‘)
print(‘ Name: ‘,Name) print(‘ Age: ‘,Age)
print(‘ Gender: ‘,Gender)
print(‘ Height ‘,Height)
FORMATTING NUMBER AND STRINGS
• format(item, format-specifier)

print(format(10.345,”10.2f”)) 10.35
print(format(10,”10.2f”)) 10.00
print(format(10.32245,”10.2f”)) 10.32
print(format(0.31456,”10.2%”)) 31.46%

Justifying Format
print(format(10.234566,”10.2f”)) #Right Justification Example 10.23
print(format(10.234566,” <10.2f”)) #Right Justification Example 10.23

Formatting String
print(format(“Hello World!”,”25s”) #Left Justification Example Hello World!
print(format(“HELLO WORLD!”,”>20s”)) #String Right Justification HELLO WORLD!
Formatting Scientific Notation
PYTHON INBUILT FUNCTIONS
The ord and chr Functions
• ord(‘A’) #Returns ASCII value of Character
‘A’
• chr(Code) returns the character
corresponding to its code

• ord(‘A’) #Returns ASCII value of Character


‘A’
• chr(65) #‘A’
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:
• Display a random number between 1 and 9

import random
print(random.randrange(1, 10))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy