Python Unit 1(Lecture 3)
Python Unit 1(Lecture 3)
Programming
(UNIT-1)
Lecture-3
Variables
• Variables represent labelled storage locations, whose values can be
manipulated during program run.
• In Python, to create a variable, just assign to its name the value of
appropriate type. For example, to create a variable namely Student to
hold student’s name and variable age to hold student’s age, you just need
to write somewhat similar to what is shown below:
Student=‘Jacob’
Age=16
Dynamic Typing
• In Python, a variable is defined by assigning to it some value (of a particular type
such as numeric, string etc.). For instance, after the statement:
X=10
We can say that variable x is referring to a value of integer type.
Later in your program, if you assign a value of some other type to variable X, No
error will be raised.
e.g. X=10
print(X)
X=“Hello World”
print(X)
Above code will yield the output as:
10
Hello World
• Dynamic typing is different from Static Typing, a datatype is attached
with a variable when it is defined first and it is fixed. That is, datatype of
a variable cannot be changed in static typing whereas there is no
restriction in dynamic typing, which is supported in Python.
Multiple Assignments
• Python is very versatile with assignments.
1. Assigning same value to multiple variables: You can assign same value
to multiple variables in a single statement.
a=b=c=10
It will assign value 10 to all three variables a,b,c.
2. Assigning multiple values to multiple Variables: You can even assign
multiple values to multiple variables in single statement.
x, y, z=10, 20, 30
It will assign the values order wise i.e., It will assign 10 to x, 20 to y and
30 to z.
Simple Input and Output
• In Python, to get input from user interactively, you can use built-in
function input().
• The function input is used in the following manner:
name=input(’What is your name?’)
The input() function always returns a value of String type. Python offers
two functions int() and float() to be used with input() to convert the values
received through input() into int and float types.
Read in the value using input() function.
And then use int() or float() function with the read value to change the
type of input value to int or float respectively.
marks=float(input(”Enter marks: ”))
print(”hello”)
print(17.5)
print(3.14159*(r*r))
print(”I\’m”, 12+5, ”years old.”)
• The print statement has a number of features:
It auto-converts the items to strings i.e., if you are printing a numeric
value, it will automatically convert it into equivalent string and print it; for
numeric expressions, it first evaluates them and then converts the result
to string, before printing.
It inserts spaces between items automatically because the default value
of sep argument (separator character) is space.
Will print
My…name…is…Amit.
• It appends a newline character at the end of the line unless you give your
own end argument.