0% found this document useful (0 votes)
20 views12 pages

100day Bootcamp Python

Uploaded by

Dixxy Scott
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
20 views12 pages

100day Bootcamp Python

Uploaded by

Dixxy Scott
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 12

Python boot camp- 100 days code

challenge

Errors:
 Syntax error – Happens when the code doesn’t makes sense to the compiler, in simple words; Something is
misspelt or there are too many brackets or a missing comma.
 Name error – This happens when there is a variable with a name which the computer doesn’t recognises.
Usually because of a typo.
 Zero division error – This happens when you try to divide something by a 0. Dividing anything by a zero is
impossible so python will complain.
 Indentation error – This happens when there is an indent wrongfully placed(unexpected indent).

Printing multiple lines in a single print statement:


“\n” is an escape sequence used to change lines in a single print statement.
If u don’t need any space in the start of the new line then avoid using a space after the escape sequence.

>>>print(“hello world!\nHello”)

Output
hello world!
Hello

Concatenation:
To concatenate two strings, we use the “+” operation to concatenate two strings. This operator doesn’t adds any
space between the concatenated strings.

>>>print(“Hello” + “World”)
>>>print(“Hello “ + “World”)
>>>print(“Hello” + “ ” + “World”)

Output
HelloWorld
Hello World
Hello World

Taking data input from a user:


To take an input from a user we use the function “input(<prompt>)”, where the prompt is the prompt for the user
usually asking the user what kind of data the function or we want. There is no space added after the compiler prints
the prompt, we need to design the prompt in such a way so that there is appropriate space after the prompt for the
user to input the data. An input always is taken as a string datatype.

>>>input(“What is you name? : ”)

When we enter the input, this above code line is replaced by the input given by the user, so “input(“What is you
name? : ”) is altered to the <input> given by the user in the system.

>>>print(“Hello ” + input(“What is your name?: ”) + “!”)


Execution
The code line, first converts “Hello” into a string the movies onto the input function and prompts the user to input
their name, after they input their name, the name is replaced with the input function and is converted into a string,
similarly the “!” is also converted into a string, everything is concatenated and the whole line is printed.

Output
What is your name?: Courage
Hello Courage!

Note: A function in a print statement has higher precendence, so it will be read first by the system like in the above
example the input function was executed first then the print statement was executed.

Finding the length of a string:


To find the length of a string the “len()” function is used, The len function finds the number of characters in a string
even if it is a blank space (“ ”).

>>>print(len(“Dave”))

Output
4

Variables:
Variables are containers which contain data.

>>> name = input(“What is your name?: ”)

Whatever input is given here by the user is now associated with the variable “name”.
Whenever we will refer to the variable name, it will refer to the input given in by the user.
A variable can consist of alphanumerical characters and special characters and underscore; But a variable can only
begin with a letter or an underscore. Keywords can’t be used as variable names

Swapping values:
To swap values between two variables, we can use a third variable which stores the value of first variable then we
store the value of second variable into the first variable and then load the value of first variable stored into the third
variable into the second variable.

>>>a = 10
>>>b = 20
>>>c = a, a = b
>>>b = c
>>>print(a,b)

Output
20 10

Or

>>> a = 10
>>> b = 20
>>> a,b = b,a
>>> print(a,b)
Output
20 10
Data types:
 String – Anything that is enclosed within double or single quotes is called a string.
 Integer – any whole or negative number without a decimal point in them is called an integer
 Float – any number with a decimal in it
 Boolean – merely “true”.
 Comments – Comments are statements which starts with a hashtag and can’t be read by the compiler, its just
for people to understand or for instructions within a code. To convert a block or a line of code into a
comment either add a hashtag infront of it or press “Ctrl + /”.

The default data type of a “print()” function is “string”

Type casting:
The “type(<variable>)” function gives the data type of the variable used with the function.

Type casting is used to convert one data type to another data type.

>>>str(123)

The above statement converted the integer “123” into a string.


The type cast functions are as follows:
 str() – to convert into string.
 int() – to convert into integer.
 float() – to convert into float.
 bool() – to convert into boolean.
 Comment – “ ctrl + / “ used to convert lines or block of codes into comments.

Two different data types can’t be concatenated, so in order to make it possible the data types must be type casted
into a single data type and then be operated upon.

Number manipulations:
 round(op, no. of rounded off digits) – rounds off a number to a whole number or to a specific number of
digits when specified
 / - division operator which gives out the output in float
 // - float division operator which gives out the output in integer format, the float portion is truncated.
 += - increment operator
 -= - decrement operator
 *= - multiplier increment operator
 /= - divider decrement operator
 == - equal to operator
 = - assignment operator
 >= - greater than or equal to
 <= -less than or equal to

F-Strings:
An F-string converts all data types used in a print statement to the string data type instead of converting all of them
to a string data type individually and concatenating them.

>>>score = 0
>>>height = 1.8
>>>isWinning = True
>>>print(f”Current score is {score}, your height is {height}, your winning is {isWinning}”)

Output
Current score is 0, your height is 1.8, your winning is True
The F-string converts all the data types into the string data type behind the scenes.

Formatting:
“{:.2f}”.format(a)

Here the “2f” means there should be 2 digits after the float (decimal) in the variable a.
If there is only 1 digit after the decimal then a 0 will be added.

>>> a = 12.1222222
>>> a = “{:.2f}”.format(a)
>>> print(a)

Output
12.12

If-Else statements:
if <condition>:
do this
elif <condition>:
do this
else:
do this

When the condition in the if statement is satisfied, the code block under the if statement is executed disregarding the
else statement.
When the condition in the if statement is not satisfied, the code block under the else statement is executed.

Nested if-else statements:


When there is an if-else statement block inside another if-else statement, it is called a nested if-else statement.

if <condition>:
if <condition>:
do this
else:
do this
else:
do this

the nested statements can be part of either if, else of any elif (else-if) statement. We can use indefinite number of elif
statements.

Logical operators:
 AND
 OR
 NOT
1). AND
AND operator requires two conditionals to be satisfied for the whole statement to be true
2). OR
OR operator requires only one conditional to be satisfied for the whole statement to be true
3). NOT
NOT operator reverse the output for a statement, True becomes false and vice versa.
 count() – The count function counts the number of a character in a string. For example
”variable.count(‘q’”, here the function counts the number of ‘q’ in the variable.
 lower() – The lower function lowercases the variable. “variable.lower()”

Generating pseudo random numbers in python:


Firstly we’ll need to import the random module which has all the functions already defined to generate pseudo
random numbers, for which the syntax is “import random”.
To call the any of the function provided in the random
module, we first type the module name “random”, add a decimal and then write the name of the function we need
to use. For instance “random.functionName()”.
 random.randint(x,y) - the randint function generates a random integer in the range of ‘x’ and ‘y’.
 random.random() – the random function generated a random floating point number in the range or 0 – 1,
not including 1. To increase the range of that function we can just multiply the random float with an
appropriate number.
 random.choice(list) – generates a random choice from the given list.

Lists:
Lists is a data type in which literals of different data types can be stored. Data stored in a list is enclosed in square
brackets “[”. The data stored in a list are indexed starting from 0 when looked from the LHS and -1 when looked from
the RHS.
To call any element from a list, we use the following syntax “<ListName>[index]” we use a square bracket to
call any element of that particular index because lists are associated with square brackets.

Any item in a list or any variable in python can be altered just by calling the variable or element position and then
altering its value.

To take input into a variable as a list we use the following syntax


List = input(<prompt>).split()
This syntax takes the inputs in the form of string characters, to convert them to a different data type; refer to for
loops

List operations:
 <listName>.append(x) – adds element x towards the end of the list.
 <listName>.extend(x) – merges two separate lists.
 <listName>.insert(x,y) – Inserts element ‘x’ at index ‘y’.
 <listName>.remove(x) – removes the element ‘x’ from the list.
 <listName>.pop([y]) – removes the element stored at index ‘y’.
 <listName>.clear() – deletes the whole list.
 <listName>.sort() – sorts the list into ascending order, to make it descending, just insert the parameter
“reverse = True”
 <listName>.count(x) – counts the number of times ‘x’ occurs in the list.

Nested lists:
When two or more lists are used as data entries of one list or when those list variables are used as elements for
another list, its then called a nested list.

Example: Output:
Frutis = [‘aaple’,1,3] [[‘aaple’,1,3], [‘banana’,5,6]]
Veggies = [‘banana’,5,6]
Groceries = [Frutis, Veggies]
Print(Groceries)
for loop:
if we want to access each item in a list or a data structure, we use a “for loop”.

Example:
Fruits = [“apple”, ”banana”, “pear”]
for I in Fruits:
print(i)

in the first iteration of the for loop, “print(i)” will print the first element in the list <Fruits>. Similarly in the second
iteration it will print the second element in the list and so on. With each iteration it will advance to the next element
until the loop is stopped or the list comes to an end.

Converting list data type from string to int or a different data type:
list = input().split() #takes input as list
for I in range(0, len(list) – 1):
list[i] = int(list[i])

the range function in for loop:


for i in range(initial_num, limit+1, step_size):
print(i)

above function will print “i” which will be numbers ranging from the initial number to the “limit + 1” as the last limit
number won’t be included, so in order to include that we need to add a unit to it. To make sure each iteration has an
increment of a specific number, the third parameter can be the step size which specifies how much increment will be
there after each iteration.

Functions:
Using inbuilt functions:
To call an inbuilt function, we first specify the function name and then enclose the parameters with brackets.

Example:
<function_name>(parameter)

Defining a function:
To define a function, we first write the keyword “def” after which we can type the name of our custom function
which we wish to build and then write the code block to be executed when the function is called.

Example:
def <function_name>(optional parameters):
<code block to be executed>

In order to use that function we need to call that function by typing “<function_name>(optional parameters)”, this
syntax will call the function and the code block under the function will be executed.

To indent a block of code left or right we use “ctrl + [” and “ctrl + ]” respectively.

While loop:
while loop is a loop which will iterate until its conditional or operating expression remains true.

Example:
while something_is_true:
#then do this
#then do this
#then do this
Defining a function:
def <function_name>(optional parameters):
<code block to be executed>

In order to use that function we need to call that function by typing “<function_name>(optional parameters)”, this
syntax will call the function and the code block under the function will be executed.

Parameter = argument

“argument” is the actual piece of data that will be passed over to the function when it is being called.
Whereas the parameter is the name of that data like a variable.

Dictionaries:
In Every dictionary there are two parts, one LHS and one RHS. The LHS is the key and the RHS corresponding to that
key is its value. Dictionaries are enclosed in curly brackets.
for example:
dictionary = {
‘key’: ‘value’,
‘key2’: ‘value2’,
}
The key can be of various data types or can be variable.

Adding new items to the dictionary:


dictionary.[‘key’] = ‘value’
#same syntax can be used to alter the values of a specific key in the dictionary by calling its corresponding key.

Creating a new empty dictionary:


Empty_dict = {}

Wiping an existing dictionary:


dictionary = {
‘key’: ‘value’,
‘key2’: ‘value2’,
}
dictionary = {}

calling a value from a dictionary:


print(dictionary[key])

when a key is run through a “for-loop”, the for loop iterates through each key not its value.

Print vs Return:
The print statement just prints the data onto the console,
But if we want to assign the value obtained in the end of a function to some another variable, we use the return
statement, it replaces the function call with the value obtained in its end.

If you don’t use the return statement it assigns the value None to the function.

Scope:
When a variable is defined under a function, we won’t be able to access it outside the function. The scope or
accessibility of this variable will be called a local scope as it can only be accessed within the function.

Whereas when u define a variable outside a function it has a global scope, as it can be called outside any function
and inside any function no matter how nested a function is.
Global and local scopes not only apply to variables but functions and other data structures as well
MULTILINE EDITING:
IN PYCHARM TO GET MULTIPLE CURSORS, EITHER PRESS ALT AND PRESS WHEREVER U WANT THE CURSOR TO BE, OR
HOLD ALT+SHIFT AND DRAG THE MOUSE CURSOR TO GET THE MULTIPLE CURSORS.

OOP in python

Pascal case/casing : in pascal casing, the initial of each word in an identifier starts with a capital letter.
Camel case/casing : camel casing is no different from pascal case, except the first letter of the identifier is lower case.
Snake case/casing : in snake casing, the subsequent words in an identifier are separated with underscores.

An object in python consists of attributes and methods which are modelled by functions.
A class is a blueprint/template which is used to define objects.

Defining a class:
class <class_name>:
statement/attributes

Classes follow Pascal casing.

Defining an object:
<object name> = <class_name>()

To define an attribute outside the class


(adding extra values to that object specifically or editing the default parameters)
<initialised_class>.<attribute_name> = <value>

To call a function/method with an object from a class:


<object_name>.<method()> (- A function tied to a class is called a method)

Defining constructors:
Constructors are just default values for an attribute in a method, method being just a defined function inside a class.
We initialize values in a constructor to set their starting values in the beginning of a program or a sub-program..
Whenever an object is being initialised, it will refer to the those default values in the constructor and will refer to
those values every time whenever the object is called. The default values under that particular object can be altered
by calling that particular attribute and assigning it a new value.

Constructors are defined in a method named “_ _ init _ _” as in initialize attributes and is defined as follows:
class <class_name>:
def _ _init_ _(self):
#initalise attributes

The “_ _init_ _” function will be called everytime u create a new object from that class triggering all the attributes,
and functions and commands to be executed under the “_ _init_ _” function.
For example:

class User:
def __init__(self):
print("A new user has been created.")

user_1 = User()
user_1.id = 1221
user_1.username = 'john doe\n'

print(user_1.username)

user_2 = User()
user_2.id = 2331
user_2.username = 'jane doe'

Output:

A new user has been created.


John doe

A new user has been created.

As it can be notices in the above example, the moment an object was initialised, all the values, functions and
commands were executed.

Assigning default values to an object or using parametrized assigning using constructor:

In a constructor, the ‘self’ parameter refers to the initialised object.

class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year

Here, ‘self’ refers to the object which will be initialised using the class ‘Car()’.
So instead of manually assigning the values like;
<initialised object name>.<attribute variable name> = <value>
and taking up multiple lines, we can just use parametrized assignment:
<object name> = <class name>(param1, param2, …., paramN)

For example:
class Car:
def __init__(self, make, model, year): #we can either use keywords or directly
self.make = make #or assign them directly to the attribute
self.model = model #without using params.
self.year = year

my_car = Car('Toyota', 'Corolla', 2020)


Methods:

When a function is attached to an object its called a method.


A method always needs the ‘self’ parameter as its first parameter

When you initialize a class with a constructor, the parameters given within the parenthesis of the class
initialization will be treated as the keyword argument or default keywords to the constructor if any, hence adding
those values to the constructor if specified.

Event Listeners or listeners:

Listeners are objects which listen to input devices for key strokes or any kind of input.

screen.listen()
screen.onkey(move_forwards, 'space') #screen.onkey(function, keystroke as a string)

the “screen.listen()” initialises the listener object, and the “screen.onkey(move_forwards, ‘space’)” reacts to the input
recorded by the listener and executes the function provided in the argument.

So ultimately, whenever we press ‘space’, the ‘move_forward’ function will be executed.


Note: We don’t provide any parenthesis at the end of the function in the listener’s ‘onkey’, command.

Higher order function:


A function which can work with other functions which only works in a few programming languages.

def add(n1, n2):


return n1 + n2

def subtract(n1, n2):


return n1 - n2

def multiply(n1, n2):


return n1 * n2

def divide(n1, n2):


return n1 / n2

def calculator(n1, n2, func):


return func(n1, n2)

result = calculator(2,3, add)


print (result)

In this example ‘calculator’ is a higher order function as it takes a function as an argument and works with other
functions.
Class inheritance:
The process of inheriting behaviour and appearance from an existing class is known as class inheritance.
i.e: inheriting the properties of a class and then adding extra properties to it.

Example:

class <class_name>(<inheritance class name>):


def _ _ init_ _(self):
super()._ _init_ _()

The ‘super()._ _init_ _()’ function, derives the constructor form the inheritance class to the constructor of our class.
To use any method or constructor function from the inheritance class into the derived class, we use the syntax;
super().<method_name>()

File management:
 To open a file:
file = open(r“file_directory/filename.txt”, mode = ‘<mode in which u want to open>’)

or

with open(r“file_directory/filename.txt”, mode = “<mode>”) as <variable>

File modes:
1. “w” = write; clears the whole file if data pre exists in it and writes new data
If it does not exist then it will create a new file the extension needs to be
correct
2. “a” = append; Appends data into the file with already co-existing data.
3. “r” = read; reads the file
4. Etc…

 To read the opened file:


contents = file.read()
now if we want to print the contents of the text file we can print using print statement.

Or

with open(r“file_directory/filename.txt”) as <variable>:


contents = file.read()
#closes the file automatically

 To write a file:
file.write(“<to be written>”)

 To read specific lines:


file.readline() or file.readlines()

 To replace specific phrases or words:


file.replace(<text to replace>, <text to be replaced with>)

 To close a file:
file.close()
we need to close the file because, it takes up resources from your computer to keep referring to it, so
upon closing it, few resources are cleared up, similar to opening a lot of tabs in your browser.

You might also like