Skip to content

Basics

First Python Program

print('Hello World!')
print("Hello World!")
print("""Hello 
        World!""")


Quotation

Python accepts single ('), double (") and triple (''' or """) quotes to denote string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal −

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""


Comments

# First comment
print('Hello World!') # second comment


Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.

Here are naming conventions for Python identifiers:

  • Class names start with an uppercase letter. All other identifiers start with a lowercase letter
  • Starting an identifier with a single leading underscore indicates that the identifier is private
  • Starting an identifier with two leading underscores indicates a strongly private identifier
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.


Reserved Words

The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield


Indentation

Python provides no braces to indicate blocks of code for class and function definitions or flow control. 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')


Multi-Line Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character () to denote that the line should continue. For example −

total = item_one + \
item_two + \
item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −

days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']


User Input

The following line of the program displays the prompt, and waits for the user to take action −

marks = input('Enter marks')
print(marks)


Variables and Data Types

Variables

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.


Assigning Values to Variables

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example −

counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print(counter) print(miles) print(name)

Multiple Assignment Python allows you to assign a single value to several variables simultaneously. For example −

a = b = c = 1
You can also assign multiple objects to multiple variables. For example −
a, b, c = 1, 2, "john"


Standard Data Types

The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.

Python has five standard data types:

  • Number
  • String
  • List
  • Dictionary
  • Tuple


Number

Numeric data types store numeric values. Number objects are created when you assign a value to them. For example −

var1 = 1
var2 = 10

Python supports four different numerical types:

  • int (signed integers)
  • float (floating point real values)
  • complex (complex numbers)
int : 10, -20, 51651461464616
float : 15.2653
complex : 3.14j, 3.14+20j


String

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. For example −

str = 'Hello World!'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""


List

Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. For example −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']


Dictionary

Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print(tinydict) # Prints complete dictionary
print(tinydict.keys()) # Prints all the keys
print(tinydict.values()) # Prints all the values
This produce the following result −

{'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john']

Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.


Tuple

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
print(tuple) # Prints complete list
print(tuple[0]) # Prints first element of the list

This produce the following result −

('abcd', 786, 2.23, 'john', 70.200000000000003) abcd

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list


Data type conversion

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function. There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

int(x [,base])
long(x [,base] )
float(x)
complex(real [,imag])
str(x)
tuple(s)
list(s)
set(s)
dict(d)
frozenset(s)
chr(x) : Converts an integer to a character.
hex(x)
oct(x)


Operator

Operators are the constructs which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator

  • Python language supports the following types of operators.
  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators


Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then

+ Addition: a + b = 30
- Subtraction: a  b = -10
* Multiplication: a * b = 200
/ Division: b / a = 2
% Modulus: b % a = 0
** Exponent: a**b = 10 to the power 20
// Floor Division: 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):


Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators. Assume variable a holds 10 and variable b holds 20, then:

== : (a == b) is not true.
!= : not equal
> : (a > b) is not true.
< : (a < b) is true.
>= : (a >= b) is not true.
<= : (a <= b) is true.


Assignment Operators

= equals: c = a + b
+= Add AND: c += a is equivalent to c = c + a
-= Subtract AND: c -= a is equivalent to c = c - a
*= Multiply AND: c *= a is equivalent to c = c * a
/= Divide AND: c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus AND: c %= a is equivalent to c = c % a
**= Exponent AND: c **= a is equivalent to c = c ** a
//= Floor Division: c //= a is equivalent to c = c // a


Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows:

a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011


Logical Operators

There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then Used to reverse the logical state of its operand.


Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below

in: x in y
not in: x not in y


Operators Precedence

The following table lists all operators from highest precedence to lowest.

** : Exponentiation (raise to the power)
~ + -
* / % //
+ -
>> << : Right and left bitwise shift
& : Bitwise 'AND'
^ | : Bitwise exclusive `OR' and regular `OR'
<= < > >=
<> == !=
= %= /= //= -= += *= **= : Assignment operators
is is not : Identity operators
in not in : Membership operators
not or and : Logical operators