0% found this document useful (0 votes)
6 views58 pages

Python Programming Fundamentals

The document provides an overview of Python programming fundamentals, covering character sets, keywords, identifiers, data types, operators, and comments. It explains the differences between identifiers and variables, the concept of literals, and various types of operators including arithmetic, comparison, logical, and assignment operators. Additionally, it discusses mutable vs immutable types, escape sequences, and built-in functions like chr(), ord(), and eval().

Uploaded by

Elanwastaken
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views58 pages

Python Programming Fundamentals

The document provides an overview of Python programming fundamentals, covering character sets, keywords, identifiers, data types, operators, and comments. It explains the differences between identifiers and variables, the concept of literals, and various types of operators including arithmetic, comparison, logical, and assignment operators. Additionally, it discusses mutable vs immutable types, escape sequences, and built-in functions like chr(), ord(), and eval().

Uploaded by

Elanwastaken
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Python

Programming
Fundamentals

1
Character Sets

● Alphabets: A-Z and a-z All upper case and lower case
alphabets.
● Digits: All digits 0-9
● Special Symbols: + - / * | ** () [] {} // = != == . ‘ ‘ “
“ , : ; % ! # ? $ & ^ <= >= @ _ ~
● White Spaces: White spaces like blank space, tab
space(‘\t’), newline(‘\n’), formfeed(‘\f’) and carriage
return(‘\r’).
● Other: All ASCII and UNICODE characters are
supported by Python that constitutes the Python
Keywords
Keywords are reserve words , Predefined words, Special words of
Python which has a special meaning for the interpreter

False class from or

None continue global pass

True def if raise

and del import return

as elif in try

assert else is while

async except lambda with

await finally nonlocal yield

break for not


IDENTIFIER
• Python Identifier is the name we give to identify a variable, function, class,
module or other object. That means whenever we want to give an entity a
name, that's called identifier. Sometimes variable and identifier are often
misunderstood as same but they are not.

• Identifier names in Python can contain numbers (0-9), uppercase letters (A-Z),
lowercase letters (a-z), and underscore (_).
• An identifier name should not contain numeric characters only.
• Identifier names in Python are case-sensitive like most other languages. (‘Ask’ is
different from ‘ASK’).
• The name should always start with a non-numeric character (Alphabets or ‘_’).
• Users can begin identifiers with an underscore; it will not display an error.
• An identifier name can be of any length, although the PEP-8 standard rule advises
limiting the number of characters in a line to 79.
• Identifiers should not carry the same name as keywords. (To avoid errors in this
regard, users can type help() followed by “keywords” to view a list of all the
keywords in Python.)
• Leading double underscores (__$) cannot be used as these category names are
used for the context of the definition of a class. These are private variables of
derived and base classes.
IDENTIFIER Vs VARIABLE
An Identifier is a name assigned to an entity in a computer program so that it
can be identified distinctly in the program during its execution. On the other
hand, a variable is a name assigned to a memory location that stores a value.

The most significant difference is that an identifier is used to assign a name


to an entity like a class, or a function, while a variable is used to assign a
name to a memory location.
Invalid Identifiers
❖2nd_Name
❖@gmail
❖Name$
❖_ _Area
❖True
Comments
A comment is text that doesn't affect the outcome of a code, it is just a piece of
text to let someone know what you have done in a program or what is being done
in a block of code

Single-line comments are created simply by beginning a line with the hash (#)
character, and they are automatically terminated by the end of line.

Unlike other programming languages Python doesn't support multi-line


comment blocks. As part of the Python course it is taught that in order to do
a multiline comment one should use """triple quotes""" . This is
wrong. Python only has one way of commenting and that is using # . Triple
quotes are treated as regular strings with the exception that they can
span multiple lines.
Data Types in Python
Literals (Constants)
In Python, literals represent fixed values of built-in data types. They are the raw values used in
the code, directly written into the script. There are several types of literals in Python:

● Numeric Literals: These represent >>> x=2+5j


numerical values and can be further
>>> x.real
divided into:
2.0
● Integer literals: Whole numbers, e.g.,
10, -5, 0. They can also be
>>> x.imag
represented in binary (e.g., 0b101),
5.0
octal (e.g., 0o12), or hexadecimal (e.g., >>> y=5-8j
0x0A). >>> y.real
● Float literals: Numbers with a decimal 5.0
point or in exponential form, e.g., 3.14, >>> y.imag
-0.001, 1e6. -8.0
● Complex literals: Numbers with a real
>>> x+y
and imaginary part, e.g., 2 + 3j.
(7-3j)
>>>
Literals (Constants)
● Boolean Literals: Represent truth
● Literal Collections: Represent
values, either True or False.
collections of data:
● None Literal: Represents the ● List literals: Ordered, mutable

absence of a value, denoted by sequences enclosed in square

None. brackets, e.g., [1, 2, 3].


● Tuple literals: Ordered, immutable
● String literals: Represent text sequences enclosed in
and are enclosed in single parentheses, e.g., (4, 5, 6).
quotes ('), double quotes ("), or ● Dictionary literals: Unordered
triple quotes (''' or """). Triple collections of key-value pairs
quotes are used for multi-line
enclosed in curly braces, e.g., {'a':
strings.
1, 'b': 2}.
string1 = 'Hello' ● Set literals: Unordered collections
string2 = "World"
of unique elements enclosed in
string3 = '''This is a
multi-line string''' curly braces, e.g., {1, 2, 3}.
Arithmetic Operators
These perform mathematical operations.

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
// Floor division x // y
% Modulus x%y
** Exponentiation x ** y
Arithmetic Operators

x = 10
y=3
print(x + y) # Output: 13
print(x - y) # Output: 7
print(x * y) # Output: 30
print(x / y) # Output: 3.333...
print(x // y) # Output: 3
print(x % y) # Output: 1
print(x ** y) # Output: 1000
Comparison Operators
These compare two values.

Operator Name Example

== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Comparison Operators

x=5
y = 10
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: False
print(x < y) # Output: True
print(x >= y) # Output: False
print(x <= y) # Output: True
Truth Value
Logical Operators
These combine conditional statements.

Operator Description Example

and Returns True if x < 5 and x < 10


both statements are true

or Returns True if x < 5 or x < 4


one of the statements is true

not Reverses the result, not(x<5 and x<10)


returns False if true
Logical Operators

x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
Assignment Operators
These assign values to variables.

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
Assignment Operators

x = 10
x += 5
print(x) # Output: 15
Operator Name
Description
& AND Sets each bit to 1
if both bits are 1

| OR Sets
each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1


if only one of two bits is 1

~ NOT Inverts all the


bits
<< Zero fill left shift Shift left by pushing zeros
in from the right
and let the leftmost bits fall off

>> Signed right shift Shift right by pushing


copies of the leftmost
bit in from the left, and let the rightmost
bits fall off
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object

in Returns True
x in y
if a sequence with
the specified value
is present in the object

not in Returns True if a sequence x not


in y
with the specified value
is not present in the object
Python Identity Operators
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:

is Returns True if both


x is y
variables are the same object

is not Returns True if both variables


x is not y
are not the same object
Operator Precedence

() Parentheses
** Exponentiation
+x -x ~x Unary plus, unary minus, and
bitwise NOT
* / // % Multiplication, division, floor
division, and modulus
+ - Addition and
subtraction
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==,!=,>,>=,<,<= Comparisons, identity and
membership operators
COMPONENTS OF AN OBJECT

x = 10
a) Identity
Refers to the object’s address in the memory
>>> id(x)
4567543 —address of the memory location

b) Type
Refers to the data type
>>> type(x)
<class ‘int’>

c) Value
Refers to the the value stored
>>> print(x)
10
Concept of L-Value and R-Value
Lvalue & Rvalue:
• An Lvalue is location value of any object
• An Rvalue is the value associated (assigned) with that object
For example:
(1774283408) Rvalue
Lvalue

X = 100
Multiple Assignment
Assigning multiple values Assigning same value to
to multiple variables multiple variables

>>> d=e=f=8
>>> a,b,c=5,'yes','no' >>> d
>>> a 8
5 >>> d
>>> b 8
'yes' >>> d
8
>>> c
>>> f
'no' 8x
MUTABLE:
Whose value can be modified. LIST, DICTIONARY,
SET
IMMUTABLE:
Whose value CANNOT be modified. NUMERIC, STRING, TUPLE

>>> A=10 >>> lst = [1,2,'a','hi']


>>> type(A) >>> type(lst)
<class 'int'> <class 'list'>
>>> s='Hello' >>> tpl=('python',3.6,100)
>>> type(s) >>> type(tpl)
<class 'str'> <class 'tuple'>
>>> pi=3.14 >>> d={1: 'one', 2: 'Two', 3:
>>> type(pi) 'Three'}
<class 'float'> >>> type(d)
<class 'dict'>
Escape Sequence / Characters
• To insert characters that are illegal in a string, use an escape character.
• An escape character is a backslash \ followed by the character you
want to insert.
• An example of an illegal character is a double quote inside a string that
is surrounded by double quotes

txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

The escape character allows you to use double quotes when you
normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."


Escape Sequence / Characters

txt = "This will insert one \\ (backslash)."


print(txt)
txt = 'It\'s alright.'
print(txt)
txt = "It's a "cat""
print(txt)
txt = "Hello\nWorld!"
print(txt)
txt = "Hello\rWorld!"
print(txt)
Escape Sequence / Characters

txt = "Hello\tWorld!"
print(txt)
#This example erases one character (backspace):
txt = "Hello \bWorld!"
print(txt)
#A backslash followed by three integers will result in a octal value:
txt = "\110\145\154\154\157"
print(txt)
#A backslash followed by an 'x' and a hex number represents a hex value:
txt = "\x48\x65\x6c\x6c\x6f"
print(txt)
\f Form Feed
chr() / ord()
The chr() function in Python is a built-in function that takes an integer as an
argument and returns the string representing the corresponding Unicode
character.
print(chr(65)) # Output: A
print(chr(90)) # Output: Z
print(chr(97)) # Output: a
print(chr(122)) # Output: Z
print(chr(49)) # Output: 1

The ord() function in Python is a built-in function that accepts a single


Unicode character as a string and returns its corresponding integer Unicode
code point value.
print(ord('A')) # Output: 65
print(ord('Z')) # Output: 90
print(ord('a')) # Output: 97
print(ord('z')) # Output: 122
print(ord('€')) # Output: 8364
print(ord('9')) # Output: 57
eval() function
>>> eval("Hai"+"Hello")
The eval() function in Python is a Traceback (most recent call last):
built-in function that evaluates a File "<pyshell#1>", line 1, in
<module>
string as a Python expression.
eval("Hai"+"Hello")
File "<string>", line 1, in
x = 'print(55)' <module>
eval(x) NameError: name 'HaiHello' is not
defined
>>> eval(8*9+5)
expression = "2 + 3 * 4"
Traceback (most recent call last):
result = eval(expression) File "<pyshell#2>", line 1, in
print(result) # Output: <module>
eval(8*9+5)
14
TypeError: eval() arg 1 must be a
string, bytes or code object
>>> eval("3.5+4.5") >>>

8.0
>>> l=[10,20]
>>> a=True >>> l1=[10,20]
>>> int(a) >>> id(l)
1 1992711254336
>>> a=[] >>> id(l1)
>>> bool(a) 1992711245248
False >>> l2=l1
>>> id(l2)
>>> bool(5-5)
1992711245248
False >>> a=9.6
>>> a="str" >>> b=3.2*3
>>> b="str" >>> b
>>> id(a) 9.600000000000001
1992670910896 >>> id(a)
>>> id(b) 1992705998256
1992670910896 >>> id(b)
1992680151312
print(bool(0))

print(bool(1))

print(bool(0.0))

print(bool("0"))

print(bool(""))

print(bool(str(0.0)))

print(bool(""))

print(bool([]))
print(bool(0)) False

print(bool(1)) True

print(bool(0.0)) False

print(bool("0")) True

print(bool("")) False

True
print(bool(str(0.0)))

False
print(bool(""))

print(bool([])) False
print(bool(()))

print(bool([12,12]))

print(bool({}))

print(bool((12)))

print(bool(int('0')))

print(bool({1:10}))

print(bool(str(0)))

print(bool(bool(1)))
print(bool(())) False

print(bool([12,12])) True

print(bool({})) False

print(bool((12))) True

print(bool(int('0'))) False

print(bool({1:10})) True

print(bool(str(0))) True

print(bool(bool(1))) True
Integer

>>> e=5
>>> f=e
>>> g=5
>>> h=2+3
>>> e is f
True
>>> e is g is f is h
True
Float

>>> e=5.0
>>> f=e
>>> g=5.0
>>> h=2.0+3.0
>>> e is f
True
>>> e is g
False
>>> e is h
False
String

>>> e='Hello'
>>> f = e
>>> g = 'Hello'
>>> h = 'Hel'+'lo'
>>> e is f
True
>>> e is g
True
>>> e is h
True
List
>>> e=[2,'a']
>>> f=e
>>> g=[2]+['a']
>>> h=[2,'a']
>>> e is f
True
>>> e is g
False
>>> e is h
False
Tuple
>>> e=(2,'a')
>>> f=e
>>> g=(2,'a')
>>> h=(2,)+('a')
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
h=(2,)+('a')
TypeError: can only concatenate tuple (not "str") to tuple
>>> h=(2,)+('a',)
>>> e is f
True
>>> e is g
False
>>> e is h
False
Dictionary
>>> e={1:'a', 2:'b'}
>>> f=e
>>> e is f
True
>>> h={1:'a', 2:'b'}
>>> e is h
False
>>> g={1:'a'}+{2:'b'}
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
g={1:'a'}+{2:'b'}
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
Dictionary
>>> g={1:'a'}+{2:'b'}
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
g={1:'a'}+{2:'b'}
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

>>> g={1:'a'}
>>> g+={2:'b'}
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
g+={2:'b'}
TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'

>>> g[2]='b'
>>> g
{1: 'a', 2: 'b'}
>>> e is g
False
Shorthand Notation
>>> name1 = 'Ram'; name2='Rahim'
>>> l=['a']
>>> l+=['b','c','d']
>>> l
['a', 'b', 'c', 'd']
>>> a='a'
>>> a+='bcd'
>>> a
'abcd'
>>>
Add elements to a string
1. 2.
>>> s='Do your' >>> s='Do your'
>>> t=' best' >>> s+=t
>>> s=s+t >>> s
>>> s 'Do your best'
'Do your best'
Add elements to a List
>>> L=[3,'a',4,'b']
>>> L=L+5 # Only a list can be added a list. No other data type
allowed
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
L=L+5
TypeError: can only concatenate list (not "int") to list

>>> L[4]=5 # Cannot add an element using index number out of range

Traceback (most recent call last):

File "<pyshell#29>", line 1, in <module>

L[4]=5

IndexError: list assignment index out of range


Add elements to a List

1. 2.
>>> L=L+[5] >>> L+=['c',6,'d']
>>> L >>> L
[3, 'a', 4, 'b', 5] [3, 'a', 4, 'b', 5, 'c', 6, 'd']
Add elements to a Tuple
>>> T=(3,'a',4,'b')

>>> T=T+5 # Only a tuple can be added a tuple. No other data type
allowed

Traceback (most recent call last):

File "<pyshell#16>", line 1, in <module>

T=T+5

TypeError: can only concatenate tuple (not "int") to tuple

>>> T=T+(5) # (5) is integer, not a tuple

Traceback (most recent call last):

File "<pyshell#17>", line 1, in <module>

T=T+(5)

TypeError: can only concatenate tuple (not "int") to tuple


Add elements to a Tuple

1. 2.
>>> T=T+(5,) >>> T+=('c',6,'d')
>>> T >>> T
(3, 'a', 4, 'b', 5) (3, 'a', 4, 'b', 5, 'c', 6, 'd')
Add elements to a Dictionary
>>> D={1:'a', 2:'b', 3:'c'}
>>> D+={4:'d'}
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
D+={4:'d'}
TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'

1.

>>> D[4]='d'

>>> D

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}


Syntax Errors

● These errors occur when the code violates Python's grammatical rules
(syntax).
● The Python interpreter detects them before the program even starts
executing.
● Examples include missing colons, incorrect indentation (leading to
IndentationError), or misspelled keywords or missing punctuation (:,
(), , etc )
● The interpreter will raise a SyntaxError and often indicate the line where
the error was detected, preventing the program from running
Runtime Errors (Exceptions)
● These errors occur during the execution of the program.
● The code might be syntactically correct, but an issue arises during runtime
that prevents the program from continuing normally.
● Python uses a mechanism called "exceptions" to handle these errors.
When a runtime error occurs, an exception object is raised.
● Common examples include:
i. NameError: Trying to use an undefined variable.
ii. TypeError: Performing an operation on an object of an inappropriate type
(e.g., adding a string to an integer).
iii. ZeroDivisionError: Attempting to divide a number by zero.
iv. IndexError: Accessing a list or sequence index that is out of bounds.
v. KeyError: Accessing a dictionary with a key that does not exist.
vi. FileNotFoundError: Trying to open a file that doesn't exist.
● These errors can often be handled using try-except blocks to prevent the
program from crashing.
10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
10 * (1/0)
~^~
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
4 + spam*3
^^^^
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
'2' + 2
~~~~^~~
TypeError: can only concatenate str (not "int") to str
Logical Errors

i. These errors occur when the program runs without


raising any exceptions, but it produces an incorrect or
unexpected result.
ii. The code's logic is flawed, leading to a discrepancy
between the intended behavior and the actual output.
iii. Logical errors are the most challenging to detect
because the program executes without any explicit
error messages.
iv. Debugging logical errors often involves careful
examination of the code's flow, variable values, and
expected outputs.

You might also like