Você está na página 1de 9

Islamic University Of Gaza

Faculty of Engineering
Computer Engineering Department

Lab 2

Variable and Data Type I

Eng. Ibraheem Lubbad

September 24, 2016


Variable is reserved a location in memory to store values, based on the data type of a variable,
the interpreter allocates memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store integers, decimals, or
characters in these variables.

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.

Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously. For
example:

Example 1:
a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location.
You can also assign multiple values to multiple variables. For example:

Example 2:
a, b, c = 1, 2, "IUG"

Identifiers are the names that identify the elements such as classes, methods, and
variables in a program, all identifiers must obey the following rules:

 Identifiers must contain at least one character.


 The first character must be an alphabetic letter (upper or lower case) or the
underscore (_)
 The remaining characters (if any) may be alphabetic characters (upper or lower case),
the underscore, or a digit
 No other characters (including spaces) are permitted in identifiers.
 A reserved word (Python Keywords) cannot be used as an identifier.
and del from None try
as elif global nonlocal True
assert else if not while
break except import or with
class False in pass yield
continue finally is raise
def for lambda return
Python keywords
Standard Data Types:
Python has various standard data types that are used to define the operations possible on them
and the storage method for each of them.

Python has 5 standard data types:


 Numbers
 String
 List
 Tuple
 Dictionary

*In this lab we will take just about Numbers and String

Python Numbers:
Number data types store numeric values. Number objects are created when you
assign a value to them. For example:

Example 3
var1 = 10
var2 = 1.5
var3 = 2.5-1j
Python supports four different numerical types:
 int (signed integers)
 long (long integers)
 float (floating point real values)
 complex (complex numbers)

int long float complex


10 51924361L 15.20 3.14j
-786 0xDEFABCECBDAECBFBAEl 32.3+e18 4.53e-7j

 Python displays long integers with a lowercase l or an uppercase L.


 A complex number consists of an ordered pair of real floating-point numbers
denoted by x + yj, where x is the real part and b is the imaginary part of the
complex number.
Python Arithmetic Operators:
Assume variable a holds 2 and variable b holds 5, then:

Operator Example

+ Addition a+b=7
- Subtraction a – b = -3
* Multiplication a * b = 10
/ Division b/a=2
% Modulus b%a=1
** Exponent a**b =32
// Floor Division 9//2 = 4 and 9.0//2.0 = 4.0 but

9/2 = 4 and 9.0/2.0 = 4.5

Python Assignment Operators:


Operator Example

= Assign c = a + b assigns value of a + b into c


+= Add AND Assign c += a is equivalent to c = c + a
-= Subtract AND Assign c -= a is equivalent to c = c - a
*= Multiply AND Assign c *= a is equivalent to c = c * a
/= Divide AND Assign c /= a is equivalent to c = c / a
%= Modulus AND Assign c %= a is equivalent to c = c % a
**= Exponent AND Assign c **= a is equivalent to c = c ** a
//= Floor Division Assign c //= a is equivalent to c = c // a
Example 4:
Example 4: Assignment_Operators.py
a=2
b=3
c=0
print "a=",a ," b=",b, " c=" , c
c = a + b
print "c = a + b , Value of c is " , c

c += a
print "c += a , Value of c is " , c

c *= a
print "c *= a , Value of c is " , c

c /= a
print "c /= a , Value of c is " , c

c = 3
c %= a
print "c = 3,c %= a , Value of c is " , c

c **= a
print "c **= a , Value of c is " , c

c //= a
print "c //= a , Value of c is " , c

Output of Example 4 (Assignment_Operators.py):

) shows:

Comments: text contained within comments is ignored by the Python interpreter.


The # symbol begins comment in the source code. The comment is in effect until the end of the
line of code:
Python Strings:
 Strings in Python are identified as a contiguous set of characters represented in the
quotation marks either pairs of single or double quotes.
 Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting
at 0 in the beginning of the string and working their way from -1 at the end
So ([-1] represent last index).
 The plus (+) sign is the string concatenation operator.
 The asterisk (*) is the repetition operator. For example:

Example 5: String_Python.py
str = 'Python Lab '
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2: 5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "Exam" # Prints concatenated string
print "length str ",len(str)

Output of Example 5 (String_Python.py):

Conversion functions:
int() : convert string containing an integer number to an integer
float() :convert string containing a floating point number to a floating point number

a = "34" a = "3.4"
print "data type a ",type(a) print "data type a ",type(a)
x = int (a) x = float (a)
print "data type x ",type(x) print "data type x ",type(x)

Output:
User Input:
The print function enables a Python program to display textual information to the user.
Programs may use the input function to obtain information from the user.

For example: input function assign entered value to x

x = input ()

Examples:

Example 6: usinginput.py
x = input ("Please enter your name: ")
print "Text entered: ", x
print " Type: " , type(x)

Output of Example 6 (String_Python.py):

Example 7: usinginput.py
x = input ("Please enter an integer value: ")
y = input("Please enter an integer value: ")

print x, ' +' , y, ' =' , x + y

Output of Example 7 (usinginput.py):


Work lab:

Write program that converts a Fahrenheit degree to Celsius using the formula

5
𝐶𝑒𝑙𝑠𝑖𝑢𝑠 = (𝑓𝑎ℎ𝑟𝑒𝑛ℎ𝑒𝑖𝑡 − 32)
9

Example 8: Convert Fahrenheit into Celsius


fahrenheit= input("Enter a degree in Fahrenheit:")

Celsius=(5.0/9)*(fahrenheit-32)

print "Fahrenheit" , fahrenheit , " is " , Celsius, " in Celsius"

Output of Example 8:
Exercises:

1) What happens if you attempt to use a variable within a program, and that variable has
not been assigned a value?

2) Classify each of the following as either a legal or illegal Python identifier:


a) Salim
b) If
c) 2x
d) -4
e) sum_total
f) sumTotal
g) sum-total
h) sum total
i) public
j) $16
k) _4
l) ___
m) a27834
n) wilma’s

3) Write an application to convert centimeters (input) to feet and inches (output).

1 inch= 2.54 cm
1 foot =30.48 cm

4) Write a Python program that split up a given number of seconds to hours, minutes, and
seconds

For example:
If the user enters 10000 seconds, the program prints 2 hr, 46 min, 40 sec.

Você também pode gostar