0% found this document useful (0 votes)
2 views18 pages

Python Basics

The document provides an overview of Python programming fundamentals, covering the character set, tokens, identifiers, keywords, literals, operators, data types, and variables. It explains the rules for naming identifiers, the types of literals available, and the various operators used in Python, including arithmetic, relational, logical, and assignment operators. Additionally, it discusses mutable and immutable types, as well as the structure of sequences like strings, lists, tuples, dictionaries, and sets.

Uploaded by

aaravgarg.del
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)
2 views18 pages

Python Basics

The document provides an overview of Python programming fundamentals, covering the character set, tokens, identifiers, keywords, literals, operators, data types, and variables. It explains the rules for naming identifiers, the types of literals available, and the various operators used in Python, including arithmetic, relational, logical, and assignment operators. Additionally, it discusses mutable and immutable types, as well as the structure of sequences like strings, lists, tuples, dictionaries, and sets.

Uploaded by

aaravgarg.del
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/ 18

PYTHON PROGRAMMING FUNDAMENTALS

PYTHON CHARACTER SET:


Python character set represents the set of valid characters that Python supports. It has the
following character set:

Letters A–Z, a–z


Digits 0–9
Special Symbols Space + – * / ** \ { } ( ) // = != == < , > . ' ' " " ; : % ! & # <= >= @ _
(underscore)
Whitespace Blank Space, Tab, Newline etc.
Other Python can process all ASCII and Unicode characters as part of data or
Characters literals

TOKENS:
The smallest individual unit in a program is known as Token. It is also called as Lexical Unit.
Tokens present in Python are:
(i) Identifiers (ii) Keywords (iii) Literals/Constants (iv) Operators (v) Punctuators/Delimiters

IDENTIFIERS: An identifier is a name given to a program element such as variable, function,


list, dictionary etc. The rules to be followed while naming an identifier in Python are,
 It may consist of letters (A–Z, a–z), digits (0–9), and underscore (_).
 It must begin with a letter or an underscore.
 It must not begin with a digit.
 Uppercase and lowercase alphabets are different. For example sum, Sum, SUM all are
different.
 A keyword must not be used as an identifier.
 It can be of any length. However, it is preferred to be short and meaningful.

KEYWORDS: A keyword is a reserved word that has a predefined meaning to the interpreter.
A keyword must not be used as identifier. For checking/displaying the list of keywords available
in Python:
**All keywords are in lower case except True, False and None.

Literals / Constants: A literal or constant is a program element that will never change its values
during program execution. Python allows several kinds of literals like:
(i) String literals (ii) Numeric literals (iii) Boolean literals (iv) Special Literal-None
String Literals: A string literal is a sequence of characters enclosed in either single quotes or
double quotes. Either both single quotes and both double quotes to be used for a string. Example:
"Python", 'Program' etc. A single quoted string inside double quotes and vice–versa is legal in
Python. Ex: "Anu's" and 'Anu"s' are valid.

Python allows (i) Single–line Strings (ii) Multiline Strings

Single–line Strings: The strings that create by enclosing text in single quotes or double
quotes are called single–line strings. Ex: "Python", 'Apple'

Multiline Strings: To provide a string in multiline, it is to be provided in triple quotes


(triple single quotes or triple double quotes)

Ex: print ("""Rosary Senior Secondary School""")

‘’’Rosary’’’ “””Rosary”””

Numeric Literals: These literals are three types namely (i) Integer literals (ii) float literals (iii)
complex literals

Integer Literals: An integer constant must have at least one digit and must not contain any
decimal point. Different integer literals available are,
1. Decimal Integer Literals: It consists of a sequence of digits between 0 and 9 and does
not start with zero. Ex: 1234, –458 etc

2. Octal Integer Literals: It consists of a sequence of digits between 0 and 7. It begins with
0o(Digit Zero Letter o) Ex: 0o24, 0o746 etc

3. Hexadecimal Literals: It consists of a sequence of hexadecimal values between 0–9 and


A–F. It begins with 0x. Ex: 0x14AC

Floating Point Literals: These are also called as Real Literals. These can be expressed in two
forms viz. Fractional Form and Exponent Form
1. Fractional Form: A real constant in fractional form must have at least one digit either
before or after decimal point. Ex; 2.0, 17.5, –14.6, –0.05, .3 (means 0.3), 6. (means 6.0)

2. Exponent Form: A real constant in exponent form consists of two parts mantissa and
exponent. The mantissa must be either an integer or a proper real constant. The mantissa
is followed by a letter E or e and the exponent. The exponent must be an integer.
Ex: 152E05, 1.52e07, 0.152E08, 152e+8,–0.172E–3, .25e–4

Complex Literals:
The numerals will be in the form of a + bj, where ‘a‘ is the real part and ‘b‘ is the complex part.
Example:
Z=7+5j

Boolean Literals: A Boolean literal represent one of the two Boolean values i.e. True or False.
A Boolean literal can either have value as True or as False.

Special Literal None:


None is a special literal in Python. It indicates the absence of value. It means "There is not
useful information" or "There is nothing here"

Ex: >>>a = None


>>>print(a)
None

Operators: An operator is a symbol that is used in a program in respect of some operation. Each
operation is denoted by some operator. For example the operation addition is denoted by + and
the operation “finding remainder” is denoted by %. Each programming language will have its
own set of operators.
The constants or variables that participate in the operation are called operands
6 + 4

Operand Operator Operand

Unary Operator: If an operator takes only one operand then it is called Unary Operator
Binary Operator: If an operator takes two operands then it is called Binary Operator.
Ternary Operator: If an operator takes three operands then it is called Ternary Operator
OPERATORS AND OPERANDS:
 Operators are special symbols which represents computation.
 They are applied on operand(s), which can be values or variables.
 Same operator can behave differently on different data types.
 Operators when applied on operands form an expression.
 Operators are categorized as Arithmetic, Relational, Logical and Assignment.
 Values/Literals and variables when used with operator are known as operands.

Arithmetic or Mathematical Operators:

Symbol Description Example 1 Example 2


>>>55+45 >>>'Good'+'Morning'
+ Addition 100 ‘GoodMorning’
>>>55–45
– Subtraction 10
>>>55*45 >>>'Good'*3
* Multiplication 2475 ‘GoodGoodGood’
>>>17/5
3.4
/ Division >>>17.0/5
3.4

Remainder / >>>17%5
% Modulo Division 2
>>>2**3 >>>2**8
** Exponentiation 8 256
>>>16**.5
4.0
Integer Division >>>7//2 >>>3//2 1
// (or) Floor Division 3

Relational Operators:
ASCII values
American Standard Code for information Interchange
A-65, B-66,C-67.....
a-97, b-98,c-99,.....
Symbol Description Example 1 Example 2
>>>7<10
True
>>>7<5 >>>'Hello'<'Goodbye'
< Less Than False False
>>>'Goodbye'<'Hello'
True
>>>7>5 >>>'Hello'>'Goodbye'
> Greater Than True True
>>>10>10 >>>'Goodbye'>'Hello'
False False
>>>2<=5 >>>'Hello'<='Goodbye'
<= Less Than or Equal To True False
>>>7<=4 >>>'Goodbye'<='Hello'
False True

Symbol Description Example 1 Example 2


>>>10>=10 >>>'Hello'>='Goodbye'
>= Greater Than or Equal To True True
>>>10>=12 >>>'Goodbye'>='Hello'
False False
>>>10!=11 >>>'Hello'!='HELLO'
!= Not Equal To True True
>>>10!=10 >>>'Hello'!='Hello'
False False
>>>10==10 >>>'Hello'=='Hello'
== Equal To True True
>>>10==11 >>>'Hello'=='Goodbye'
False False

Logical Operators:

Symbol Description
and If both the operands are true, then the condition becomes true
or If any one of the operand is true, then the condition becomes true
not Reverses the state of operand/condition
Truth Tables for Logical Operators:

A B A and B A or B not A
True True True True False
True False False True False
False True False True True
False False False False True

Assignment Operators/Shorthand Assignment Operators/ Augmented Assignment


Operators:

Symbol Description Example Explanation


Assigns value from right side operand to left >>>x=12
= >>>y='greetings'
side variable
Means x=x+2
+= Add and assign the result to left side variable >>>x+=2
x becomes 14
Means x=x–2
–= Subtract and assign the result to left side variable >>>x–=2
x becomes 10
Means x=x*2
*= Multiply and assign the result to left side variable >>>x*=2
x becomes 24
Means x=x/2
/= Divide and assign the result to left side variable >>>x/=2
x becomes 6
Modulo Divide and assign result to left Means x=x%2
%= >>>x%=2
side variable x becomes 0
Performs exponential calculation and assign Means x=x**2
**= >>>x**=2
result to left side variable x becomes 144
Performs floor division on operators and Means x=x//2
//= >>>x//=2
assign result to left side variable x becomes 6
Identity Operators:

Symbol Description Example Explanation


>>> x=10 Here, the operands x and z
Returns True only if both the >>> y=20 are pointing to the same
Is operands a and b are pointing to the >>> z=10 object 10, hence resulted in
same object, returns False otherwise >>> x is z True, whereas x and y are
True pointing to different
>>> x is y objects, hence resulted in false
False
>>>x is not y
Returns True if both the operands a True
is not and b are pointing to different
objects, returns False otherwise

Membership Operators:

Symbol Description Example


>>> ‘H’ in ‘Hello’
True
>>> ‘B’ in ‘Hello’
in Returns True if the variable or value is False
found in the specified sequence and False
otherwise

>>> ‘H’ not in ‘Hello’


Returns True if the variable/value is not False
not in found in the specified sequence and False >>> ‘B’ not in ‘Hello’
otherwise True

Precedence of Operators:

While evaluating an expression the precedence of operators will be like below. It gives the order
of evaluation of operators in an expression. However the precedence can be changed by using
parenthesis.

Operators Associativity is used when two operators of same precedence appear in an


expression. Associativity can be either Left to Right or Right to Left.
** - Right to Left
Assignment Operators – Right to Left

DATA TYPES:
A data type represents the type of data like character, integer, real, string etc. Different
types of data types in Python are,
Numbers: Number data type stores numerical values. This data type is immutable, mean that
the value of its object cannot be changed. These are of three different types:

Integers: Integers are the whole numbers like 100000, –99, 0, 17 etc. They have no decimal
point. Integers can be positive or negative. If an integer has no sign, then it is positive. There are
two types of Integers
int: While writing an integer value, commas must not be used to separate digits. Also
integers should not have leading zeros. The data type int can store any integer, either big
or small.
Range of an integer in Python can be from -2147483648 to +2147483647, and long
integer has unlimited range, subject to available memory.

bool: These represent the truth values False and True, that resembles integers 0 and 1
respectively. The bool( ) function returns the boolean equivalent digit.
>>> bool(1)
True
>>> bool(0)
False
>>>bool_1 = (6>10)
>>>print(bool_1)
False

Floating Point Numbers / Real Numbers: Numbers with fractions or decimal point are called
floating point numbers. A floating point number will consist of sign (+,–) sequence of decimals
digits and a dot such as 0.0, –21.9, 0.98333328, 15.2963. These numbers can be written in two
forms
(i) Fractional Form Examples 3500.75, 0.00005, 147.9101 etc
(ii) Exponent Form Examples 3.50075E03, 0.5E–04, 1.479101E02 etc
The advantage of floating point numbers over integers are, they can be used to represent much
greater range of values.

Complex Numbers: 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.imag. Imaginary part of the number is represented by j instead of i, so 1+0j denotes
zero imaginary part.
>>> c=2–3j
>>> c.real
2.0
>>> c.imag
–3.0

None: This is special data type with single value. It is used to signify the absence of value/false
in a situation. It is represented by None. It is used to define a null value, or no value at all. None
is not the same as 0, False, or an empty string.
>>> x=None
>>>print(x)
None

Sequences

String

The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

‘Hello’, “Hello”

List

List is a collection of elements of different types. The items stored in the list are separated with a
comma (,) and enclosed within square brackets []. It is mutable.

L=[10,20,30]

Tuple

Tuples also contain the collection of the items of different data types. The items of the tuple are
separated with a comma (,) and enclosed in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

T=(10,20,30)

Mapping

Dictionary

Dictionary is an unordered set of a key-value pair of items. The items in the dictionary are
separated with the comma (,) and enclosed in the curly braces {}. It is mutable.

D={1:10,2:20,3:30}

Set

Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values.

S1={ 10, ‘Python’, 20.5}

MUTABLE AND IMMUTABLE TYPES:


Immutable Types: The immutable types are those that can never change their value in place.
Integers, Floating Point Numbers, Booleans, Strings and Tuples are immutable types.
Mutable Types: The mutable types are those that can change their value in place. Lists,
Dictionaries and Sets are mutable types.

Punctuators/Delimiters: These are the symbols used in programming which can be used as
separators of values or to enclose some values. Some punctuators available in Python are, ' " #
\()[]{}@,: .=

VARIABLES:

A variable is a program element that can change its value during program execution. It
is an identifier that has a named location and refers to a value and that value can be processed
during program run. As a variable is an identifier, all the rules for naming an identifier are
applicable for naming a variable

Creating a Variable: A variable is created by assigning a value of desired type to it. For
example, an integer variable can be created by assigning an integer value, and a string variable
can be created by assigning a string. It is not possible to create a variable without assigning a
value to it.

Ex: age = 20 # Means variable age is integer


average = 95.6 # Means variable average is of type float
name = "CBSE" # Means variable name is of type string

LValues and RValues: The LValues are the variables that hold a value or expression, and may
present on either left–hand side or right–hand side of assignment. The RValues are the literals
or expressions or variables that are assigned to LValues and can present on only right–hand side
of assignment.

Ex: Valid Statements a = 20


d =b*b–4*a*c
temp = a
Invalid Statements 20 = a
a*2=b
Multiple Assignments: Different ways of assignments are,
1. Assigning same value to multiple variables
Ex: a = b = c = 18
2. Assigning multiple values to multiple variables

Ex1: x, y, z = 10, 20, 30 # Means x=10, y=20, z=30


Ex2: x,y = y,x # This makes x=20, y = 10
Ex3: a, b, c = 5, 10, 7
b, c, a = a+1, b+2, c–1 print
(a, b, c) # a=6, b=6, c=12

Dynamic Typing: A variable having a value of certain data type can be assigned with value of
some other data type. In this case, it automatically assumed to change the data type of that
variable. This is referred as Dynamic Typing
x = 10
print (x)
x = "Informatics Practices"
print(x)
This code will results in:
10
‘Informatics Practices’

VARIABLE INTERNALS:
The data or values are referred to as object. Similarly, a variable is also an object that refer to a
value.
Every object has three key attributes associated to it. These are,
(ii) type of object: The data type of a constant or variable can be displayed using type( )
statement with the required argument.
Ex: >>> type(11)
<class 'int'>
>>> type(12.5)
<class 'float'>
>>> type(2+3j)
<class 'complex'>
>>> type('Vidyalaya')
<class 'str'>
(iii) value of object: The print( ) can be used to print the value of an object like a variable or
constant.

Ex: >>> a=4


>>> print(a)
4
>>> print(4+2j)
(4+2j)

(iv) id of an object: The id of an object is the memory location of it. The function id( ) is used for
this purpose.
Ex: >>>x=10
>>>id(x)
140715083070816
>>>y=20
>>>id(y)
140715083071136
>>>z=10
>>>id(z)
140715083070816

INPUT AND OUTPUT IN PROGRAMMING:

Input: The input( ) function is used to input during runtime of a program. But, this function
always returns a value of string type. i.e. even a number inputted using input( ) method is not
a number and is a string.

Syntax: variable = input(<Message to be displayed>)

>>>x = input ("Enter a Number")


>>>Enter a Number10

In the above case the value 10 inputted is assumed as string. Hence type of x is string.

To input as a number it is to be appropriately converted into desired data type, like


below

>>> a=int(input("Enter a Number"))


Enter a Number10

>>>
print(a
+2) 12
Output: The print( ) function is used for output to standard output device, monitor.
Syntax: print(object1, [object2, object3, , sep=' ' or seperator_string, end=' ' or
end_string])

Exampl Comman Outpu


e d t
1 print("Informatics Practices") Informatics Practices
2 print("Sum of 2 and 3 is", 2+3) Sum of 2 and 3 is 5
a=2
3 b=3 Sum of 2 and 3 is 5
print("Sum of", a, "and", b, "is", a+b)
a=2
4 b=3 Sum of$2$and$3$is$5
print("Sum of",a,"and",b,"is",a+b, sep='$')
a=2
5 b=3 Sum of *2 *and* 3* is*
print("Sum of",a,"and",b,"is",a+b, end='*') 5*

EXPRESSIONS:

An expression is a combination of literals, operators and variables. In Python, an expression may


be an arithmetic expression, string expression, relational expression, logical expression,
compound expression etc.

1. Arithmetic Expressions: These expressions involve numbers (integers, floating point


numbers, complex numbers) and arithmetic operators.
Ex: 2+8/3, 5.6–4.2/8*1.2

2. Relational Expressions: An expression having literals and/or variables of any valid


type and relational operators is a relational expression

Ex: x>y, y<=z, z<>x, z==q, x<y>, x==y<>z

3. Logical Expressions: An expression having literals and/or variables of any valid type
and logical operators is a logical expression.

Ex: a or b, b and c, a and not b, not c or not b

4. String Expressions: An expression that have string operands and results to string are
string expression.

Ex: "Pine"+"Apple", "Hello"*3


Comments:

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

The statements which are not processed by the Python Interpreter.

Single-Line Comment:

# This is a single line comment.

Multi-line Comment:

‘’’ This is a

Multiline

Comment ‘’’

“””This is a

Multiline

Comment “””

DEBUGGING:

A bug is an error caused in a program. Correcting an error is called Debugging. Different types
of errors that will be encountered while developing any application are as follows:
 Syntax Errors
 Runtime Errors
 Logical Errors

Syntax Errors: A set of rules for writing a statement in a program is called Syntax. Hence, syntax
errors occur when the syntax rules of program are not followed. These errors are visible during
interpretation of program.
In case of syntax errors, program will never execute.
For example, parentheses mismatch the following statement will results into a syntax
error.
d = (b * b – (4 * a * c)

Runtime Errors: These errors are so called because these will be occurred during runtime of
program. A program may be syntactically correct, but may generate errors during run time.
For example,
a = 10, b = 0
c=a/b

The above code is syntactically correct. But during runtime division with 0 is not possible and
hence error will be generated. These errors will cause abnormal termination of code.
Logical Errors: A program, without having any syntax and runtime errors, may give wrong
results. The errors that will give wrong results due to the mistakes made by programmer are
called Logical Errors. These errors are hard to locate. Consider the below example:
hin_marks = 82, eng_marks = 90,
gk_marks = 94;

average = hin_marks + eng_marks + gk_marks / 3;


The above statement is not having syntax error or runtime error, but gives a wrong
result. It should be as,

average = (hin_marks + eng_marks + gk_marks) / 3;


It is an error by programmer and is called as Logical Error.

Escape Sequences (back slash characters) – is a non-printable character represented by a


backslash (\) followed by one or more characters.

Non-graphic characters: which cannot be directly typed from the keyboard, backspace, tab,etc.

Example:

\n - new line
\b – backspace
\t - tab
\v – vertical tab
\’ – single quote

Etc.

Example:
string = 'That\'s my bag.'
print(string)

That’s my bag.

Type conversion:

Also known as type casting.

Changing one data type into another.

1. Explicit type Conversion (Forced Conversion)

The programmer forces it in the program.

Syntax:
(new_data type) (expression)

Example:

>>>x=50.75
>>>print(int(x))
50

Disadvantage:
There is a risk of data loss.

Explicit type conversion functions

Function Description Output


int(x) Converts x into an integer. >>>int(100.00)
100
float(x) Converts x into a floating-point >>>float(10)
number. 10.0
str(x) Converts x into a string. >>>str(1000)
‘1000’
chr(x) Converts x into a character. >>>chr(65)
‘A’

2. Implicit Type Conversion:

 When conversion is done automatically by Python.

 It is also known as coercion.


Smaller data type -> bigger data type

int -> float

Example:

>>>Num1=10
>>>Num2=55.0
>>>Num3=Num1+Num2
>>>print(Num3)

65.0

You might also like