Variables, Keywords, Operators,
basic programs
Variable Expressions and Statements
• Value is a one of the fundamental thing, that a program manipulates.
• Variable is a name that refers to a value that maybe changed in the
program.
• The assignment statement creates new variables and gives them
values:
• >>> message = "What's up, Doc?"
• >>> n = 17
• >>> pi = 3.1415
Variable
• Variable names must be meaningful.
• It contains both numbers and letters, but they have to begin with a letter or
underscore symbol
• Case sensitive.
• The underscore (_) character can appear in a name.
• Eg.
– >>>76trombones = "big parade“ >>> more$ = 1000000
– SyntaxError: invalid syntax SyntaxError: invalid syntax
– >>> class = "Computer Science 101“
– SyntaxError: invalid syntax
Keywords
• Keywords define the language’s rules and structure and they can’t be
used as variable names.
• Python has twenty-nine keywords:
and def exec if not return
assert del finally import or try
break elif for in pass while
class else from is print yield
continue except global lambda raise
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. If there is more
than one statement, the results appear one at a time as the
statements execute.
Evaluating Expressions
• An expression is a combination of values, variables, and operators.
• If you type an expression on the command line, the interpreter
evaluates it and displays the result:
– >>> 1 + 1
– 2
• A value all by itself is considered an expression, and so is a variable.
>>> 17 >>> x
17 2
Simultaneous Assignments
Python also supports simultaneous assignments like this:
var1,var2…………..,varn=exp1,exp2…………….,expn
>>> a,b,c=4,5,6
>>> a
4
>>> b
5
>>> c
6
Write code to swap two numbers.
>>>X=1
>>>Y=3
>>>Temp=X
>>>X=Y
>>>Y=Temp
Can be written as:
>>>X=1
>>>Y=3
>>>X,Y=Y,X
• a, b, c = 5, 3.2, "Hello"
• print (a)
• print (b)
• print (c)
• x = y = z = "same"
• print (x)
• print (y)
• print (z)
Python Data Types
• Text Type: str
• Numeric Types: int, float, complex
• Sequence Types: list, tuple, range
• Mapping Type:dictionary
• Set Types: set
• Boolean Type: bool
Getting the Data Type
• You can get the data type of any object by using
the type() function:
• Example
• Print the data type of the variable x:
• x = 5
print(type(x))
Setting the Data Type
• Example Data Type Try it
• x = "Hello World" -str
• x = 20-int
• x = 20.5 -float
• x = 1j -complex
• x = ["apple", "banana", "cherry"] -list
• x = ("apple", "banana", "cherry") -tuple
• x = range(6)-range
Setting the Data Type
• x = {"name" : "John", "age" : 36} -dictionary
• x = {"apple", "banana", "cherry"} -set
mcq
• Which of the following is the correct extension of the Python file?
a) .python
b) .pl
c) .py
d) .p
• Which of the following character is used to give single-line comments
in Python?
a) //
b) #
c) !
d) /*
Operators and Operands
• Operators are special symbols that represent computations like
addition and multiplication.
• The values the operator uses are called operands
• When both of the operands are integers, the result must also be an
integer, and by convention, integer division always rounds down.
• +, -, *, /, %, **,//
• ** is used for exponential.
• / is also used for float division
• // is used to integer division
Operators and Operands
Python divides the operators in the following groups:
•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators
Python Arithmetic Operators
Operator Meaning Example 1: Arithmetic operators in Pyth
Example
+ Add two operands or unary plus x + y+ 2
Subtract right operand from the left or unary
- x - y- 2
minus
* Multiply two operands x*y
Divide left operand by the right one (always
/ x/y
results into float)
Modulus - remainder of the division of left
% x % y (remainder of x/y)
operand by the right
Floor division - division that results into
// whole number adjusted to the left in the x // y
number line
Exponent - left operand raised to the power
** x**y (x to the power y)
of right
Python Arithmetic Operators
• a = 10
• b=3
print("Addition:", a + b)
• print("Subtraction:", a - b)
• print("Multiplication:", a * b)
• print("Division:", a / b)
• print("Floor Division:", a // b)
• print("Modulus:", a % b)
• print("Exponentiation:", a ** b)
• print 9//2
• A 4.5
• B 4.0
• C4
• D Error
• What will be the value of the following Python expression?
>>> 4 + 3 % 5
a) 7
b) 2
c) 4
d) 1
Python Comparison Operators
Operator Meaning Example
Greater than - True
if left operand is
> x>y
greater than the
right
Less than - True if
< left operand is less x<y
than the right
Equal to - True if
== both operands are x == y
equal
Not equal to - True if
!= operands are not x != y
equal
Greater than or
equal to - True if left
>= operand is greater x >= y
than or equal to the
right
Less than or equal to
- True if left operand
<= x <= y
is less than or equal
to the right
Example 2: Comparison operators in Python
• a = 10
• b = 20
print("Equal to:", a == b)
• print("Not Equal to:", a != b)
• print("Greater than:", a > b)
• print("Less than:", a < b)
• print("Greater than or Equal to:", a >= b)
• print("Less than or Equal to:", a <= b)
Logical operators
Operator Meaning Example
True if both the
and x and y
operands are true
True if either of the
or x or y
operands is true
True if operand is
not false (complements not x
the operand)
Python Assignment Operators
Operator Description Example
= Assigns values from right side operands to left side
c = a + b assigns value of a + b into c
operand
+= Add It adds right operand to the left operand and assign the
AND result to left operand c += a is equivalent to c = c + a
-= Subtract It subtracts right operand from the left operand and
AND assign the result to left operand
c -= a is equivalent to c = c - a
*= Multiply It multiplies right operand with the left operand and
AND assign the result to left operand
c *= a is equivalent to c = c * a
/= Divide It divides left operand with the right operand and assign
AND the result to left operand c /= a is equivalent to c = c / a
%= It takes modulus using two operands and assign the
Modulus result to left operand
AND c %= a is equivalent to c = c % a
**= Performs exponential (power) calculation on operators
Exponent and assign value to the left operand
AND c **= a is equivalent to c = c ** a
Python Logical Operators
• a = 10
• b = 20
• print("AND operator:", a > 5 and b > 15) # True (both are true)
• print("OR operator:", a > 15 or b > 15) # True (one is true)
• print("NOT operator:", not(a > 15)) # True (because a > 15 is
False)
Bitwise operators
• Bitwise operators act on operands as if they were strings of binary
digits. They operate bit by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.
• In the table below: Let x = 10 (0000 1010 in binary)
• and y = 4 (0000 0100 in binary)
Bitwise operators
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
x | y = 14 (0000
| Bitwise OR
1110)
x ^ y = 14 (0000
^ Bitwise XOR
1110)
x >> 2 = 2 (0000
>> Bitwise right shift
0010)
x << 2 = 40 (0010
<< Bitwise left shift
1000)
Assignment operators
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
Special operators
Operator Meaning Example
True if the operands
is are identical (refer x is True
to the same object)
True if the operands
are not identical (do
is not x is not True
not refer to the
same object)
Example 4: Identity operators in Python
• x1 = 5
• y1 = 5
• # Output: False
• print(x1 is not y1)
x2 = 'Hello'
• y2 = 'Hello‘
• # Output: True
• print(x2 is y2)
• x3 = ‘h’
• y3 = ‘h’
# Output: False
• print(x3 is y3)
Membership operators
Operator Meaning Example
True if
value/variable is
in 5 in x
found in the
sequence
True if
value/variable is not
not in 5 not in x
found in the
sequence
Membership operators
• x = 'Hello world'
• y = {1:'a',2:'b'}
# Output: True
• print('H' in x)
# Output: True
• print('hello' not in x)
# Output: True
• print(1 in y)
# Output: False
• print('a' in y)
Python Bitwise Operators
• Bitwise operator works on bits and performs bit by bit
operation. Assume if a = 60; and b = 13; Now in the
binary format their values will be 0011 1100 and 0000
1101 respectively. Following table lists out the bitwise
operators supported by Python language with an example
each in those, we use the above two variables (a and b)
as operands −
• a = 0011 1100
• b = 0000 1101
• -----------------
Python Bitwise Operators
Operator Description Example
& Binary Operator copies a bit to the result if it exists in
(a & b) (means 0000 1100)
AND both operands
| Binary OR It copies a bit if it exists in either operand.
(a | b) = 61 (means 0011 1101)
^ Binary It copies the bit if it is set in one operand but
(a ^ b) = 49 (means 0011 0001)
XOR not both.
<< Binary The left operands value is moved left by the
Left Shift number of bits specified by the right operand.
a << 2 = 240 (means 1111 0000)
>> Binary The left operands value is moved right by the
Right Shift number of bits specified by the right operand.
a >> 2 = 15 (means 0000 1111)
Order of Operations
• When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.
– Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want.
– Exponentiation has the next highest precedence.
– Multiplication ,Float Division, Integer Division and remainder have
the same precedence, which is higher than Addition and Subtraction,
which also have the same precedence.
– Operators with the same precedence are evaluated from left to right.
Operations on Strings
• Mathematical operations can’t be performed on strings, even if the strings look like
numbers.
• the + operator represents concatenation.
• For Example:
– fruit = "banana"
– bakedGood = " nut bread“
– print fruit + bakedGood
• The * operator also works on strings; it performs repetition.
• For eg:
– "Fun"*3 is "FunFunFun"
Composition
• One of the most useful features of programming languages is their
ability to take small building blocks and compose them
Comments
• It is a good idea to add notes to your programs to explain in natural
language what the program is doing. These notes are called comments.
• they are marked with the # symbol:
•For eg:
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
FIRST PYTHON PROGRAM
• # This program prints Hello, world!
• print('Hello, world!')
Simplest Way to Receive User Input
• print("Enter anything: ")
• val = input()
• print("\nYou've entered:", val)
• Or
• val = input("enter the no")
print("\nYou've entered:", val)
Simplest Way to Receive User Input
• print("Enter an Integer Value: ", end="")
• val = int(input()) or val = float(input()) or val = str(input())
• print("\nYou've entered:", val)
Add Two Numbers in Python
• print("Enter First Number: ")
• numOne = int(input())
• print("Enter Second Number: ")
• numTwo = int(input())
• res = numOne+numTwo
• print("\nResult =", res)
Add Two Numbers in Python
• print("Enter Two Numbers: ", end="")
• nOne = float(input())
• nTwo = float(input())
• print(nOne, " + ", nTwo, " = ", nOne+nTwo)
Simple Celsius to Fahrenheit Conversion
• print("Enter Temperature in Celsius: ")
• cel = float(input())
• fah = (cel*1.8)+32
• print("\nEquivalent Value in Fahrenheit = ", fah)
Calculate Average & Percentage Marks in Python
• print("Enter Marks Obtained in 5 Subjects: ")
• mOne = int(input())
• mTwo = int(input())
• mThree = int(input())
• mFour = int(input())
• mFive = int(input())
• sum = mOne+mTwo+mThree+mFour+mFive
• avg = sum/5
• perc = (sum/500)*100
• print(end="Average Mark = ")
• print(avg)
• print(end="Percentage Mark = ")
• print(perc)
Find Area of Triangle based on Base and Height
• print("Enter the Base Length of Triangle: ")
• b = float(input())
• print("Enter the Height Length Triangle: ")
• h = float(input())
• a = 0.5 * b * h
• print("\nArea = ", a)
Python Solve Quadratic Equation
• To find the roots of a quadratic equation ax2 + bx + c = 0, we need to
first calculate the discriminant of the equation. Here is the formula to
find the discriminant:
• D = b2 - 4ac
• Where D refers to discriminant. After finding the discriminant, the
roots can be calculated as:
• R = (-b ± D ** 0.5) / (2*a)
• import cmath
• print("Enter the Value of a: ", end="")
• a = int(input())
• print("Enter the Value of b: ", end="")
• b = int(input())
• print("Enter the Value of c: ", end="")
• c = int(input())
• discriminant = (b**2) - (4*a*c)
• solutionOne = (-b-cmath.sqrt(discriminant))/(2*a)
• solutionTwo = (-b+cmath.sqrt(discriminant))/(2*a)
• print("\nRoot 1 =", solutionOne)
• print("Root 2 =", solutionTwo)
Find and Print ASCII Value of a Character
• print("Enter a Character: ")
• ch = input()
• asc = ord(ch)
• print("\nASCII Value:", asc)
Python program to convert Kilometres to Miles
• kilometre_1 = float (input ("Please enter the speed of car in Kilometre
as a unit: "))
• conversion_ratio_1 = 0.621371
• miles_1 = kilometre_1 * conversion_ratio_1
• print ("The speed value of car in Miles: ", miles_1)
Python program to display calendar
1. import calendar
2. # Enter the month and year
3. yy = int(input("Enter year: "))
4. mm = int(input("Enter month: "))
5.
6. # display the calendar
7. print(calendar.month(yy,mm))