Python Complete Beginner’s Guide
Basic Setups
- First, you need to visit this website and Download & Install Python on your system.
- If you don’t have an editor Download & Install Visual Studio Code from this website .
- To Check Python is Installed or Not in your PC , type the following code in your Terminal
python --version
4. Save the Python file name in .py extension
5. Run the Python Code using the command :
Python Your_file_name.py
Character Sets
Valid character used in Python.
i) Alphabets: A - Z, a - z
ii) Digits: 0-9
iii)Special Characters: !,@, #, &, $, ^, *, (, ), ….. etc
Variables ( Identifiers )
Names that refers to a value or Name given to an entity used in programming.
#Example 1.1
a = 6
b = 4.3
c = “Hello world”
Rules for naming Variables
i) It should starts with an alphabet or Underscore(_).
ii) Digits are considered, But don’t use in start.
iii) Can’t use a keyword as an identifiers.
iv) Uppercase and Lowercase letters are distinct.
v) Can’t use white space or blank space in Variables.
#Example 1.2
var = 1
_var = 2
var_three = 3
Var = 4
VAR = 5
var1 = 6
Keyword
Special Words have a predefined meaning in programming language.
These are the list of Python keywords.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass
Data Types
Types Used in ProgramBooleans : boolNumbers : int, Float, complexStrings : strBinary : bytes, bytearrayLists : []Tuples : ()Sets : set, frozensetDictionaries : { "key" : "Value" } or dict()
Literals
Constant value assigned to a variable.
a) Integer Literals
Eg ; a=5, b=10
b) Floating point literals
Eg ; pi=3.14
c) String literals
Eg ; a=’MP’ , b=”Channels”
d) Boolean literals
Eg; True , False
e) Special literals
Eg; None
Indentations
Python use indentation to indicate blocks of code. Some other language like c, c++, java use curly brackets { } to indicate blocks of code.
#Example 1.3
if 4 < 5 :
print("Five is greater")#Output
IndentationError: expected an indented block#correct
if 4 < 5 :
print("Five is greater")#Output
Five is greater
Indentation should be at least 1 , But same number of spaces or indentations inside the same code blocks.
#Example 1.4
if 4 < 5 :
print(“Five is greater”)
print(“Four is lesser”)#Output
IndentationError: expected an indent#correct
if 4 < 5 :
print("Five is greater")
print(“Four is lesser”)#Output
Five is greater
Four is lesser
Input Operators
• Input() : get input as integer.
#Example 1.5
a = input(“Enter a number”)
• raw_input() : get input as String, here casting is used to convert the type.
#Example 1.6
a = raw_input(“Enter a string”)
b = int(raw_input(“Enter a number”))
c = float(raw_input(“Enter a fractional number”))
Output Operator
print()
#Example 1.7
print (c)
print (a,b)
print (“the result is “,c)
print (a,”is greater than”,b)
Python Sample Code
#Example 1.8
a=int(input())
#a=int(raw_input())
b=int(input())
#b=int(raw_input())
c=a+b
print(“The result is”,c)#Output
2
3
The result is 5ora=input(“Enter first ”)
b=input(“Enter second ”)
c=a+b #Here '+' act as concatenation Operator
print(“the result is ”,c)#Output
Enter first a
Enter second b
the result is ab
Python interpreter treats each line in a Python script as a statement, and it return a new line character at the end of a statement. So it doesn’t require a semicolon ; at the end of each statement like c, c++, Java, etc.
Operators & Expression
Operators are Symbols used to perform some operation. Eg: +, - , * , / , % , ** , < , > ….etc.
Expressions are Combination of Operators and Operands. Eg: a + b , a — b , a * b ….etc.
Arithmetic Operators & Expression
Operator Description Example+ Add Sum of two operands a + b– Subtract Difference between the two operands a - b* Multiply Product of the two operands a * b/ Division Quotient of the two operands a / b// Floor Division Quotient of the two operands a // b
without fraction part% Modulus Remainder after division a % b
of ‘a’ by ‘b.’** Exponent Power of ‘a’ raised by ‘b’ a ** b
Relational Operators & Expression
Operator Description Example> Greater than if the left operand is greater a > b
than the right,then it returns true.< Less than if the left operand is less than a < b
the right, then it returns true.== Equal if the two operands are equal, a == b
then it returns true.!= Not equal if two operands are not equal, a != b
then it returns true.>= Greater than
or equal if the left operand is greater than a >= b
or equal to the right,then it
returns true.
<= Less than
or equal if the left operand is less than a <= b
or equal to the right, then it
returns true.
Logical Operators & Expression
Operator Description Exampleand Returns True if both statements a and b
are true , Else Return Falseor Returns True if one of the statements a or b
is true ,Else Return Falsenot Reverse the result, returns True not a
if the result is False
Bitwise Operators & Expression
Operator Description Example& Bitwise AND compares two operands on a bit level a & b
and returns 1 if both the bits are 1| Bitwise OR compares two operands on a bit level a | b
and returns 1 if any of the bits is 1~ Bitwise NOT inverts all of the bits in a single ~a
operand^ Bitwise XOR compares two operands on a bit level a ^ b
and returns 1 if any of the bits is 1
,but not both>> Right shift shifts the bits of ‘a’ to the a >> b
right by ‘b’ number of times<< Left shift shifts the bits of ‘a’ to the left a << b
by ‘b’ number of times
Assignment Operators & Expression
Operator Expression Same as = a=1 a=1 += a+=1 a=a+1 -= a-=1 a=a-1 *= a*=1 a=a*1 /= a/=1 a=a/1 %= a%=1 a=a%1 **= a**=1 a=a**1 &= a&=1 a=a&1 |= a|=1 a=a|1 ^= a^=1 a=a^1 >>= a>>=1 a=a>>1 <<= a<<=1 a=<<1
Identity Operators & Expression
Operator Description Exampleis Returns True if both Operands x is y
are Same is not Returns True if both Operands x is not y
are not same
Membership Operators & Expression
Operator Description Examplein Returns True if a sequence with x in y
the specified value is present in
the objectnot in Returns True if a sequence with the x not in y
specified value is not present in
the object
operators precedence
List of all operators from highest precedence to lowest.
Operator Description { } Parentheses Top Precedencef(args…) Function callsx[index:index] Slicingx[index] Subscriptionx.attribute Attribute reference** Exponent~x Bitwise not+x, -x Positive, negative*, /, % Multiply, division, remainder+, – Addition, subtraction<<, >> Left Shifts, Right Shifts& Bitwise AND^ Bitwise XOR| Bitwise ORin, not in, is, Relational, membership, identity
is not, <, <=, >,
>=,<>, !=, ==not x Boolean NOTand Boolean ANDor Boolean ORlambda Lambda expression Low Precedence
Define flow of execution of a program
- Sequential Control structure
Flow of Execution is Continuous or Sequential.
#Example 1.9
a=5
b=6
c=a+b
print(" The result is ”,c)#Output
The result is 11
2. Conditional/Branching Control Structure
Based on a particular condition set of statement selected for Execution.
a) Simple if
#syntaxif test_expression:
statement(s)#Example 1.10
num = int(input("Enter a number: "))
if num > 0:
print("Positive number")#Output
Enter a number: 2
Positive number
b) If- Else Statements
#syntaxif test_expression:
Body of if Statement
else:
Body of else#Example 1.11
num =int(input(“Enter a number: “))
if num >= 0:
print(“Positive or Zero”)
else:
print(“Negative number”)#Output
Enter a number: -1
Negative number
b) if…elif…else (Chained Condition)
#syntaxif test_expression1:
Body of if
elif test_expression2:
Body of elif
...
else:
Body of else#Example 1.12 | To Check a given number is +,-,or 0num =int(input(" Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")#Output
Enter a number: 0
Zero
c) Nested If Statements
if within an if Statements.
#Example 1.13 | To Check a given number is +,-,or 0num = int(input(“Enter a number: “))
if num >= 0:
if num == 0:
print(“Zero”)
else:
print(“Positive number”)
else:
print(“Negative number”)#Output
Enter a number: 5
Positive number
3)Looping/Iterative Control Structure
Based on a particular condition, the statement was executed repeatedly.
a) While Loop
#syntaxwhile test_expression:
Body of while#Example 1.14 | To Find the sum of first n natural Numbers
n = int(input(“Enter the number: “))
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1
print(“The sum is”,sum)#Output
Enter the number: 10
The sum is 55
The range() function
Generate a sequence of numbers. Eg : range(10):will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size for these function range(start,stop,step_size) , step size defaults to 1 if not provided.
#Example 1.15 #Output
range(0,20) : 0,1,2,3,……….19
range(0,20,2) : 0,2,4,6,……….18
range(1,20,2) : 1,3,5,7,……….19
b)For Loop
#syntax:for val in sequence:
Body of for#Example 1.16 | To find the sum of all numbers in the given List
numbers = [6,5,3,8,4,2,5,4,11]
sum = 0
for val in numbers:
sum = sum+val
print(“The sum is”,sum)#Output
The sum is 48
Python Comments
single Line Comment (#)
#Example 1.17
#This is a comment
#print “Hello”
multiple Line comments (‘’’ or “””)
#Example 1.18
”””This is also a
perfect example of ...
multiple line comments”””