Python Variables & types, Operators, Type Conversion

A few important things about Python:

  • Python is case sensitive
  • Spacing is important in Python
  • print() is a useful building function in Python used to display results.
    • Python Comments

      Comments start with a # in Python

      Variables and Assignment Operators

      Unlike other programming languages (ex PHP, with $), Python has no command for declaring a variable. A variable is created at the moment you first assign a value to it.

      Variables don’t need to be declared with any particular type and You can change the type after they have been set.

      month = 3
      month = "march"
      print(month)
      #Result: march
      

      Assign value to Multiple Variables

      Python allows you to assign values to multiple variables in one line:

      x, y, z = 1, 2, 3

      Rules for Python variables:

      • Must start with a letter or the underscore.
      • Can use only letters, numbers, and underscores in your variable names. They can’t have spaces.
      • Can’t use reserved words or built-in identifiers
      • The pythonic way to name variables is to use all lowercase letters and underscores to separate words (ex my_age = 45).

      !!Variable names are Case Sensitive in Python

      Re-declaring a variable works

      x = 0
      print(x)
      
      x = "abc"
      print(x)
      

      Variables of different types cannot be combined

      print("this is a string " + 789)
      #TypeError: can only concatenate str (not "int") to str
      
      #instead use
      print("this is a string" + str(789))
      

      del keyword

      The del keyword is used to delete objects. Because in Python everything is an object, the del keyword can also be used to delete variables, lists, etc.

      x = "abc"
      del x
      print(x)
      
      #NameError: name 'x' is not defined
      

      Scientific notation

      In scientific notation, all numbers are written in the form: m × 10n

      7.33e2 is equal to 7.33 * 10 ** 2 which is equal to 733

      Integers and Floats

      int – for integer values
      float – for a decimal or floating-point values

      Floating points numbers are approximations!

      x = 3 = integer
      y = 4.0 – float
      y = 4. – float

      print(3/4) – 0.75 – float

      Even one integer divided by another integer exactly, the result will be float

      print(4/4) / 1.0 – float

      You can create a value that follows the data type by using the following syntax:

      x = int(4.7) # x is now an integer 4
      The part after the decimal is cut
      y = float(4) # y is now a float of 4.0

      You can check the type by using the type function:

      print(type(x))
      # int
      print(type(y))
      # float
      

      Variable assignment

      If you’ve programmed in certain other languages (like Java or C++), you might be noticing some things Python doesn’t require:

      Don’t need to “declare” a variable before assigning to it.

      Don’t need to tell Python what type of value a variable is going to refer to. In fact, we can reassign a variable to refer to a different sort of thing like a string, a float, or a boolean.

      How to swap 2 variables(a,b) between them?

      The most straightforward solution is to use a third variable to temporarily store one of the old values. e.g.:

      tmp = a
      a = b
      b = tmp

      or You can swap the two variables in one line:

      a, b = b, a

      Constants in Python

      In other programming languages we can create constant values in different ways, e.g.:

      in Java
      public static final String CONST_NAME = “Name”;

      in PHP
      define(“GREETING”, “Hello!”);

      How to declare constant in Python?

      You cannot declare a variable or value as constant in Python.

      Just don’t change it, e.g:

      CONST_NAME = “Name”

      If you are in a class, the equivalent would be:

      class myClass():
          CONST_NAME = “Name”

      Operators

      Python Arithmetic Operators

      + Addition
      Subtraction
      * Multiplication
      / Division
      % Modulus
      ** Exponentiation
      // Floor division

      Gives the result rounded down to the next integer.

      In Python, there are two kinds of division: integer division and float division.

      print(4 / 3)
      print(4 // 3)
      

      Gives the output in Python 3

      1.3333333333333333 
      1
      

      Python Logical Operators

      and Returns True if both statements are true
      or Returns True if one of the statements is true
      not Reverse the result, returns False if the result is true

      Python uses and, not and or conditionals, instead of &&, ! or ^^.

      What is the value of this expression?

      True or True and False

      The expression is evaluated as True, because and is evaluated before or.

      If we evaluated it from left to right, we would have calculated True or True first (which is True) and then taken the and of that result with False, giving a final value of False.

      PHP logical operators

      $a and $b 	And 	TRUE if both $a and $b are TRUE.
      $a or $b 	Or 	TRUE if either $a or $b is TRUE.
      $a xor $b 	Xor 	TRUE if either $a or $b is TRUE, but not both.
      ! $a 	Not 	TRUE if $a is not TRUE.
      $a && $b 	And 	TRUE if both $a and $b are TRUE.
      $a || $b 	Or 	TRUE if either $a or $b is TRUE.
      

      Python Identity Operators

      In Python Identity operators are

      is – evaluates if both sides have the same identity. Is operator is stronger than ==.

      is not – evaluates if both sides have different identities

      !Comparisons to singletons like None should always be done with ‘is’ or ‘is not’, never with the equality operators. Read more here – Style Guide for Python Code

      someobj = None
      if not someobj:
      #do something

      Examples

      a = [1, 1, 2]
      b = a
      
      print(a == b)
      # True
      
      print(a is b)
      # True
      
      4.0 == 4
      # True
      
      '4' == 4
      # False
      

      List a and list b are equal and identical.

      a = [1, 1, 2]
      b = [1, 1, 2]
      
      print(a == b)
      # True They have the same content!
      
      print(a is b)
      # False
      

      They have the same content but point to two different objects, so they aren’t identical objects.

      a = [1, 1, 2]
      b = [1, 1, 2, 4]
      
      print(a == b)
      # False They don't have the same content!
      
      print(a is b)
      # False They don't have the same content and point to different objects!
      

      In PHP identical operator is ===

      In PHP the Identical operator is the triple equal sign “===”

      This operator returns true if both variable contains same information and same data types otherwise return false.

      Why is === faster than == in PHP?

      === is faster because don’t converts the data type to see if two variables have same value

      Python Bitwise Operators

      & AND (Sets each bit to 1 if both bits are 1)
      | OR (Sets each bit to 1 if one of two bits is 1)
      ^ XOR (Sets each bit to 1 if only one of two bits is 1)
      ~ NOT (Inverts all the bits)
      << Zero fill left shift (Shift left by pushing zeros in from the right and let the leftmost bits fall off)
      >> Signed right shift (Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off)

      Divide By Zero in Python

      What happens if you divide by zero in Python?

      ZeroDivisionError: division by zero

      Python Booleans

      You can evaluate any expression in Python, and get one of two answers, True or False.

      bool() function

      The bool() function allows you to evaluate any value, and give you True or False in return

      print(bool("abc"))
      # True
      print(bool(10))
      # True
      

      # all numbers are treated as true, except 0

      # all strings are treated as true, except the empty string “”

      We can use non-boolean objects in if conditions and other places where a boolean would be expected. Python will treat them as their corresponding boolean value:

      if 0:
          print(0)
      elif "spam":
          print("xyz")
      
      # xyz
      

      None Keyword

      The None keyword is used to define a null value or no value at all.
      None is a variable, a value, that we can distinctly detect differently than numbers.

      None is not the same as 0, False, or an empty string. None is a datatype of its own (NoneType) and only None can be None.

      x = None
      print(x) 
      
      //None
      

      How do we get data from the user in Python?

      You can read data from the user using the input() function.
      The input() function returns a string!

      name = input(“What is Your name?”)

      Even if the user will tipe “123” the result will be string, not int!

      Strings

      Strings in Python are arrays of bytes representing Unicode characters.

      In Python, You can define a string with either double quotes ” or single quotes ‘.

      In Python, a string is immutable. You cannot overwrite the values of immutable objects.

      Read more here about Working with strings in Python ✅ Methods, Slicing, String Mutations ✅ Exercises, and examples

      Type & Type Conversion

      int + float = float

      print(.1 + .1 + .1 + .1 == .4)
      False

      Because the float, 0.1 is actually slightly more than 0.1.
      When we add several of them together will see the difference between the mathematically correct answer and the one that Python creates.

      print(0 + 7)
      # 7
      print("0" + "7")
      # 07
      print("0" + 7)
      # TypeError: can only concatenate str (not "int") to str
      print(0 + "7")
      TypeError: unsupported operand type(s) for +: 'int' and 'str'
      

      type() function

      The type() function returns the type of the specified object

      print(type(10))
      # <class 'int'>
      print(type("10"))
      # <class 'str'>
      print(type(10.))
      # <class 'float'>
      

      Type Conversion

      You can convert from one type to another with the int(), float(), str() and complex() methods:

      #convert from float to int:
      a = int(2.0)
      print(type(a))
      # <class 'int'>
      
      #convert from string to int:
      a = str(10)
      print(type(a))
      # <class 'str'>
      

Leave a Comment

WebPedia.net