0% found this document useful (0 votes)
10 views

Python M1 Ktunotes - in

basics python

Uploaded by

KARTHIK KRISHNAN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python M1 Ktunotes - in

basics python

Uploaded by

KARTHIK KRISHNAN
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

PYTHON MODUL 1

Python - Programming
Python Programming Language
• Python is a high level language
• Introduced in 1991 by Guido Van Rossum, a Dutch computer programmer
• Interpreted Language
Advantages of Python
• Considerably less number of lines of code
• Simplest syntax, availability of library and built-in modules
• Extensive collection of third party resources
• Cross platform language
• Desktop application, database application, network programming, game programming, mobile
development, machine learning
Installing Python in your PC
• Presently the version is Python 3.x
• http://www.python.org/downloads
• Download the suitable version based on OS (Windows/Linux etc) and processor(32 bit/64bit)
• Download and install python interpreter
Interactive versus Script
• Interactive
• Command-line mode
• You type directly to Python one line at a time and it responds
• Script
You enter a sequence of statements (lines) into a file using a text editor and tell Python to execute the
statements in the file
Constants
• Fixed values such as integers, letters and strings are called constants because their values does not change
• Numeric constants
• String constants use single quotes(‘) or double quotes(“)
Variables
• A variable is a named place in memory where a programmer can store the data and later retrieve the data
using the variable name
• Programmers get to choose the names of the variable
• You can change the contents of a variable in a later statement
Variable Name Rules
• Must start with a letter or underscore_
• Must consist of letters, numbers and underscores
• Case sensitive
• Good: spam, egg, spam23, _egg
• Bad: 23spam, #sign, var.12
• Different: spam, SPAM, Spam
Reserved words
• You cannot use reserved words as variable names / identifiers
And except lambda with
As finally nonlocal while
Assert false None yield
Break for not

Downloaded from Ktunotes.in


Class from or
Continue global pass
Def if raise
Del import return
Elif in True
Else is try

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.
• a=10
• Name=“John”
Multiple Assignment
• Python allows you to assign a single value to several variables simultaneously
•a=b=c=1
• a, b, c = 1, 2, ”john” a = b = c = 1
Statements
• A statement is an instruction that the Python interpreter can execute
• When you type a statement on the command line, Python executes it and displays the result, if there is one
• A script usually contains a sequence of statements. The result appears one at a time as the statements
execute.
• print 1
• x=2
• print(x)
• Produces the output:
•1
•2
Expression
• An expression is a combination of values, variables and operators
• Python interpreter evaluates a valid expression
• 10-2
• (10-5)/5
Operators in Python
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
1. Arithmetic Operators
• + (addition)
• - (subtraction)
• * (multiplication)
• / (division)

Downloaded from Ktunotes.in


• // (floor division)
• % (modulus)
• ** (exponent)
Arithmetic operators- Example
• Suppose x=7 and y=2
•x+y=9
•x–y=5
• x * y = 14
• x / y = 3.5
• x // y = 3 (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) -11//3=4
• x % y = 1 (remainder)
• x ** y = 49
2. Comparison Operators
• These operators compare the values on either sides of them and decide the relation among them. They are
also called Relational operators.
• ==
• !=
•>
•<
• >=
• <=
Comparison Operator Example
• Suppose a=10 and b=3
• a == b returns false
• a != b returns true
• a > b returns true
• a < b returns false
• a >= b returns true
• a <= b returns false
3. Assignment Operators
•=
• +=
• x+=2 is same as x=x+2
• -=
• *=
• /=
• %=
• x%=2 is same as x=x%2
• //=
4 Bitwise Operators
• Bitwise operator works on bits and performs bit by bit operation
• & Binary AND
• | Binary OR
• ^ Binary XOR
• ~ Binary one’s complement
• << Binary left shift

Downloaded from Ktunotes.in


• >> Binary right shift
5.Logical Operators
• and
• If both the operands are true then condition becomes true.
• or
• If any of the two operands are non-zero then condition becomes true.
• not
• Used to reverse the logical state of its operand.
6.Membership Operators
• Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples
• in
• Evaluates to true if it finds a variable in the specified sequence and false otherwise.
• x in y, here in results in a 1 if x is a member of sequence y.
• not in
• Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.
• x not in y, here not in results in a 1 if x is not a member of sequence y.
7. Identity Operators
• Identity operators compare the memory locations of two objects. There are two Identity operators
1. is - Evaluates to true if the variables on either side of the operator point to the same object and false
otherwise.
eg: x is y, here is results in 1 if id(x) equals id(y).
2. is not - Evaluates to false if the variables on either side of the operator point to the same object and true
otherwise.
Eg: x is not y, here is not results in 1 if id(x) is not equal to id(y).
OPERATOR PRECEDENCE
• PEMDAS
• Paranthesis
• Exponent
• Multiplication and Division has same precedence
• Addition and Subtraction has same precedence

Downloaded from Ktunotes.in


Data Types
• Python accepts various data types like Integer, Float and String
• Integers are numbers with no decimal part
• 8, -10, 0, 1789
• Float :numbers that has decimal part
• 6.23, 9.0, -0.34
• String: refers to text. Strings are defined within single quotes(‘) or double quotes(”)
• “John”, ‘Good Evening!’ Prof.
• If you are not sure what type a value has, the interpreter can tell you using type() function
• type(“Hello World”) => class ‘str’
• type(17) =>class ‘int’
• type(2.3) =>class ‘float’
• N=10
type(N) =>class ‘int’
String concatenation
• Multiple strings can be combined using the concatenate sign( + )
• “Good”+”Morning” is equivalent to the string “GoodMorning”
• “Good ” + 2 => Error, can only concatenate string
Type Casting
• Type casting helps to convert from one data type to another ie from integer to string and vice-versa
• 3 built-in functions in Python
• int()
• float()
• str()
Type Casting
• int(7.6) outputs 7
• int(“4”) outputs 4
• float(6) outputs 6.0
• str(4) outputs “4”
• str(“Ram”) outputs “Ram”
input()
• Pause the program and read data from the user
• Eg1: name = input(“Enter your name”)
print(“Welcome”, name)
Eg:2: # To read two numbers from user and display its sum
n1=input(“Enter First number”)
n2=input(“Enter Second Number”)
#Value read form the user will be a string. So covert into int
n1=int(n1)
n2=int(n2)

Downloaded from Ktunotes.in


sum=n1+n2
print(“Sum=”,sum)

Control flow statements


Control flow
• A program’s control flow is the order in which the program’s code executes
• The control flow of a Python program is regulated by conditional statements, loops, and function calls
• Raising and handling exceptions also affects control flow
if statement
• The Python compound statement if, which uses if, elif, and else clauses, lets you conditionally execute
blocks of statements.
• Python relies on indentation (whitespace at the beginning of a line) to define scope in the code

if statement example
userInput = input("Enter 1 or 2: ")
if userInput == "1":
print("Hello Python")
print("How are you")
elif userInput == "2":
print("Python is good")
print("I love Python")
else:
print("Invalid Number")
• The elif keyword is python’s way of saying "if the previous conditions were not true, then try this
condition".
• The else keyword catches anything which isn't caught by the preceding conditions
• The elif and else clauses are optional.
• Python does not have a switch statement, so you must use if, elif, and else for all conditional processing.
Python Loops
• Python has two primitive loop commands:
• while loops
• for loops
While statement
• while statement supports repeated execution of a statement or block of statements that is controlled by a
conditional expression
• With the while loop we can execute a set of statements as long as a condition is true.
while(expression):
statement1
statement2

Downloaded from Ktunotes.in


while example:
#Prints Hello Python 3 times
count=0
while (count <3):
print(“Hello Python”)
count=count+1
for loop
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
• This is less like the for keyword in other programming languages, and works more like an iterator method
• With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
for val in sequence:
statement(s)
Example
#Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
• Looping Through a String
• Even strings are iterable objects, they contain a sequence of
characters:
#Loop through the letters in the word "banana":
for x in "banana":
print(x)
break statement
• With the break statement we can stop the loop before it has looped through all the items:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Output:
apple
banana
Break statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
Output:
apple
continue statement
• With the continue statement we can stop the current iteration of the loop, and continue with the next:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

Downloaded from Ktunotes.in


Output:
apple
cherry
range() function
• To loop through a set of code a specified number of times, we can use the range() function,
• The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
for x in range(6):
print(x)
• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
• The range() function defaults to 0 as a starting value
• it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to
6 (but not including 6):
for x in range(2, 6):
print(x)
• The range() function defaults to increment the sequence by 1
• it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):
for x in range(2, 30, 3):
print(x)
for…else
• else keyword in a for loop specifies a block of code to be executed when the loop is finished
#Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested Loops
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each iteration of the "outer loop“:
#Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
pass statement
• For loops cannot be empty, but if you have some reason to have a for loop with no content, put in the pass
statement to avoid getting an error
for x in [0, 1, 2]:
pass
while.. else
• With the else statement we can run a block of code once when the condition no longer is true
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Downloaded from Ktunotes.in

You might also like