Variables

  • Every variables holds a value, which is the information associated with that variables.

  • To hold a value you require some space in memory. This means that when you create a variable you reserve some space in memory and that memory location you give a name that is called Variables.


   Syntax:
      Variable_name = Value 

    Example:

        msg  = “Hello World”

        print(msg)


Rules for Variable Name Declaration

  

  • Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number. For instance, you can call a variable message_1 but not 1_message. 

  • Spaces are not allowed in variable names, but underscores can be used to separate words in variable names. For example, greeting_message works, but greeting message will cause errors. 

  •  Avoid using Python keywords and function names as variable names; that is, do not use words that Python has reserved for a particular programmatic purpose, such as the word print.

  • Variable names should be short but descriptive. For example, name is better than n, student_name is better than s_n, and name_length is better than length_of_persons_name. 

  • Be careful when using the lowercase letter l and the uppercase letter O because they could be confused with the numbers 1 and 0.


Try it:

1. declare a variable with a message, and print that message. Then change the value of the variable, and print the message.


Assignment Variation:
By using ‘,’ separator we can assign value to multiple variables in a single stmt.

  a = “ghgfh”

  a,b = “vvv”,”fghfg”

  A,b,c = “hjh”, 555,78.99


It is not allowed
A,b = 25


Swap Operation program:

x = 40
y = 50

Check Java program code

In python we need only single stmt
x,y = y,x



DataType

  • The data stored in variables has in different types. If you want to store student roll_number it is a numeric value and his address is stored as alphanumeric characters.

  • Using type() method we will be able to get a type of variable. 

  • By Using id(‘variable_name’) function we will able to get memory address of that variable based on that value we find that data type in mutable and immutable.


There are two type of Data Type in python

  1. ImMutable - address get change
      1.1 int
      1.2 float
      1.3 complex
      1.4 bool

  1.5 String

  1.6 Tuple


  1. Mutable - address not get change

2.1 List
2.2 Dictionary
2.3 Set

2.4  byte 

2.5 bytearray



  1. Numeric
    int – holds signed integers of non-limited length.
    long- holds long integers(exists in Python 2.x, deprecated in Python 3.x).
    float- holds floating precision numbers and it’s accurate upto 15 decimal places.
    complex- holds complex numbers.


#create a variable with int.

x=200

print( x, " is ", type(x))


#create a variable with float value.

y=123.45

print( y, " is ", type(y))


#create a variable with complex value.

z=345+8j

print( z, " is ", type(z))




  1. String

  • A string is nothing but a series of characters. 

  • Anything inside quotes is considered a string in Python, and you can use single (‘’) or double quotes (“”) around your strings like this:
        “Hello String”
          ‘Hello String’

  • This flexibility will help us to use quotes and apostrophes within our strings:
    “I love ‘Python’ ”
    ‘I said, “I love Python”’

- concatenate  String using , and +  

 # using ','(Used with all type)
    print(a,"concatenated with",b)

  #using '+' (Only using with String)
    print(a+" concated with "+b)

- Adding Whitespace to Strings with Tabs or Newlines                      
    print(“I am good at \n \tC\n\tJava\n\t.Net”) #\n used to start tying from new line and \t used to add space

-  String Function.
a = “ python is my world ”  #a is a string
    title() - where each word begins with a capital letter. (a.title())

    upper() - string to all uppercase (a.upper())

    lower() - string to all lowercase(a.lower())

    strip() - remove whitespaces(a.trip())

    lstrip() - strip whitespace from the left side of a string (a.lstrip())

    rstrip() - strip whitespace from the right side of a string(a.rstrip())

    str() -    convert the numerical value to string(str())


Try it: Create new file for this excersise

  1. Store your name in a variable, and print a msg. Your msg should like “Hello “Your_Name”, would you like to learn some Python today?”

  2. Store your name in a variable, and then print that per- son’s name in lowercase, uppercase, and titlecase

  3. Find a good quote of a person you like. Your output should look like below including the quotation marks:
                      person_Name once said, “person_quote ”

  4. Store your name in a variable and include some whitespace using "\t" and "\n", at least once .  print output using strip(),lstrip(),rstrip() functions

  5. Store your age in a integer variable and print message like below
      “I am 24 years old”


3. List

  • The list is a versatile data type exclusive in Python.

  • it can simultaneously hold different types of data.

  •  list is an ordered sequence of some data written using square brackets([]) and commas(,)

  • List index starts from 0.

#list of having only integers
a= [1,2,3,4,5,6]
print(a)

#list of having only strings
b=["hello","john","reese"]
print(b)

#list of having both integers and strings
c= ["hey","you",1,2,3,"go"]
print(c)

#index are 0 based. this will print a single character
print(c[1]) #this will print "you" in list c

4. Tuple

  • Tuple is a sequence of data similar to list. But it is immutable.

  • Data in a tuple is written using parentheses and commas.

  • List index starts from 0.

#tuple having only integer type of data.
a=(1,2,3,4)
print(a) #prints the whole tuple

#tuple having multiple type of data.
b=("hello", 1,2,3,"go")
print(b) #prints the whole tuple



#index of tuples are also 0 based.
print(b[4]) #this prints a single element in a tuple, in this case "go"

5. Dictionary

  • Python Dictionary is an unordered sequence of data of key-value pair form.

  • Dictionaries are written within curly braces in the form key:value

  • Key and value can be any kind of type.

  • It is very useful to retrieve data in an optimized way among a large amount of data.

#a sample dictionary variable
a = {1:"first name",2:"last name", "age":33}

#print value having key=1
print(a[1])

#print value having key=2
print(a[2])

#print value having key="age"
print(a["age"])

6. Set 

  • Set is an unordered collection.

  • Doesn’t allow duplicates elements.(At the time of print it will remove duplicates elements)

  • used for mathematical operations like union, intersection, difference and complement etc.

Declaration of the set (Empty set)

Name_of_set =  {()}  OR Name_of_set = set()

  #empty set
   aset = {()}  OR aset = set()
  aset = {3.4,11,22,3.4,(3,4,5)}
  print(aset)  #{3.4,11,22,(3,4,5)
  aset.update({89}) OR aset.add({89})

Frozen Set:

  • Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned


# Frozensets
# initialize
a = frozenset([1, 2, 3, 4])  #When try to update we will get error AttributeError: 'frozenset' object has no attribute 'update'

Categories: Python Tags: #Python,

Comments