Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
30 views16 pages

Python Fundamentals Overview

The document provides an overview of Python fundamentals, including the character set, tokens, keywords, identifiers, literals, operators, and basic programming concepts. It explains the rules for creating identifiers, the types of literals in Python, and the significance of operators and expressions. Additionally, it covers variable creation, user input, type casting, and the print statement, along with practice questions to reinforce understanding.
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)
30 views16 pages

Python Fundamentals Overview

The document provides an overview of Python fundamentals, including the character set, tokens, keywords, identifiers, literals, operators, and basic programming concepts. It explains the rules for creating identifiers, the types of literals in Python, and the significance of operators and expressions. Additionally, it covers variable creation, user input, type casting, and the print statement, along with practice questions to reinforce understanding.
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/ 16

San Thome Academy, Dewas

CLASS-XI SUBJECT: INFORMATICS PRACTICES


CHAPTER-3
PYTHON FUNDAMENTALS
2.1 Python Character Set :
It is a set of valid characters that a language recognize.
Letters: A-Z, a-z
Digits : 0-9
Special Symbols
Whitespace

2.2 TOKENS
Token: Smallest individual unit in a program is known as token.
There are five types of token in python:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators

1. Keyword: Reserved words in the library of a language. There are 33 keywords in


python.

False class finally is return break

None continue for lambda try except

True def from nonlocal while in

and del global not with raise

as elif if or yield

assert else import pass

All the keywords are in lowercase except 03 keywords (True, False, None).
Page 1
2. Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.

Rules for identifiers:

▪ It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or


digits (0 to 9) or an underscore.
▪ It cannot start with a digit.
▪ Keywords cannot be used as an identifier.
▪ We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
▪ _ (underscore) can be used in identifier.
▪ Commas or blank spaces are not allowed within an identifier.

3. Literal: Literals are the constant value. Literals can be defined as a data that is given in
a variable or constant.

Literal

String Literal
Numeric Boolean Special
Collections

int float complex

True False None

A. Numeric literals: Numeric Literals are immutable.

Eg.

5, 6.7, 6+9j

Page 2
B. String literals:

String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes for a String.

Eg:

"Aman" , '12345'

Escape sequence characters:


\\ Backslash
\’ Single quote
\” Double quote
\a ASCII Bell
\b Backspace
\f ASCII Formfeed
\n New line charater
\t Horizontal tab

C. Boolean literal: A Boolean literal can have any of the two values: True or False.

D. Special literals: Python contains one special literal i.e. None.

None is used to specify to that field that is not created. It is also used for end of lists in
Python.

E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.

4. Operators: An operator performs the operation on operands. Basically there are two
types of operators in python according to number of operands:
A. Unary Operator
B. Binary Operator

A. Unary Operator: Performs the operation on one operand.


Page 3
Example:
+ Unary plus
- Unary minus
~ Bitwise complement
not Logical negation

B. Binary Operator: Performs operation on two operands.

5. Separator or punctuator : , ; , ( ), { }, [ ]

2.3 Mantissa and Exponent Form:

A real number in exponent form has two parts:


➢ mantissa
➢ exponent
Mantissa : It must be either an integer or a proper real constant.
Exponent : It must be an integer. Represented by a letter E or e followed by integer value.

Valid Exponent form Invalid Exponent form


123E05 2.3E (No digit specified for exponent)
1.23E07
0.24E3.2 (Exponent cannot have fractional part)
0.123E08
23,455E03 (No comma allowed)
123.0E08
123E+8
1230E04
-0.123E-3
163.E4
.34E-2
4.E3

Page 4
2.4 Basic terms of a Python Programs:
A. Blocks and Indentation
B. Statements
C. Expressions
D. Comments

A. Blocks and Indentation:


• Python provides no braces to indicate blocks of code for class and function definition or
flow control.
• Maximum line length should be maximum 79 characters.
• Blocks of code are denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.
for example –
if True:
print(“True”)
else:
print(“False”)

B. Statements
A line which has the instructions or expressions.

C. Expressions:
A legal combination of symbols and values that produce a result. Generally it produces a value.

D. Comments: Comments are not executed. Comments explain a program and make a program
understandable and readable. All characters after the # and up to the end of the physical line are
part of the comment and the Python interpreter ignores them.

Page 5
There are two types of comments in python:
i. Single line comment
ii. Multi-line comment

i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values

ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple
quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as docstring.
Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’

Page 6
Multiple Statements on a Single Line:
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)

2.5 Variable/Label in Python:


Definition: Named location that refers to a value and whose value can be used and processed
during program execution.
Variables in python do not have fixed locations. The location they refer to changes every time
their values change.

Creating a variable:

A variable is created the moment you first assign a value to it.

Example:

x=5

y = “hello”

Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.

x = 4 # x is of type int
x = "python" # x is now of type str
print(x)

Rules for Python variables:

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscore (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Page 7
Python allows assign a single value to multiple variables.

Example: x=y=z=5

You can also assign multiple values to multiple variables. For example −

x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12

Lvalue and Rvalue:


An expression has two values. Lvalue and Rvalue.
Lvalue: the LHS part of the expression
Rvalue: the RHS part of the expression
Python first evaluates the RHS expression and then assigns to LHS.
Example:
p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-1
print (p,q,r)
Now the result will be:
6 6 12

Note: Expressions separated with commas are evaluated from left to right and assigned in same
order.

❖ If you want to know the type of variable, you can use type( ) function :

Page 8
Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>
❖ If you want to know the memory address or location of the object, you can use id( )
function.
Example:
>>>id(5)
1561184448
>>>b=5
>>>id(b)
1561184448
You can delete single or multiple variables by using del statement. Example:
del x
del y, z

2.6 Input from a user:


input( ) method is used to take input from the user.
Example:
print("Enter your name:")
x = input( )
print("Hello, " + x)

➢ input( ) function always returns a value of string type.

2.7 Type Casting:


To convert one data type into another data type.

Casting in python is therefore done using constructor functions:

Page 9
• int( ) - constructs an integer number from an integer literal, a float literal or a string
literal.

Example:

x = int(1) # x will be 1 y
= int(2.8) # y will be 2 z
= int("3") # z will be 3

• float( ) - constructs a float number from an integer literal, a float literal or a string literal.

Example:

x = float(1) # x will be 1.0 y


= float(2.8) # y will be 2.8 z =
float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

• str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.

Example:

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Reading a number from a user:


x= int (input(“Enter an integer number”))

2.8 OUTPUT using print( ) statement:


Syntax:
print(object, sep=<separator string >, end=<end-string>)

Page 10
object : It can be one or multiple objects separated by comma.
sep : sep argument specifies the separator character or string. It separate the objects/items. By
default sep argument adds space in between the items when printing.
end : It determines the end character that will be printed at the end of print line. By default it
has newline character( ‘\n’ ).
Example:
x=10
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30

Page 11
Write all questions in C.W copy.

Practice Questions:

Type A : Short Answer Questions/Conceptual Questions

Question 1

What are tokens in Python ? How many types of tokens are allowed in Python ? Examplify your answer.

Answer

The smallest individual unit in a program is known as a Token. Python has following tokens:

1. Keywords — Examples are import, for, in, while, etc.


2. Identifiers — Examples are MyFile, _DS, DATE_9_7_77, etc.
3. Literals — Examples are "abc", 5, 28.5, etc.
4. Operators — Examples are +, -, >, or, etc.
5. Punctuators — ' " # () etc.

Question 2

How are keywords different from identifiers ?

Answer

Keywords are reserved words carrying special meaning and purpose to the language compiler/interpreter. For example,
if, elif, etc. are keywords. Identifiers are user defined names for different parts of the program like variables, objects,
classes, functions, etc. Identifiers are not reserved. They can have letters, digits and underscore. They must begin with
either a letter or underscore. For example, _chk, chess, trail, etc.

Question 3

What are literals in Python ? How many types of literals are allowed in Python ?

Answer

Literals are data items that have a fixed value. The different types of literals allowed in Python are:

1. String literals
2. Numeric literals
3. Boolean literals
4. Special literal None
5. Literal collections

Question 4

Can nongraphic characters be used in Python ? How ? Give examples to support your answer.

Answer

Page 12
Yes, nongraphic characters can be used in Python with the help of escape sequences. For example, backspace is
represented as \b, tab is represented as \t, carriage return is represented as \r.

Question 5

How are floating constants represented in Python ? Give examples to support your answer.

Answer

Floating constants are represented in Python in two forms — Fractional Form and Exponent form. Examples:

1. Fractional Form — 2.0, 17.5, -13.0, -0.00625


2. Exponent form — 152E05, 1.52E07, 0.152E08, -0.172E-3

Question 6

How are string-literals represented and implemented in Python ?

Answer

A string-literal is represented as a sequence of characters surrounded by quotes (single, double or triple quotes). String-
literals in Python are implemented using Unicode.

Question 7

Which of these is not a legal numeric type in Python ? (a) int (b) float (c) decimal.

Answer

decimal is not a legal numeric type in Python.

Question 8

Which argument of print( ) would you set for:

(i) changing the default separator (space) ?


(ii) printing the following line in current line ?

Answer

(i) sep
(ii) end

Question 9

What are operators ? What is their function ? Give examples of some unary and binary operators.

Answer

Operators are tokens that trigger some computation/action when applied to variables and other objects in an expression.
Unary plus (+), Unary minus (-), Bitwise complement (~), Logical negation (not) are a few examples of unary
operators. Examples of binary operators are Addition (+), Subtraction (-), Multiplication (*), Division (/).

Page 13
Question 10

What is an expression and a statement ?

Answer

An expression is any legal combination of symbols that represents a value. For example, 2.9, a + 5, (3 + 5) / 4.
A statement is a programming instruction that does something i.e. some action takes place. For example:
print("Hello")
a = 15
b = a - 10

Question 11

What all components can a Python program contain ?

Answer

A Python program can contain various components like expressions, statements, comments, functions, blocks and
indentation.

Question 12

What do you understand by block/code block/suite in Python ?

Answer

A block/code block/suite is a group of statements that are part of another statement. For example:

if b > 5:
print("Value of 'b' is less than 5.")
print("Thank you.")

Question 13

What is the role of indentation in Python ?

Answer

Python uses indentation to create blocks of code. Statements at same indentation level are part of same block/suite.

Question 14

What are variables ? How are they important for a program ?

Answer

Variables are named labels whose values can be used and processed during program run. Variables are important for a
program because they enable a program to process different sets of data.

Question 15

What do you understand by undefined variable in Python ?

Page 14
Answer

In Python, a variable is not created until some value is assigned to it. A variable is created when a value is assigned to it
for the first time. If we try to use a variable before assigning a value to it then it will result in an undefined variable. For
example:

print(x) #This statement will cause an error for undefined variable x


x = 20
print(x)
The first line of the above code snippet will cause an undefined variable error as we are trying to use x before assigning
a value to it.

Question 16

What is Dynamic Typing feature of Python ?

Answer

A variable pointing to a value of a certain type can be made to point to a value/object of different type.This is called
Dynamic Typing. For example:

x = 10
print(x)
x = "Hello World"
print(x)

Question 17

What would the following code do : X = Y = 7 ?

Answer

It will assign a value of 7 to the variables X and Y.

Question 18

What is the error in following code : X, Y = 7 ?

Answer

The error in the above code is that we have mentioned two variables X, Y as Lvalues but only give a single numeric
literal 7 as the Rvalue. We need to specify one more value like this to correct the error:

X, Y = 7, 8

Question 19

Following variable definition is creating problem X = 0281, find reasons.

Answer

Python doesn't allow decimal numbers to have leading zeros. That is the reason why this line is creating problem.

Page 15
Question 20

"Comments are useful and easy way to enhance readability and understandability of a program." Elaborate with
examples.

Answer

Comments can be used to explain the purpose of the program, document the logic of a piece of code, describe the
behaviour of a program, etc. This enhances the readability and understandability of a program. For example:

# This program shows a program's components

# Definition of function SeeYou() follows


def SeeYou():
print("Time to say Good Bye!!")

# Main program-code follows now


a = 15
b = a - 10
print (a + 3)
if b > 5: # colon means it's a block
print("Value of 'a' was more than 15 initially.")
else:
print("Value of 'a' was 15 or less initially.")

SeeYou() # calling above defined function SeeYou()

To be continued…….

Yamini Dubey
PGT: Computer Science

Page 16

You might also like