Skip to content

Instantly share code, notes, and snippets.

@amelieykw
Last active July 15, 2018 16:05
Show Gist options
  • Save amelieykw/945996029bc6dd369435b20aa378ae4d to your computer and use it in GitHub Desktop.
Save amelieykw/945996029bc6dd369435b20aa378ae4d to your computer and use it in GitHub Desktop.
[Python Tutorial] #Python

Welcome to this lesson on Data Types and Operators! You'll learn about:

  • Data Types: Integers, Floats, Booleans, Strings, Lists, Tuples, Sets, Dictionaries
  • Operators: Arithmetic, Assignment, Comparison, Logical, Membership, Identity
  • Built-In Functions, Compound Data Structures, Type Conversion
  • Whitespace and Style Guidelines

Type Conversion in Python

Python defines type conversion functions to directly convert one data type to another.

  1. int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base in which string is if data type is string.

  2. float() : This function is used to convert any data type to a floating point number

# Python code to demonstrate Type conversion
# using int(), float()
 
# initializing string
s = "10010"
 
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
 
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:

After converting to integer base 2 : 18
After converting to float : 10010.0
  1. ord() : This function is used to convert a character to integer.

  2. hex() : This function is to convert integer to hexadecimal string.

  3. oct() : This function is to convert integer to octal string.

# Python code to demonstrate Type conversion
# using  ord(), hex(), oct()
 
# initializing integer
s = '4'
 
# printing character converting to integer
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)
 
# printing integer converting to hexadecimal string
c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c)
 
# printing integer converting to octal string
c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)

Output:

After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
  1. tuple() : This function is used to convert to a tuple.

  2. set() : This function returns the type after converting to set.

  3. list() : This function is used to convert any data type to a list type.

# Python code to demonstrate Type conversion
# using  tuple(), set(), list()
 
# initializing string
s = 'geeks'
 
# printing string converting to tuple
c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)
 
# printing string converting to set
c = set(s)
print ("After converting string to set : ",end="")
print (c)
 
# printing string converting to list
c = list(s)
print ("After converting string to list : ",end="")

Output:

After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
  1. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.

  2. str() : Used to convert integer into a string.

  3. complex(real,imag) : : This function converts real numbers to complex(real,imag) number.

# Python code to demonstrate Type conversion
# using  dict(), complex(), str()
 
# initializing integers
a = 1
b = 2
 
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
 
# printing integer converting to complex number
c = complex(1,2)
print ("After converting integer to complex number : ",end="")
print (c)
 
# printing integer converting to string
c = str(a)
print ("After converting integer to string : ",end="")
print (c)
 
# printing tuple converting to expression dictionary
c = dict(tup)
print ("After converting tuple to dictionary : ",end="")
print (c)

Output:

After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Arithmetic Operators

+ Addition
- Subtraction
* Multiplication
/ Division
% Mod (the remainder after dividing)
** Exponentiation (note that ^ does not do this operation, as you might have seen in other languages)
// Divides and rounds down to the nearest integer

Assignment Operators

= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x = x | 3
&= x &= 3 x = x & 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators

== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators

and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Identity Operators

is Returns true if both variables are the same object x is y
is not Returns false if both variables are the same object x is not y

Membership Operators

in Returns True if a sequence with the specified value is present in the object x in y
not in Returns False if a sequence with the specified value is present in the object x not in y

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

Creating Variables

Unlike other programming languages, Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

x = 3
y = 4
z = 5

and

x, y, z = 3, 4, 5

Variable Names (case-sensitive)

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)

The pythonic way to name variables is to use all lowercase letters and underscores to separate words.

YES

my_height = 58
my_lat = 40
my_long = 105

NO

my height = 58
MYLONG = 40
MyLat = 105

Output Variables

x = "awesome"
print("Python is " + x)

If you try to combine a string and a number, Python will give you an error:

x = 5
y = "John"
print(x + y)

Global and Local Variables in Python

Global variables are the one that are defined and declared outside a function and we need to use them inside a function.

# This function uses global variable s
def f(): 
    print s 
 
# Global scope
s = "I love Geeksforgeeks"
f()

Output:

I love Geeksforgeeks

If a variable with same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value.

# This function has a variable with
# name same as s.
def f(): 
    s = "Me too."
    print s 
 
# Global scope
s = "I love Geeksforgeeks"
f()
print s

Output:

Me too.
I love Geeksforgeeks.

The question is, what will happen, if we change the value of s inside of the function f()? Will it affect the global s as well? We test it in the following piece of code:

def f(): 
    print s
 
    # This program will NOT show error
    # if we comment below line. 
    s = "Me too."
 
    print s
 
# Global scope
s = "I love Geeksforgeeks"
f()
print s

Output:

Line 2: undefined: Error: local variable 's' referenced before assignment

“global” keyword

To make the above program work, we need to use “global” keyword.

We only need to use global keyword in a function if we want to do assignments / change them. global is not needed for printing and accessing.

Why? Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message.

Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable.

To tell Python, that we want to use the global variable, we have to use the keyword “global”, as can be seen in the following example:

# This function modifies global variable 's'
def f():
    global s
    print s
    s = "Look for Geeksforgeeks Python Section"
    print s 
 
# Global Scope
s = "Python is great!"
f()
print s

Now there is no ambiguity. Output:

Python is great!
Look for Geeksforgeeks Python Section.
Look for Geeksforgeeks Python Section.

A good Example

a = 1
 
# Uses global because there is no local 'a'
def f():
    print 'Inside f() : ', a
 
# Variable 'a' is redefined as a local
def g():    
    a = 2
    print 'Inside g() : ',a
 
# Uses global keyword to modify global 'a'
def h():    
    global a
    a = 3
    print 'Inside h() : ',a
 
# Global scope
print 'global : ',a
f()
print 'global : ',a
g()
print 'global : ',a
h()
print 'global : ',a

Output:

global :  1
Inside f() :  1
global :  1
Inside g() :  2
global :  1
Inside h() :  3
global :  3
  • int
    • Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
      • z = -3255522
  • float
    • Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
      • z = -35.59
    • Float can also be scientific numbers with an "e" to indicate the power of 10.
      • x = 35e3
      • y = 12E4
      • z = -87.7e100
  • complex
    • Complex numbers are written with a "j" as the imaginary part
    • x = 3+5j
>>> print(type(x))
int
>>> print(type(y))
float

Casting

x = int(4.7)   # x is now an integer 4
y = float(4)   # y is now a float of 4.0
  • int()
    • constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number) literal, or a string literal (providing the string represents a whole number)
  • float()
    • constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
  • str()
    • constructs a string from a wide variety of data types, including strings, integer literals and float literals
x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
x = float(1)     # x will be 1.0
y = float(2.8)   # y will be 2.8
z = float("3")   # z will be 3.0
w = float("4.2") # w will be 4.2
x = str("s1") # x will be 's1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'

String Literals

Strings in Python are shown as the variable type str.

String literals in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".

You can also include a \ in your string to be able to include one of these quotes:

this_string = 'Simon\'s skateboard is in the garage.'
print(this_string)

Strings can be output to screen using the print function. For example: print("hello").

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

a = "hello"
print(a[1])
b = "world"
print(b[2:5])
>>> first_word = 'Hello'
>>> second_word = 'There'
>>> print(first_word + second_word)

HelloThere

>>> print(first_word + ' ' + second_word)

Hello There

>>> print(first_word * 5)

HelloHelloHelloHelloHello

>>> print(len(first_word))

5

strip()

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

len()

The len() method returns the length of a string:

a = "Hello, World!"
print(len(a))

upper()

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

replace()

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

split()

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

All the methods

>>> my_string.islower()
True
>>> my_string.count('a')
2
>>> my_string.find('a')
3

One important string method: format()

We will be using the format() string method a good bit in our future work in Python, and you will find it very valuable in your coding, especially with your print statements.

We can best illustrate how to use format() by looking at some examples:

# Example 1
print("Mohammed has {} balloons".format(27))

Mohammed has 27 balloons

# Example 2
animal = "dog"
action = "bite"
print("Does your {} {}?".format(animal, action))

Does your dog bite?

# Example 3
maria_string = "Maria loves {} and {}"
print(maria_string.format("math","statistics"))

Maria loves math and statistics

Command-line String Input input()

print("Enter your name:")
x = input()
print("Hello, " + x)
C:\Users\Your Name>python demo_string_input.py

Our program will prompt the user for a string

Enter your name:

The user now enters a name:

Linus

Then, the program prints it to screen with a little message:

Hello, Linus
Collection ordered? changeable? indexed? allow duplicate members? mix and match of the data types
List Yes Yes Yes Yes Yes
Tuple Yes No Yes Yes
Set No Yes No No
Dictionary No Yes Yes No

List

Lists can contain any mix and match of the data types you have seen so far.

list_of_random_things = [1, 3.4, 'a string', True]

Create a List:

thislist = ["apple", "banana", "cherry"]
print(thislist)

Change the second item:

thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

The list() Constructor

  • It is also possible to use the list() constructor to make a list.
  • To add an item to the list use append() object method.
  • To remove a specific item use the remove() object method.
  • The len() function returns the length of the list.

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

Using the append() method to append an item:

thislist = list(("apple", "banana", "cherry"))
thislist.append("damson")
print(thislist)

Using the remove() method to remove an item:

thislist = list(("apple", "banana", "cherry"))
thislist.remove("banana")
print(thislist)

The len() method returns the number of items in a list:

thislist = list(("apple", "banana", "cherry"))
print(len(thislist))

Slice and Dice with Lists

You saw that we can pull more than one value from a list at a time by using slicing. When using slicing, it is important to remember that the lower index is inclusive and the upper index is exclusive.

>>> list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[1:2]
[3.4]

Are you in OR not in?

You saw that we can also use in and not in to return a bool of whether an element exists within our list, or if one string is a substring of another.

>>> 'this' in 'this is a string'
True
>>> 'in' in 'this is a string'
True
>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True
>>> 5 in [1, 2, 3, 4, 6]
False

join method

Join is a string method that takes a list of strings as an argument, and returns a string consisting of the list elements joined by a separator string.

new_str = "\n".join(["fore", "aft", "starboard", "port"])
print(new_str)

Output:

fore
aft
starboard
port

In this example we use the string "\n" as the separator so that there is a newline between each element. We can also use other strings as separators with .join. Here we use a hyphen.

name = "-".join(["García", "O'Kelly"])
print(name)

Output:

García-O'Kelly

It is important to remember to separate each of the items in the list you are joining with a comma (,). Forgetting to do so will not trigger an error, but will also give you unexpected results.

List Methods

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
max() returns the greatest element of the list. How the greatest element is determined depends on what type objects are in the list. The maximum element in a list of numbers is the largest number. The maximum elements in a list of strings is element that would occur last if the list were sorted alphabetically. This works because the the max function is defined in terms of the greater than comparison operator. The max function is undefined for lists that contain elements from different, incomparable types.
min() returns the smallest element in a list. min is the opposite of max, which returns the largest element in a list.

Mutability and Order

Mutability is about whether or not we can change an object once it has been created. If an object (like a list or string) can be changed (like a list can), then it is called mutable. However, if an object cannot be changed with creating a completely new object (like strings), then the object is considered immutable.

>>> my_lst = [1, 2, 3, 4, 5]
>>> my_lst[0] = 'one'
>>> print(my_lst)
['one', 2, 3, 4, 5]

There are two things to keep in mind for each of the data types you are using:

  • Are they mutable?
  • Are they ordered?

Both strings and lists are ordered. However, you will see some data types in the next sections that will be unordered. For each of the upcoming data structures you see, it is useful to understand how you index, are they mutable, and are they ordered. Knowing this about the data structure is really useful!

A tuple is a collection which is ordered and unchangeable.

They are often used to store related pieces of information.

location = (13.4125, 103.866667)
print("Latitude:", location[0])
print("Longitude:", location[1])

In Python tuples are written with round brackets.

Tuples are similar to lists :

  • they store an ordered collection of objects which can be accessed by their indices.

Unlike lists :

  • tuples are immutable - you can't add and remove items from tuples, or sort them in place.

Create a Tuple:

thistuple = ("apple", "banana", "cherry")
print(thistuple)

Return the item in position 1:

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

You cannot change values in a tuple:

thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant" # test changeability
print(thistuple)

The tuple() Constructor

  • It is also possible to use the tuple() constructor to make a tuple.
  • The len() function returns the length of the tuple.

Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

The len() method returns the number of items in a tuple:

thistuple = tuple(("apple", "banana", "cherry"))
print(len(thistuple))

Tuples can also be used to assign multiple variables in a compact way.

dimensions = 52, 40, 100
length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))

=

length, width, height = 52, 40, 100
print("The dimensions are {} x {} x {}".format(length, width, height))

Quiz

tuple_a = 1, 2
tuple_b = (1, 2)

print(tuple_a == tuple_b)
print(tuple_a[1])

True, 2

A set is a collection which is unordered and unindexed.

In Python sets are written with curly brackets.

Create a Set:

thisset = {"apple", "banana", "cherry"}
print(thisset)

Note: the set list is unordered, so the items will appear in a random order.

The set() Constructor

set() constructor to make a set
add() add an item
remove() remove an item from the set
len() returns the size of the set

Set()

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

add()

thisset = set(("apple", "banana", "cherry"))
thisset.add("damson")
print(thisset)

remove()

thisset = set(("apple", "banana", "cherry"))
thisset.remove("banana")
print(thisset)

len()

thisset = set(("apple", "banana", "cherry"))
print(len(thisset))

Sets support the in operator the same as lists do. You can add elements to sets using the add method, and remove elements using the pop method, similar to lists. Although, when you pop an element from a set, a random element is removed. Remember that sets, unlike lists, are unordered so there is no "last element".

fruit = {"apple", "banana", "orange", "grapefruit"}  # define a set

print("watermelon" in fruit)  # check for element

fruit.add("watermelon")  # add an element
print(fruit)

print(fruit.pop())  # remove a random element
print(fruit)

This outputs:

False
{'grapefruit', 'orange', 'watermelon', 'banana', 'apple'}
grapefruit
{'orange', 'watermelon', 'banana', 'apple'}

Other operations you can perform with sets include those of mathematical sets: Methods like union, intersection, and difference are easy to perform with sets, and are much faster than such operators with other containers.

Quiz

a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
b = set(a)
print(len(a) - len(b))

Output: 6

A dictionary is a collection which is unordered, changeable and indexed.

In Python dictionaries are written with curly brackets, and they have keys and values.

Create and print a dictionary:

thisdict =	{
  "apple": "green",
  "banana": "yellow",
  "cherry": "red"
}
print(thisdict)

Change the apple color to "red":

thisdict =	{
  "apple": "green",
  "banana": "yellow",
  "cherry": "red"
}
thisdict["apple"] = "red"
print(thisdict)

The dict() Constructor

It is also possible to use the dict() constructor to make a dictionary:

thisdict =	dict(apple="green", banana="yellow", cherry="red")
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)

Output:

C:\Users\My Name>python demo_dictionary_dict.py
{'apple': 'green', 'banana': 'yellow', 'cherry': 'red'}

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

thisdict =	dict(apple="green", banana="yellow", cherry="red")
thisdict["damson"] = "purple"
print(thisdict)

Removing Items del()

Removing a dictionary item must be done using the del() function in python:

thisdict =	dict(apple="green", banana="yellow", cherry="red")
del(thisdict["banana"])
print(thisdict)

Get the Length of a Dictionary len()

The len() function returns the size of the dictionary:

thisdict =	dict(apple="green", banana="yellow", cherry="red")
print(len(thisdict))

We can check whether a value is in a dictionary the same way we check whether a value is in a list or set with the in keyword.

Dicts have a related method that's also useful, get. get looks up values in a dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn't found.

print("carbon" in elements)
print(elements.get("dilithium"))

This would output:

True
None

Carbon is in the dictionary, so True is printed. Dilithium isn’t in our dictionary so None is returned by get and then printed. If you expect lookups to sometimes fail, get might be a better tool than normal square bracket lookups because errors can crash your program.

Identity Operators

Keyword Operator
is evaluates if both sides have the same identity
is not evaluates if both sides have different identities
  • You can check if a key returned None with the is operator.
  • You can check for the opposite using is not.
n = elements.get("dilithium")
print(n is None)
print(n is not None)

This would output:

True
False

Quiz

Q1 : Which of these could be used as the key for a dictionary? (Choose all that apply.) Hint: Dictionary keys must be immutable, that is, they must be of a type that is not modifiable.

str / int / float - YES; List - NO

Q2 : What happens if we look up a value that isn't in the dictionary? Create a test dictionary and use the square brackets to look up a value that you haven't defined. What happens?

A keyError occurs

Checking for Equality vs. Identity: == vs. is

Q3 : What will the output of the following code be? (Treat the comma in the multiple choice answer as a newline.)

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a == b) - True
print(a is b) - True
print(a == c) - True
print(a is c) - False

There is a playground workspace further down this page that you can use to try it out.

get with a Default Value

Dictionaries have a related method that's also useful, get().

get() looks up values in a dictionary, but unlike looking up values with square brackets, get() returns None (or a default value of your choice) if the key isn't found.

If you expect lookups to sometimes fail, get() might be a better tool than normal square bracket lookups.

>>> elements.get('dilithium')
None
>>> elements['dilithium']
KeyError: 'dilithium'
>>> elements.get('kryptonite', 'There\'s no such element!')
"There's no such element!"

In the last example we specified a default value (the string 'There's no such element!') to be returned instead of None when the key is not found.

Context

Use the dictionary below to answer ALL of the questions regarding dictionaries. Consider you have a dictionary named animals that looks like this:

animals = {'dogs': [20, 10, 15, 8, 32, 15], 'cats': [3,4,2,8,2,4], 'rabbits': [2, 3, 3], 'fish': [0.3, 0.5, 0.8, 0.3, 1]}
DESCRIPTION VALUE
The data type of the keys in the dictionary. string
The data type of the values in the dictionary. list
The result of animals['dogs']. [20, 10, 15, 8, 32, 15]
The result of animals['dogs'][3]. 8
The result of animals[3] Error
The result of animals['fish'] [0.3, 0.5, 0.8, 0.3, 1]

We can include containers in other containers to create compound data structures. For example, this dictionary maps keys to values that are also dictionaries!

elements = {"hydrogen": {"number": 1,
                         "weight": 1.00794,
                         "symbol": "H"},
              "helium": {"number": 2,
                         "weight": 4.002602,
                         "symbol": "He"}}

We can access elements in this nested dictionary like this.

helium = elements["helium"]  # get the helium dictionary
hydrogen_weight = elements["hydrogen"]["weight"]  # get hydrogen's weight

You can also add a new key to the element dictionary.

oxygen = {"number":8,"weight":15.999,"symbol":"O"}  # create a new oxygen dictionary 
elements["oxygen"] = oxygen  # assign 'oxygen' as a key to the elements dictionary
print('elements = ', elements)

Output is:

elements =  {"hydrogen": {"number": 1,
                          "weight": 1.00794,
                          "symbol": 'H'},
               "helium": {"number": 2,
                          "weight": 4.002602,
                          "symbol": "He"}, 
               "oxygen": {"number": 8, 
                          "weight": 15.999, 
                          "symbol": "O"}}

Conditions and If statements

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

Indentation (white space)

a = 33
b = 200
if b > a:
  print("b is greater than a")

ERROR:

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif ("if the previous conditions were not true, then do this condition".)

a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

Else (catches anything which isn't caught by the preceding conditions.)

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

Boolean Expression for Conditions

Complex Boolean Expressions

If statements may contain multiple comparisons operators, logical operators, and even calculations.

if 18.5 <= weight / height**2 < 25:
    print("BMI is considered 'normal'")

if is_raining and is_sunny:
    print("Is there a rainbow?")

if (not unsubscribed) and (location == "USA" or location == "CAN"):
    print("send email")

For really complicated conditions you might need to combine some ands, ors and nots together. Use parentheses if you need to make the combinations clear.

Here are most of the built-in objects that are considered False in Python:

  • constants defined to be false: None and False
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '"", (), [], {}, set(), range(0)

Example:

errors = 3
if errors:
    print("You have {} errors to fix!".format(errors))
else:
    print("No errors to fix!")

In this code, errors has the truth value True because it's a non-zero number, so the error message is printed. This is a nice, succinct way of writing an if statement.

While Loop

Syntax :

while expression:
    statement(s)

In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.

# prints Hello Geek 3 Times
count = 0
while (count < 3):    
    count = count+1
    print("Hello Geek")

Output:

Hello Geek
Hello Geek
Hello Geek

As mentioned in the article, it is not recommended to use while loop for iterators in python.

For in Loop

In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages.

Syntax:

for iterator_var in sequence:
    statements(s)

It can be used to iterate over iterators and a range.

# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
    print(i)
      
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
    print(i)
      
# Iterating over a String
print("\nString Iteration")    
s = "Geeks"
for i in s :
    print(i)
      
# Iterating over dictionary
print("\nDictionary Iteration")   
d = dict() 
d['xyz'] = 123
d['abc'] = 345
for i in d :
    print("%s  %d" %(i, d[i]))

Output:

List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz  123
abc  345

Nested Loops

Syntax:

for iterator_var in sequence:
    for iterator_var in sequence:
        statements(s)
        statements(s)

The syntax for a nested while loop statement in Python programming language is as follows:

while expression:
    while expression: 
        statement(s)
        statement(s)

A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa.

from __future__ import print_function
for i in range(1, 5):
    for j in range(i):
         print(i, end=' ')
    print()

Output:

1
2 2
3 3 3
4 4 4 4

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.

Continue Statement

It returns the control to the beginning of the loop.

# Prints all letters except 'e' and 's'
for letter in 'geeksforgeeks': 
    if letter == 'e' or letter == 's':
         continue
    print 'Current Letter :', letter
    var = 10

Output:

Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Break Statement

It brings control out of the loop

for letter in 'geeksforgeeks': 
 
    # break the loop as soon it sees 'e' 
    # or 's'
    if letter == 'e' or letter == 's':
         break
 
print 'Current Letter :', letter

Output:

Current Letter : e

Pass Statement

We use pass statement to write empty loops.

Pass is also used for empty control statement, function and classes.

# An empty loop
for letter in 'geeksforgeeks':
    pass
print 'Last Letter :', letter

Output:

Last Letter : s

A function = a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Create a Function - def

def my_function():
  print("Hello from a function")

Calling a Function

def my_function():
  print("Hello from a function")

my_function()

Parameters

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Default Parameter Value

If we call the function without parameter, it uses the default value:

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Return Values - return

def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Partial functions allow us to fix a certain number of arguments of a function and generate a new function.

Example:

from functools import partial
 
# A normal function
def f(a, b, c, x):
    return 1000*a + 100*b + 10*c + x
 
# A partial function that calls f with
# a as 3, b as 1 and c as 4.
g = partial(f, 3, 1, 4)
 
# Calling g()
print(g(5))

Output:

3145

In the example, we have pre-filled our function with some constant values of a, b and c. And g() just takes a single argument i.e. the variable x.

Another Example :

from functools import *
 
# A normal function
def add(a, b, c):
   return 100*a + 10*b  + c
 
# A partial function with b = 1 and c = 2
add_part = partial(add, c=2, b=1)
 
# Calling partial function
print(add_part(3))

Output:

312

Partial functions can be used to derive specialized functions from general functions and therefore help us to reuse our code.

the keyword lambda is used to create what is known as anonymous functions.

These are essentially functions with no pre-defined name.

They are good for constructing adaptable functions, and thus good for event handling.

An anonymous function that returns the double value of i:

myfunc = lambda i: i*2
print(myfunc(2))

Lambda defined functions can have more than one defined input, as shown here:

myfunc = lambda x,y: x*y
print(myfunc(3,6))

The power of lambda is better shown when you generate anonymous functions at run-time, as shown in the following example.

The power of lambda is better shown when you generate anonymous functions at run-time

def myfunc(n):
  return lambda i: i*n

doubler = myfunc(2)
tripler = myfunc(3)
val = 11
print("Doubled: " + str(doubler(val)) + ". Tripled: " + str(tripler(val)))

Here we see the defined function, myfunc, which creates an anonymous function that multiplies variable i with variable n.

We then create two variables doubler and tripler, which are assigned to the result of myfunc passing in 2 and 3 respectively. They are assigned to the generated lambda functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment