0% found this document useful (0 votes)
96 views9 pages

Chapter 6

Python has a defined set of basic elements including characters, tokens, expressions, and statements. Characters include letters, digits, and special symbols. Tokens include keywords, identifiers, literals, operators, and punctuators. A Python program follows an IPO cycle of input, processing, and output. It contains components like expressions, statements, comments, functions, blocks, and adheres to style rules.

Uploaded by

unknownrabul
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)
96 views9 pages

Chapter 6

Python has a defined set of basic elements including characters, tokens, expressions, and statements. Characters include letters, digits, and special symbols. Tokens include keywords, identifiers, literals, operators, and punctuators. A Python program follows an IPO cycle of input, processing, and output. It contains components like expressions, statements, comments, functions, blocks, and adheres to style rules.

Uploaded by

unknownrabul
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/ 9

Python Fundamentals

INTRODUCTION
 All computer actions are governed by IPO (Input, Process, Output) cycle. For every program, there is
certain Input, certain kind of Processing and an Output.
 To transform some kind of input to certain output, you have to develop and execute a program.
 A program is a set of instructions that govern the processing, i.e., a program forms the base for
processing.
 The basic elements that a Python program can contain are character set, tokens, expressions, statements,
simple input and output, etc.
PYTHON CHARACTER SET
Character set is a set of valid characters that a programming language can recognize. A character represents
any letter, digit or any other symbol. Python supports Unicode encoding standard. The character set of
Python are:
Letters A – Z, a – z
Digits 0–9
Special symbols space + – * / ** \ ( ) [ ] { } // = != == < > ' " ''' . , ; : % ! & # <= >= @ _ (underscore)
Whitespaces Blank space, tabs (), carriage return (), newline, formfeed
Other characters Python can process all ASCII and Unicode characters as part of data or literals.

TOKENS IN PYTHON
The smallest individual unit in a program is known as a Token or a lexical unit. Python has the following
tokens:
1. Keywords
2. Identifiers (Names)
3. Literals
4. Operators
5. Punctuators
Keywords
 A Keyword is a predefined word having special meaning reserved by the programming language.
 A keyword must not be used as a normal identifier name.
 Python programming language has the following keywords:

False assert del for in Or while


None break elif from is Pass with
True class else global lambda Raise yield
and continue except if nonlocal Return
as def finally import not Try

Identifiers (Names)
 Identifiers are the names given to different parts of the program such as variables, functions, lists,
dictionaries, etc.
 Python is case sensitive as it treats upper and lower-case characters differently.
 Naming rules for Python identifiers:
 Variable names must only be a non-keyword word with no spaces in between.
 Variable names must be made up of only letters, numbers and underscore (_).
 Variable names cannot begin with a number.
Examples for Valid and Invalid Identifiers
 The following are some valid identifiers:
Myfile, DATE9_7_77, MYFILE, _DS, _CHK, FILE13, Z2TOZ9, _HJI3_JK

 The following are some invalid identifiers:


DATA–REC Contains special character –
(hyphen)
29CLCT Starting with a digit
Break Reserved word / Keyword
My.file Contains special character dot (.)

Literals / Values
Literals are data items that have a fixed / constant value. The various types of literals are:
1. String Literals
 A string literal is a sequence of characters surrounded by single or double or triple quotes.
 Single line strings must terminate in one line.
 Multiline strings are strings spread across multiple lines. With single and double quotes, each line
other than the concluding line has an end character \ (backslash) but with triple quotes, no
backslash is needed.

 In strings, you can include non-graphic characters through escape sequences as given below:

Size of Strings: Python determines the size of a string as the count of characters in the string. But if your
string literal has an escape sequence contained within it, then make sure to count the escape sequence as
one character. Some examples are:
'\\' Size is 1 (\\ is an escape sequence to represent backslash)
'abc' Size is 3
"\ab" Size is 2 (\a is an escape sequence, thus one character)
"Seema\'s pen" Size is 11 (For typing apostrophe (') sign, escape sequence \' has been used)
"Amy's" Size is 4 (Python allows a single quote without escape sequence in double-
quoted string and vice versa
For multiline strings created with triple quotes, while calculating size, the EOL (end-of-line) character at
the end of the line is also counted in the size. For example, if you have created a string Str3 as:
Str3='''a The enter keys are considered as EOL (end-of-line)
b characters and counted in the length of multi-line
c''' string.
then size of the string Str3 is 5 (three characters a, b, c and two EOL characters that follow characters
a and b respectively).
For multiline strings created with single / double quotes and backslash character at end of the line, while
calculating size, the backslashes are not counted in the size of the string; also you cannot put EOLs using
return key in single / double quoted multiline strings, e.g.,
Str4='a\
b\
c'
The size of string Str4 is 3 (only 3 characters, no backslash counted).
To check the size of the string, you can also type len(<stringname>) command on the Python
prompt in console window shell as shown below:
>>> Str3='''a
b
c'''
>>> Str4='a\
b\
c'
>>> len(Str3)
5
>>> len(Str4)
3
>>>
2. Numeric Literals:
 These literals are numeric values and can be one of the following types:
a. int (signed integers) are the positive or negative whole numbers with no decimal point. The
integer literals can be written in:
 Decimal form: an integer with only digits 1–9. e.g., 1234, 4100, etc.
 Octal form: an integer beginning with 0o (zero followed by letter o)
e.g., 0o35, 0o77, etc.
In octal number system, 8 and 9 are invalid digits.
 Hexadecimal form: an integer beginning with 0x (zero followed by letter x)
e.g., 0x73, 0xAF, etc.
Valid digits for hexadecimal numbers are 0 – 9 and A – F.
b. Floating Point or Real literals represent real numbers and are written with a decimal point
dividing the integer and fractional parts.
These literals can be written in fractional form e.g., –13.0, .75, 7. etc. or in Exponent form e.g.,
0.17E5, 3.E2, .6E4, etc.
c. Complex number literals are of the form a + bJ, where a and b are floats and J (or j) represents
√(−1), which is an imaginary number.
a is the real part of the number, and b is the imaginary part.
3. Boolean Literals
 A Boolean literal in Python is used to represent one of the two Boolean values, i.e., True (Boolean
true) or False (Boolean false).
 A Boolean literal can either have value as True or as False.
4. Special Literal (None)
 Python has one special literal, which is None.
 The None literal is used to indicate the absence of value.
 Python can also store literal collections, in the form of tuples, lists, etc.

Operators
Operators perform some computation / action when applied to operands (i.e., variables and other objects) in
an expression.
Unary Operators: The operators that require one operand to operate upon. Following are some unary
operators:
+ Unary plus – Unary minus
~ Bitwise complement not Logical negation
Binary Operators: The operators that require two operands to operate upon. Following are some binary
operators:
The operators can be:
 Arithmetic operators (+ Addition, – Subtraction, * Multiplication, / Division, % Remainder / Modulus,
** Exponent (raise to power), // Floor division)
 Bitwise operators (& Bitwise AND, | Bitwise OR, ^ Bitwise exclusive OR [XOR]),
 Shift operators (<< Shift left, >> Shift right),
 Identity operators (is is the identity same ?, is not is the identity not same ?),
 Relational operators (< Less than, > Greater than, <= Less than or equal to, >= Greater than or equal to,
== Equal to, != Not equal to),
 Logical operators (and Logical AND, or Logical OR),
 Assignment operator (= Assignment),
 Membership operators (in, not in), and
 Arithmetic-Assignment operators (+= Assign sum, –= Assign difference, *= Assign product,
/= Assign quotient, %= Assign remainder, **= Assign exponent, //= Assign floor division).

Punctuators
 Symbols are used in programming languages to organize the program structure, and to indicate the
emphasis of expressions and statements.
 Most common punctuators of Python programming language are:
'"#\()[]{}@:,.`=
BAREBONES OF A PYTHON PROGRAM

This sample program contains various components such as:


 Expressions, which are any legal combination of symbols that represent a value.
 Statements, which are programming instructions.
 Comments, which are additional readable information to clarify the source code. Comments can be
 Single line comments, that start with #, and
 Multi-line comments that can be either triple-quoted strings or multiple # style comments.
 Functions, which are named code sections and can be reused by specifying their names (function
calls).
 Block(s) or suite(s), which is a group of statements, which are part of another statement of a
function. All statements inside a block or suite are indented at the same level. Statements requiring
suite / code-bloc have a colon (:) at their end. You cannot unnecessarily indent a statement; Python
will raise error for that.

Python Style Rules and Conventions


 Statement Termination: Python does not use any symbol to terminate a statement. when you end a
physical code-line by pressing Enter key, the statement is considered terminated by default.
 Maximum Line Length: Line length should be maximum 79 characters.
 Lines and Indentation: Blocks of code are denoted by line indentation, which is enforced through 4
spaces (not tabs) per indentation level.
 Blank Lines: Use two blank lines between top-level definitions, one blank line between method /
function definitions.
 Avoid multiple statements on one line: Although you can combine more than one statements in one
line using symbol semicolon (;) between two statements, but it is not recommended.
 Whitespace: You should always have whitespace around operators and after punctuation but not with
parentheses. Python considers ' ' (space), '\n' (newline), '\t' (horizontal tab), '\v' (vertical tab), '\f '
(formfeed) and '\r' (carriage return) as white spaces.
 Case Sensitive: Python is case-sensitive, so case of statements is very important. Be careful while
typing code and identifier-names.
 Docstring Conventions: Conventionally triple double quotes (""") are used for docstrings.
 Identifier Naming: You may use underscores to separate words in an identifier, e.g., loan_amount or
use CamelCase by capitalizing first letter of each word, e.g., LoanAmount or loanAmount.
VARIABLES AND ASSIGNMENTS
 Variables represent labelled storage locations, whose values can be manipulated during program
execution.
 To create a variable, assign to its name the value of appropriate type.
Example: The following statements create variables namely Student to hold a student’s name and Age to
hold student’s age.
Student = 'Jacob'
Age = 16
 Python will internally create labels referring to these values.
Lvalues and Rvalues:
lvalue : The objects to which you can assign a value or expression. Lvalues can come on
lhs (left hand side) or rhs (right hand side) of an assignment statement.
rvalue : The literals and expressions that are assigned to lvalues.
Rvalues can come on rhs of an assignment statement.
For example, you can say that
a=20
b=10
But you cannot say
20=a
or 10=b
or a+2=b
The above three statements result in error. In Python, assigning a value to a variable means, variable’s label
is referring to that value.
Multiple Assignments
1. Assigning same value to multiple variables.
Example:
a = b = c = 10
The above statement will assign value 10 to all three variables a, b, c.
2. Assigning multiple values to multiple variables.
Example:
x, y, z = 10, 20, 30
The above statement will assign value 10 to x, 20 to y and 30 to z.
In Python, assigning a value to a variable means, variable’s label is referring to that value.

Variable Definition:
A variable is defined only when you assign some value to it. Using an undefined variable in an expression /
statement causes an error called NameError. For example, consider the following code fragment:
print(x)
x=20
print(x)
When you run the above code, it will produce an error for the first statement as:
NameError: name 'x' is not defined
The reason for above error is implicit; printing / using uncreated (undefined) variable results into error. So,
to correct the above code, you need to first assign something to x before using it in a statement.
x=0 # variable x created now
print(x)
x=20
print(x)
The above code will execute without any error.
Dynamic Typing
 A variable pointing to a value of a certain type can be made to point to a value / object of different type.
Example:
X = 10
print (X)
X = “Hello World”
print (X)

 With dynamic typing, Python makes a label refer to new value with new assignment.
 Although Python is comfortable with changing types of a variable, the programmer is responsible for
ensuring right types for certain type of operations. For example,
x=10
y=0
y=x/2 # Legal, because two integers can be used in divide operation
x='Day' # Python is comfortable with dynamic typing
y=x/2 # ERROR! a string cannot be divided.
 If you want to determine the type of a variable, you can use type() in following manger:
type(<variable name>)
 For example, consider the following sequence of commands that uses type() three times:
>>> a=10
>>> type(a) # The type returned as int (integer)
<class 'int'>
>>> a=20.5
>>> type(a) # The type returned as float (floating-point number)
<class 'float'>
>>> a="hello"
>>> type(a) # The type returned as str (string)
<class 'str'>
Dynamic Typing vs. Static Typing
In static typing, a data type is attached with a variable when it is defined first and it is fixed, i.e., data type of
a variable cannot be changed, whereas there is no such restriction in dynamic typing.
Python supports dynamic typing.

SIMPLE INPUT AND OUTPUT


The input() function is used to get input from user interactively. The general usage of this function is:
variable_to_hold_the_value=input(<prompt to be displayed>)
For example,

will display the prompt as:

The input() function always returns a value of string type. Python offers two functions int() and
float() to convert the values received through input() into int and float types.
The general usage of these functions in input() are:
<variable_name>=int(input(<prompt string>))
Or
<variable_name>=float(input(<prompt string>))
Example:

While inputting integer values using int() or float values using float() with input(), make sure that
the value being entered must be compatible to int type or float type (e.g., 'abc' cannot be converted to
int or float, hence it is not compatible).

Output Through print() Statement


The print() function is used to send output to standard output device (i.e, monitor). The syntax is:
print(*objects,[sep=' ' or <separator-string> end='\n' or <end-string>])
*objects means it can be one or multiple comma separated objects.
Examples:
print("hello") # a string
print(17.5) # a number
print(3.14159*(r*r)) # the result of a calculation, which will be performed
and then printed (assuming that some number has
been assigned to the variable r)
print("I\'m ",12+5, "years old.") # multiple comma separated expression

Features of print statement:


 It auto-converts the items to strings. If you are printing a numeric value, it will automatically convert it
into equivalent string ant print it; for numeric expressions, it first evaluates them and then converts the
result to string, before printing.
 It inserts spaces between items automatically because the default value of sep argument (separator
character) is space (' ').
Example:

You can change the value of separator character with sep argument of print ( ).

 It appends a newline character at the end of the line unless you give your own end argument.
Example:
print("My name is Amit. ")
print("I am 16 years old. ")
will produce the output as:
My name is Amit.
I am 16 years old.
If you explicitly give an end argument with a print() function, then the print() will print the line and
end it with the string specified with the end argument, and not the newline character. For example,
print("My name is Amit. ", end = '$')
print("I am 16 years old.")
will print the output as:
My name is Amit. $I am 16 years old.

You might also like