A custom module is just a python file with fiunctions in it. You can create a python file and put in the same location as the program where you are going to call it. Here is an example:
I will create a new file called mymodule.py
def banana(filename):
name = open(filename)
content = name.read()
list = content.split(” “)
print (list)
counter = 0
for i in list:
if i.lower() == “banana”:
counter += 1
print (counter)
def calculate_e(precision):
counter = 1
accumulative = 1
variable = 1
while True:
accumulative += variable*(1/counter)
variable = (1/counter)*variable
new = accumulative + variable*(1/counter)
if (new – accumulative) < precision:
break
counter += 1
return accumulative
And now i´m going to call that file just like if it were a module. This file is called file.py and is located in the same directory as mymodule.py:
import mymodule.py
a = mymodule.banana(“text.txt”) #You must have a file named “text” called “text”
b = mymodule.calculate_e(35)
print (a)
print(b)
2
2.71825
As you can see in file.py i used the functions inside of mymodule.py by calling them as if they were a module(well, it is a module now)
Reading files:To read a file you should know this functions: open(“filename”,”r”) and filename.read()The first one is used to open a file, read it and pass that information to a variable ( if you want) or to simply work with it directly.The second one …
Here i will show you what are the python conventions.
First of all, in python the indentation does matter. Indentantion is the way that python recognize if a code block has ended. For example:
if (a < b):
counter + =1
print (counter)
This is wrong because the IF has nothing inside it, instead it will always add 1+ to the counter because is at the same level as the IF. This is not C++ or JS where you can tell the program when your if ends with {}. The right way to do it is this:
if ( a < b):
counter += 1
print(counter)
Also here are some tips to give a standar python style to your code:
-Just do one statement per line
Please don´t do this:
def ejercicio3(diccionario): return ((“Homework promedio:”, sum(diccionario[“homework”])/len(diccionario[“homework” ])), (“Quizzes promedio:”, sum(diccionario[“quizzes”])/len(diccionario[“quizzes”])), (“Tests promedio:”, sum(diccionario[“tests”])/len(diccionario[“tests”])))
Yes, this is a python program that actually works. As you can see it is very hard to read and you will make others to have a bad time trying to understand what you want to do. Don´t be a smart a** and put order to your code so that everyone can understand it.
-Keep spaces between variables if necessary, just to make it more readable
-Build your functions on the top part of the code
I think that this is clear, declare your functions first and call them below. Try to declare all the functions you can on the top part and write the main program after that, this will make your code easier to read because if someone wants to follow the executuion order of your code he/she doesn´t have to look for a specific function on all the code; otherwise, he/she will know where the functions are and you will save him/her time.
–Keep your code simple
Here is an example of the last point:
a = input(“Write a number”))
a = int(a)
for i in range(0,50)
if i/a % 0:
counter = counter + 1
b = counter*2
c = b+18
print (c)
This code is really simple but it can be done in less words and space, the proper way to do it is:
a = int (input(“Write a number” ))
for i in range( 0 , 50 )
if (i/a) % 0:
counter += 1
print(counter*2+18)
The elif is a conditional used to expand options of a normal conditional of If-Else. It´s very useful when you want to check different conditions at once but at the same time you want to save time at writing the code. Lets see an example, first a program without elif:
x = input(“¿What do you want to do next?”)
if x == “exit”:
#close the program
else:
if x == “pay”:
#go to the pay window
else:
if x == “back”:
#move to the previous window
else:
if x == “next”:
#move to the next window
else:
if x == “add”:
#add the item to the shopping list
else:
print (“please write exit, pay, back, next or add”)
This program is a cheap and lazy representation of an online store. It receives an input from the user and do whatever the user writes, to do this we need to check several conditions at the same time (aka a nesting of conditions): if the user wants to exit, pay, go back, go next or add the item to the list. As you can see it took me a lot of space to write those conditions in the regular way. If the first condition didn´t work it will pass to the else that is another condition and if that condition is false it will pass the the next else that is another condition and it keeps going on until one condition is true or it reaches the final else. The easy and clean way to do it is with the elif, let´s see an example of the same program but this time with elifs:
x = input(“¿What do you want to do next?”)
if x == “exit”:
#close the program
elif x == “pay”:
#go to the pay window
elif x == “back”:
#move to the previous window
elif x == “next”:
#move to the next window
elif x == “add”:
#add the item to the shopping list
else:
print (“please write exit, pay, back, next or add”)
This program do exaclty the same but it took me less time to write it and is easier to understand than the other one. The elif is like the combination of else-if, Python reads it exactly in the same way.
Notice that each elif is used as an if, with the condition by the side, the “:” at the end and the instructions are indented. To finish the nesting of conditions we put an else just as if it were a normal if/else. If the user writes “back” the first and second conditions will be false and it will execute the code inside the second elif. Have in mind that after the program ends executing the code inside the elif it will jump to the end of the nesting and continue going, what i mean is that the program will not continue checking if the other conditions are true because one has already been executed. Also, the program reads from top to botton the conditions, not at the same time; so if two conditions are true it will only execute the first one. Let´s see an example of this:
x = 3
if x > 0:
print (“X is greater than 0”)
elif x < 10:
print (“X is less than ten”)
elif x < 0:
print (“X is a negative number”)
else:
print (“X is greater than 10”)
X is greater than cero
Well, what´s wrong with this program? What´s wrong is that no matter what number you put, it will print “X is greater than 0” or “X is a negative number” completely ignoring the other two conditions. Lets see, if we write a 9 it should print “X is less than then” but also the first condition is true so it should also print “X is greater than 0” but as a nesting of conditions can only take one condition it will go for the first one to be true si it will print “X is greater than 0”. If we write number 20 the first condition to be true will be x > 0 so it will print “X is greater than 0” again. Just in case that you write a negative number it will print “X is a negative number” but for all the other numbers the first condition will always be true first. If you want to make a good condition nesting with elif (also with else/if) always have in mind which condition you give the preference. Nothing happens if two or more conditions are true, the program can still work as you want if you put them in the right order. I recommend you to order the condition from specific to general, in that way if the specific condition is true but also the general is true the program is going to take the specific condition first. Here is the same program but this time taking all the posibilities from the specific to the general:
x =0
if x == 0:
print (“X is equal to 0”)
elif x < 10:
print (“X is less than ten”)
elif x > 10:
print (“X is greater than 10”)
else:
print (“X is a negative number or is a string”)
X is equal to 0
Functions in Python are very easy to use, they do specific actions with the value you call them. The function substitute a value into a block of code and the returns the calculation (or sometimes they do nothing). For example, you have probably used before the print function:
Calling a function
Creating a function
Notes
Hello!! Here i´m going to show you how to write and print a text based user input.
Print text based user input
Lets say that you want to ask for the name of the user and then print it. It´s something very simple that requires an imput. Here I will show you my code:
In the code I created a variable called Name that is going to take the value of whatever the user input is, inside the INPUT function I asked the user for his/her name. It´s important to keep the user informed about what you want him to give you, always fill the parenthesis with the inormation you want to ask him because f youi leave it in blank the user will not know what to write.
This is the code working:
As you noticed, the string that I wrote inside the INPUT function (between the parenthesis) is what Python asked me to write. Then I wrote my name and the variable Name took that string value. When the program printed Name it printed what I wrote.
In the PRINT function we are telling the program that we want to print the variable Name, this is not between the quotes because it´s a variable, remember that if you want to print a string you have to use the quotes. Also, you can combine variables and strings in the same PRINT function, let me show you:
If i write “José Carlos” as my name and “17” as my age what this program should do is to print ” Your name is José Caros Peñuelas and your are 17 years old”. Lets see if this works:
Well, something obviously went wrong. Lets see what it was.
Oh I see now, the variables (shown in black by default) should be separated from the text with commas “,”, this is the way that python recognize that you want a variable there and not a string.
This is the correct way to do it, notice that i have the commas now:
The program will put the value of name and age between the strings. Notice that in the PRINT function I separated the variables from the strings with a comma. This is the code working:
Integer input
Now let´s try the same thing but with numbers:
To create a new file:
To create a file in python first you have to open the Python IDLE, to do this you have to go to the search bar and look for “python”, there you willl see the IDLE exe.