Python
Table of Contents
The Logo of the Python Programming Language [1] |
---|
Introduction
Python is an interpreted, high-level, general-purpose programming language [2]. Python's design emphasizes code readability with its notable use of significant indentation. Python is dynamically typed and garbage collected. It supports multiple programming paradigms such as procedural, object-oriented, and functional programming due to its thorough standard library. As of April 2021, Python was ranked third in The Importance of Being Earnest (TIOBE) index, an index measuring the most popular programming languages [3]. Python is not the fastest programming language by any means, but the convenience brought upon by its user-oriented design generally outweighs any minor runtime deficits.
This wiki page serves as a basic introduction to Python, but is by no means a comprehensive resource to learn the language. It will go over basic syntax and a few features, but will not go in depth. There are numerous reputable online courses, and books for learning Python that one should look into for comprehensive information. One such course, is the Python for Everybody course which is available at the freecodecamp website. It is also recommended that one should set up their own development environment, such as through an Integrated Development Environment (IDE), to develop their python code.
Setting Up The Development Environment
For beginners, it is strongly recommended to use an IDE to write and debug code. For a tutorial detailing how to install and setup the Atom IDE to code in python, please refer here. Alternately, one can use text editors such as VSCode, but for the purposes of a beginner, an IDE is more preferable. An IDE, essentially, packages all the tools you need to write functioning code. Thus, one can minimize the time it takes to set up their development environment, and go straight to coding.
Basic Program
Python scripts differ slightly from the scripts of other programming languages, as there no "int main()" where you put the bulk of your code. You simply write code on a blank script and it will execute lines in the order they are written in.
Since Python has such a comprehensive standard library, one will often find that they generally do not need to use as many external libraries compared to a language such as C. That being said, one will still have to use external libraries and their functions, and the way to declare it in a script is:
import pygame #all imports should be at the top of the python script
It should also be noted that this same syntax can be used to import other python files into your main script. Remember when using this method to import a python file to leave the ".py" suffix out of the name. Also, one can comment in their code using "#".
In Python, there are things known as functions, which are a block of organized, reusable code that is used to perform a single related action [4]. Functions help organize a script by avoiding repetition and making code reusable. A function is defined in python by "def function_name(parameters):". Then any code that is contained in the scope of the function must be indented. Most functions return a value of a given data type, the one exception to this are void functions. Void functions perform a task in lieu of returning a value. For non-void functions, the end of the function must contain the line "return" followed by the value that needs to be returned.
#This is a function which returns the sum of two numbers def addition(x,y): return x + y #This is a void function which prints sum of two numbers as a math expression def printMath(x,y,ans): print(x, '+', y, '=', ans) #Calling upon the function x = 8 y = 5 sum = addition(x,y) # sum = 13 printMath(x,y,sum) # 8 + 5 = 13 would be the output
Variables and Data Types
Python is a dynamically typed programming language, which essentially means that one does not need to declare the type of one's variables before using them [5]. Here are some examples of variable declarations:
building = "School" numPeople = 8 mark = 80.5
Variable names can contain uppercase/lowercase characters, digits, and underscores, but can not start with a digit. It is good coding practice to descriptively name your variables, as it significantly improves legibility for others viewing your code, as well as yourself. It should be noted that in Python a variable must be declared with an initial value, there is no way to declare an "empty" variable the way once can in C.
Basic Data Type | Example |
---|---|
int | 45 |
float | 45.55 |
complex | 3 + 2j |
char | 'a' |
str | "hello" |
bool | True |
This table just touches on some basic data types found in Python.
Basic Operators
Arithmetic Operators [4]
x = a + b #Addition operator, adds a and b and returns the result x = a - b #Subtraction operator, subtracts b from a and returns the result x = a * b #Multiplication operator, multiplies a and b and returns the result x = a / b #Division operator, divides a by b and returns the result as a floating point number x = a % b #Modulus operator, divides a by b and returns the remainder x = a // b #Floor division operator, divides a by b and returns the rounded down result x = a**b #Exponention operator, returns the result of a to the exponent b
Assignment Operators [4]
x = a #Assignment operator, assigns the value on the right to the variable x += a #Equivalent to x = x + a x -= a #Equivalent to x = x - a x *= a #Equivalent to x = x * a x /= a #Equivalent to x = x / a x %= a #Equivalent to x = x % a x //= a #Equivalent to x = x // a
Logical Operators [4]
x > 10 and x < 15 #AND operator, returns true if both conditions are true x > 10 or x < 15 #OR operator, returns true if one of the conditions is true not(x > 15) #NOT operator, returns the opposite of the conditions. e.g if x = 16 it returns false
Identity Operators [4]
x is y #is operator, returns true if x and y are the same object, meaning same value and datatype x is not y #is not operator, returns true if x and y are not the same object
Membership Operators [4]
x in y #in operator, returns true if a sequence with the specified value is present in the object x not in y #not in operator, returns true if a sequence with the specified value is not present in the object
Comparison Operators [4]
x == y #checks if x is equal to y, and returns true if it is x > y #checks if x is greater than y, and returns true if it is x < y #checks if x is less than y, and returns true if it is x >= y #checks if x is greater than or equal to y, and returns true if it is x <= y #checks if x is less than or equal to y, and returns true if it is
This covers the majority of operators in the Python language.
Conditionals
if condition : #insert block of code to run if the condition is fulfilled #important to note that this block code of has to be uniformly indented if x == 5 : #block of code that will execute if x is equal to 5 else : #block of code that will execute if x is not equal to 5 if x > 100 : #block of code that will execute if x is greater than 100 elif x > 50 : #block of code that will execute if x < 100 and x > 50 else #block of code that will execute if x < 50
Printing and Reading
Basics of Printing
The print function allows one to print something to console. The print function automatically converts any parameter values into strings, so that one can print the value of multiple variables with differing datatypes in one statement. Each parameter is automatically equally spaced from each other, so it is not something you need to take into account.
Here's an example:
print("The year is", 2021)
Reading Input
The input() functions allows one to read user input from console. Here's an example:
question = "What is your name?" name = input(question) #input is bob print("Your name is", name) #"Your name is bob" is printed to console #The input function prints the query you want, and then receives the response #The response is then assigned to a variable #It should be noted that input function always returns a string #So if one does not want to a string variable, one has to change the datatype question = "What is your age?" age = int(input(question)) print("Your age is", age)
Loops
Loops are a method which will automate repetitive processes [4]. There are two main types of loops in Python:
While Loops
while condition : #execute block of code
An example of a while loop may be:
#this script prints the numbers from 0 to 100 x = 0 while x <= 100 : print(x) x += 1
In this scenario, the x variable is initialized at 0. Then, the variable is incremented by a value of 1 every time the while loop executes. Finally, when x variable is equal to 101, therefore not fulfilling the while condition, the script breaks out of the loop.
Another feature of loops is break and continue. If there is break under an if statement coded into a loop, when that if condition is fulfilled, the script will stop looping. Conversely, if there is a continue under an if statement coded into the loop, when that if condition is fulfilled, the loop will skip the current iteration and go on to its next iteration.
Here's an example:
#Here the program will only print the values from 0 to 5, even though while condition is still true x = 0 while x <= 10 : print(x) if x == 5 : break x += 1 #Here the program will only print even numbers from 2 to 100 y = 2 while y <= 100 : if not(y % 2 == 0) : continue print(y)
For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
#This script will print the number of times 6 is found in the list numbers = [6, 10, 14, 6, 103, 2004, 18] count = 0 for x in numbers : if x == 6 : count += 1 print(count)
Lists
A list is a variable that can store multiple values of any data type. Meaning that the list can contain integers, string, and floats for example. There are two ways to initialize a list in Python: to create an empty list, or to create a list with values. List's are not confined to the size they are initialized with, they are dynamic so one can add as many new values as one needs.
x = list() #this creates an empty list numbers = [2,3,5,6,1,6] #this creates a list with initial values
The list shown in the example above can be visualized as:
Index | 0 | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|---|
Value | 2 | 3 | 5 | 6 | 1 | 6 |
It is important to note that starting index is 0 not 1. Therefore, if one wanted to get the 1st value in the list, it is actually stored in the index 0 of the list. So, when calling the value from the list, the code would look like: "numbers[0]".
Lists have a lot of different built in functions which one can learn about from the numerous different online resources detailing the data structure. One especially useful function is the append() function which adds an object to the list. Here's an example using the append function:
#This script will add items to your grocery list until you are done grocery = list() prompt = "What grocery item do you need?" prompt1 = "Do you have any more to add? Y/N" while True : item = input(prompt) grocery.append(item) again = input(prompt1) if again == N break print(grocery)
Next Steps
This page has barely scratched the surface of learning Python, it is meant to be a bare bones introduction to the language. As there are vast array of topics that are not covered here. One can further develop their Python skills from reading books such as Python Crash Course by Eric Matthews or Automate the Boring Stuff with Python, 2nd Edition: Practical Programming for Total Beginners by Al Sweigart. As previously mentioned, the Python for Everybody course on the freecodecamp website is also a great free in depth resource to learn Python. Lastly, the official Python documentation is very legible and understandable even for beginners, so it is a great reference to supplement one's Python learning.
References
[1] J. Bullock, “Python, for Experienced Programmers,” Medium, 07-Jan-2021. [Online]. Available: https://medium.com/dev-genius/python-for-experienced-programmers-a2ee334ce62f. [Accessed: 14-Apr-2021].
[2] S. Yegulalp, “What is Python? Powerful, intuitive programming,” InfoWorld, 13-Nov-2019. [Online]. Available: https://www.infoworld.com/article/3204016/what-is-python-powerful-intuitive-programming.html. [Accessed: 14-Apr-2021].
[3] “Most Popular Programming Languages,” TIOBE. [Online]. Available: https://www.tiobe.com/tiobe-index/. [Accessed: 14-Apr-2021].
[4] “Python ,” Python Tutorial. [Online]. Available: https://www.w3schools.com/python/default.asp. [Accessed: 14-Apr-2021].
[5] “The Python Tutorial¶,” The Python Tutorial - Python 3.9.4 documentation. [Online]. Available: https://docs.python.org/3/tutorial/index.html. [Accessed: 14-Apr-2021].
Contributors:
User | Last Update |
---|---|
Mayurakhi Khan | 1145 days ago |
Former user (Deleted) | |
Former user (Deleted) | |
Former user (Deleted) |