1. Variables - Learn to conveniently store data in your Python programs!
2. Numbers - Learn how numbers work behind the scenes in your Python programs!
3. Strings - Master the written word and automate messages using text!
4. Logic and Data Structures - Teach your Python programs to think and decide!
5. Loops - Save time and effort, by making computers do the hard work for you!
6. Functions - Automate Tasks by Creating your very own Python Functions that you can use over and over!
7. OOP - Add Python to Your Resumé By Mastering Object-Oriented Programming, an industry-standard programming technique!
5. What is variable?
● Variables are containers for storing data values.
● 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.
● Python is dynamically type language.
● We can use type(variable name) to know the datatype of the variable.
● We can change the variable type in python.
● Example: number = 5
● 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 alphanumeric characters and underscores
(A-z, 0-9, and _ ).
7. Basic arithmetic, floats and modulo
Operators:
● Operators are used to perform operations on variables and values.
● Basic arithmetic operator:
○ + Addition x + y
○ - Subtraction x - y
○ * Multiplication x * y
○ / Division x / y
○ % Modulus x % y
● Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
● Ex: 10.4
8. ● Ordering Operations:
○ Python follow BODMAS rule
○ This was implemented in python 3
○ Ex: 2 * 5 - 1 = 9
● Python random module:
○ Ex:
Import random
health = 50
health_portion = random.randint(10,20)
Health = health + health_portion
9. Python Math module
● This module in python is used for mathematical tasks.
● Import math - this will import the math module
● math.floor(2.4) = 2 - this will round the number to the lower value.
● math.ceil(2.4) = 3 - this will round the number to the highest value.
● math.hypot(3,4) = 25 - this will calculate the hypotenuse.
● math.pow(2,3) = 8 - this is similar to 2 ^ 3.
● math.cos(0) = 1 - trigonometry calculations
11. String literals
● String literals in python are surrounded by either single quotation marks, or
double quotation marks.
● Example:
○ ‘Hello’
○ “Hello”
● Multi line strings - We can use three double or single quotes.
● Example:
○ a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
12. ● We use input() to collect data.
● Example:
○ name = input(“Enter name: ”)
○ Look same in idle.
13. String methods
● Count() - it is used to count the number of times the character or substring
appears in a string.
○ Example: “hello”.count(“h”)
○ Output: 1
● lower() - It is used to convert all the uppercase characters to lowercase in a
string.
○ Example: “Hello”.lower()
○ Output: hello
● upper() - It is used to convert all the lowercase characters to uppercase in a
string.
○ Example: “hello”.upper()
○ Output: HELLO
14. String methods
● capitalize() - it is used to capitalize the first character in a string.
○ Example: “hello world”.capitalize()
○ Output: Hello world
● title() - It is used to capitalize the first letter of each word in a string.
○ Example: “hello world”.title()
○ Output: Hello World
● isupper() - This returns true if all the characters in the string are in upper
case
○ Example: “hello”.isupper()
○ Output: False
15. String methods
● istitle() - Returns True if the string follows the rules of a title.
● isalpha() - Returns True if all characters in the string are in the alphabet
● isdigits() - Returns True if all characters in the string are digits
● isalnum() - Returns True if all characters in the string are alphanumeric
● index() - Searches the string for a specified value and returns the position of
where it was found.
○ Ex: x.index(“day”)
○ It throws value error if the string passed is not found.
● find() - Searches the string for a specified value and returns the position of
where it was found.
○ Ex: x.find(“day”)
○ It returns -1 if the string passed is not found.
16. String methods
● strip() - The strip() method removes any whitespace from the beginning or
the end.
○ a = " Hello, World! "
○ print(a.strip()) # returns "Hello, World!"
○ We can pass parameter to strip the given character.
17. String Slicing
● You can return a range of characters by using the slice syntax.
● Specify the start index and the end index, separated by a colon, to return a
part of the string.
● Syntax:
○ Word[start : end : step]
● Example:
○ b = "Hello, World!"
○ print(b[2:5]) #llo
● We can use b[: :-1] to revere the string.
● We can use -ve indexing to start from the end o the string.
18. Email Slicer - Program
#get user email
email = input("Enter email address: ").strip()
#Slice out user name
user_name = email[:email.find('@')]
#slice out domain name
domain_name = email[(email.find('@')+1):]
#format message
output = "your username is {} and your domain name is {}".format(user_name,domain_name)
#print output
print(output)
20. Booleans and Comparison Operators
● Booleans
○ Booleans represent one of two values: True or False.
○ When you compare two values, the expression is evaluated and Python
returns the Boolean answer.
○ Example:
■ print(10 > 9) # True
■ print(10 == 9) # False
■ print(10 < 9) # False
● Operators
○ Comparison operators are used to compare two values
21. Booleans and Comparison Operators
Operator Name
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
22. If Statements
● If statements allow us to execute a certain piece of code only if a condition is
true.
● Syntax:
○ If condition :
Statements
● Example:
○ if 3>2:
print("it worked")
23. If Statements - Else
● Else : The else keyword catches anything which isn't caught by the
preceding conditions.
● Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
24. If Statements - Elif
● Elif : The elif keyword is pythons way of saying "if the previous conditions
were not true, then try this condition".
● Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
25. Logical Operators
● Logical operators are used to combine conditional statements
Operator Description
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
27. List
● A list is a collection which is ordered and changeable. In Python lists are
written with square brackets.
● Example:
thislist = ["apple", "banana", "cherry"]
print(thislist)
● We can store heterogeneous data inside list
● We can use both +ve and -ve index to access elements in the list.
● Slicing can be used on list
○ Example: thislist[0:2]
● We can have a list inside a list
○ Example: l=[1,2,3,4,[5,6,7],8]
print(l[4][1]) # 6
28. List - program
known_users = ["adarsh","don","pinky","ponky","moon"]
print(len(known_users))
while True:
print("Hi !, Welcome")
name = input("Whats your name: ").strip().lower()
if (name in known_users):
print("Hello {}!".format(name))
remove = input("Would you like to be removed from the system (y/n)")
if(remove.upper()=="Y"):
print(known_users)
known_users.remove(name)
print(known_users)
else:
print("Hmm ! I dont have met you yet")
add_me = input("Would you like to be added to the system (y/n)").lower()
if(add_me=="y"):
known_users.append(name)
elif(add_me=="n"):
print("No problem ! See you around")
29. Adding item to lists
● Only list can be added to list
● Example:
A = [1,2,3,4]
A = A + 1 // this will give error
A = A + [5] //[1,2,3,4,5]
A = A + “ABC” // this will give error
A = A + [“BCD”] //[1,2,3,4,”BCD”]
A = A + list(“ABC”) //[1,2,3,4,’A’,’B’,’C’]
● We can use append() to add elements at the last of list
● We can use insert() to add the elements at the desired index.
○ Example : A.insert(2,100) // [1,2,100,3,4]
30. Tuples
● A tuple is a collection which is ordered and unchangeable. In Python tuples
are written with round brackets.
● Example : thistuple = ("apple", "banana", "cherry")
● We can use slice as in list Ex: thituple[0:2] //("apple", "banana")
● Tuples are immutable, so they cannot be changed.
○ Ex: thistuple[1] = “orange” // This will throw error
● We can join tuples using + operator.
○ Ex: tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2 // ("a", "b" , "c",1, 2, 3)
31. Dictionaries
● 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.
● Example : thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
● We can access the elements in the dictionary by referring to the key name.
○ Example: thisdict["model"] // Mustang
● You can change the value of a specific item by referring to its key name
○ Example : thisdict["year"] = 2018
● keys() gives all the keys in the dictionary
○ Example: thisdict.keys() //dict.keys([“brand”,”model”,”year”])
● values() gives all the values in the dictionary
○ Example: thisdict.values() //dict.keys([“Ford”,”Mustang”,1964])
32. Dictionaries
● We can store dictionary inside a dictionary
○ Example: students{
“don” : {“id”: 11,”Age”:20, “grade”:”B”},
“monu” : {“id”: 22,”Age”:19, “grade”:”A”},
“sonu” : {“id”: 33,”Age”:18, “grade”:”C”}
}
print(students[“don”][“Age”]) //20
33. Cinema Simulator
films = {"don 1": [18,5],
"sheru": [3,2],
"tarzan": [15,5],
"bourne":[18,5]
}
while True:
print(list(films.keys()))
choice = input("What film would you like to watch ?").strip().lower()
if choice in films:
age = int(input("How old are you ?:").strip())
if age>=films[choice][0]:
if films[choice][1]>0:
films[choice][1] = films[choice][1] -1
print("Enjoy the film !")
else:
print("Sorry, We are sold out!")
else:
print("you are too young to see the film!")
else:
print("We do not have that film...")
35. While loop
● With the while loop we can execute a set of statements as long as a
condition is true.
● Example:
i = 1
while i < 6:
print(i)
i += 1
● This will print numbers from 1 to 5.
36. For loop
● A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
● With the for loop we can execute a set of statements, once for each item in
a list, tuple, set etc.
● Example:
vowels = 0
consonants = 0
for letter in "adarsh" :
if letter.lower() in "aeiou":
vowels = vowels +1
elif letter ==" ":
pass
else:
consonants = consonants + 1
print("There are {} vowels".format(vowels))
print("There are {} consonants".format(consonants))
37. List Comprehensions
● List Comprehensions provide an elegant way to create new lists. The
following is the basic structure of a list comprehension:
● output_list = [output_exp for var in input_list if (var satisfies this condition)]
● Printing even numbers:
Even_number = [x for x in range(1,101) if x%2==0]
39. Function
● A function is 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.
● In Python a function is defined using the def keyword.
● Example: def my_function():
print("Hello from a function")
● Function can accept parameter, these parameters are specified after the
function name, inside the parentheses, we can add as many arguments as
we want , just separate them with comma.
Calling function
● To call a function, use the function name followed by parenthesis
● Example: my_function()
40. Function
● To let function return a value, we use return statement.
● Example:
def my_function(x):
return 5 * x
41. Variable scope
● Local scope - A variable created inside a function belongs to the local scope
of that function, and can only be used inside that function.
● Example : def myfunc():
x = 300
print(x)
● As explained in the example above, the variable x is not available outside
the function, but it is available for any function inside the function.
● A variable created in the main body of the Python code is a global variable
and belongs to the global scope.
● Example : x = 300
def myfunc():
print(x)
myfunc()
print(x)
42. Variable scope
● If you need to create a global variable, but are stuck in the local scope, you
can use the global keyword.
● The global keyword makes the variable global.
● use the global keyword if you want to make a change to a global variable
inside a function.
● Example : x = 300
def myfunc():
global x
x = 200
myfunc()
print(x) //200
43. Arbitrary arguments and keywords
● If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
● This way the function will receive a tuple of arguments, and can access the
items accordingly.
● Example : def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus") //The youngest child is Linus
● If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
44. Arbitrary arguments and keywords
● This way the function will receive a dictionary of arguments, and can access
the items accordingly
● Example : def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
46. Python classes and objects
● Class - A Class is like an object constructor, or a "blueprint" for creating
objects.
● To create a class, use the keyword class.
● Example : class MyClass:
x = 5
● Now we can use the class named MyClass to create objects
● Objects have both states and behaviours.
● Example : p1 = MyClass()
print(p1.x)
47. Python classes and objects
● __init__() - is always executed when the class is being initiated.
● __init__() function can be used to assign values to object properties, or other
operations that are necessary to do when the object is being created.
● Example: class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
48. Python classes and objects
● The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs to the class.
● We can call it whatever you like, but it has to be the first parameter of any
function in the class.
● Del - You can delete objects by using the del keyword.
○ Example: del p1