Python Session3-4 Variable
Python Session3-4 Variable
Module 1
• Topic 1: Why should you learn to write programs
• Topic 2: Variables, expressions and statements
• Topic 3: Conditional execution
• Topic 4: Functions
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.1
WhenValues andaTypes
you type large integer, you might be tempted to use commas between groups of three
digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
>>> print(1,000,000)
100
Well, that’s not what we expected at all! Python interprets 1,000,000 as a commaseparated
sequence of integers, which it prints with spaces between.
This is the first example we have seen of a semantic error: the code runs without producing an
error message, but it doesn’t do the “right” thing.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.2 Variables
One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a
name that refers to a value.
An assignment statement creates new variables and gives them values:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931
This example makes three assignments. The first assigns a string to a new variable named message; the second
assigns the integer 17 to n; the third assigns the (approximate) value of π to pi.
To display the value of a variable, you can use a print statement:
>>> print(n)
17
>>> print(pi)
3.141592653589793
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.2 Variables
2.4 Statements
A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statements: print being
an expression statement and assignment.
When you type a statement in interactive mode, the interpreter 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.
For example, the script
print(1)
x=2
print(x)
produces the output
1
2
The assignment statement produces no output
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.6 Expressions
An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so
is a variable, so the following are all legal expressions (assuming that the variable x has been assigned a value):
17
x
x + 17
If you type an expression in interactive mode, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
But in a script, an expression all by itself doesn’t do anything! This is a common source of confusion for beginners.
Exercise 1: Type the following statements in the Python interpreter to see what they do:
5
x=5
x+1
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
If you expect the user to type an integer, you can try to convert the return value to int using the int() function:
>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
17
>>> int(speed)
17
>>> int(speed) + 5
22
But if the user types something other than a string of digits, you get an error:
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int() with base 10:
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.11 Comments
As programs get bigger and more complicated, they get more difficult to read. Formal languages
are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or
why.
For this reason, 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, and in Python they start with the
# symbol:
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
In this case, the comment appears on a line by itself. You can also put comments at the end of a
line:
percentage = (minute * 100) / 60 # percentage of an hour
Everything from the # to the end of the line is ignored; it has no effect on the program.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.11 Comments
Comments are most useful when they document non-obvious features of the code. It is
reasonable to assume that the reader can figure out what the code does; it is much more
useful to explain why.
This comment is redundant with the code and useless:
v = 5 # assign 5 to v
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.
Good variable names can reduce the need for comments, but long names can make complex
expressions hard to read, so there is a trade-off.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.13 Debugging
At this point, the syntax error you are most likely to make is an illegal variable name, like
class and yield, which are keywords, or odd~job and US$, which contain illegal characters.
If you put a space in a variable name, Python thinks it is two operands without an
operator:
>>> bad name = 5
SyntaxError: invalid syntax
>>> month = 09
File "", line 1 month = 09 ^
SyntaxError: invalid token
>>> principal = 327.68
>>> interest = principle * rate
NameError: name 'principle' is not defined
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
2.13 Debugging
The runtime error you are most likely to make is a “use before def;” that
is, trying to use a variable before you have assigned a value. This can
happen if you spell a variable name wrong:
Variables names are case sensitive, so LaTeX is not the same as latex. At
this point, the most likely cause of a semantic error is the order of
operations.
For example, to evaluate 1/2π, you might be tempted to write >>> 1.0 /
2.0 * pi
But the division happens first, so you would get π/2, which is not the
same thing! There is no way for Python to know what you meant to write,
so in this case you don’t get an error message; you just get the wrong
answer.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
Exercises
Exercise 2: Write a program that uses input to prompt a user for their name and then welcomes them.
Enter your name: Chuck
Hello Chuck
Exercise 3: Write a program to prompt the user for hours and rate per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Exercise 4: Assume that we execute the following assignment statements: width = 17 height = 12.0
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
1. width//2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. Use the Python interpreter to check your answers.
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
Exercises
Exercise 5: Write a program which prompts the user for a Celsius temperature, convert the temperature to
Fahrenheit, and print out the converted temperature.
(C*(9/5))+32
Exercise 6: Mention three types of error encountered in python programs. Explain the basic built in blocks of
python with an example python program to display format number(Fn=2 2n) for a ‘n’ value promoted by the
users
Fn=22n
Exercise 7: Write a python program to calculate the area of square, rectangle and circle. Print the results.
Take input from user.
(s2, w*h, pi*r2 )
Exercise 8: Predict the output and justify your answer: (i)11%9 (ii) 7.7//7 (iii) (200-70)*10/5 (iv)not “False”
(v)5*1**2
{ Ans: 2,1.0,260.0,True,5}
VIDYA VIKAS INSTITUTE
Department of Electronics & Communication Engineering OF ENGINEERING &
TECHNOLOGY
Exercises
N=int(input('enter the length of the y[n]=int(input())
sequence')) print(y)
x=[0,0,0,0,0] z=[0,0,0,0,0]
print('enter num1') w=[0,0,0,0,0]
for n in range(N): for n in range(N):
x[n]=int(input()) z[n]=x[n]+y[n]
print(x) w[n]=x[n]*y[n]
y=[0,0,0,0,0] print(z)
print('enter num2') print(w)
for n in range(N):