Learn Python in Under 8 Minutes: The Ultimate Guide to Python Syntax
Photo from Unsplash

Learn Python in Under 8 Minutes: The Ultimate Guide to Python Syntax

I’ll explain everything from the basics of creating variables and lists to object-oriented programming through examples.

Python is one of the?fastest-growing programming languages and is the second most popular?overall. Not only is it extremely versatile and in sky-high demand right now, but it’s also super beginner-friendly, thanks to its clear and concise syntax and the large family of programmers who are willing to help fellow developers on?StackOverflow.

Whether you need a quick refresher of Python syntax, or whether you’re a total newbie, this guide is for you.

Table of Contents

  • Outputs and Inputs
  • Comments
  • Data types and variables
  • Arithmetic and Logical Operations
  • Conditional Statements
  • Loops
  • Functions
  • Object-Oriented Programming


Advice Before We Begin

To make learning more practical and effective, you should try writing some of your own Python code as we go along, either by visiting the following website or by using an IDE (integrated development environment)?you have installed, and creating a .py file.

Outputs and Inputs

Outputs

Perhaps the first thing you want to get a computer to do is print something, or output something on a terminal. The classic statement every programmer outputs when they first learn a language is “Hello World”.

Printing anything on a Python terminal is dead easy; just use the keyword?print?and follow it with brackets that contain the words you want to output in quotations.

For example, to print “Hello World”, we just write the following code:

  print("Hello World")        

When executed, this code shows up as follows on a terminal:

output screen

Inputs

Instead of getting your program to print something on a terminal for users to see, you might instead want it to ask the users for some information.

For example, suppose you wanted to say hello not to the world, but to the user instead. For that, you’d want to know their name.

To ask the user for their name, we write the following code.

  
input("What's your name?")        

Basically, we use a built-in input() function that allows the user to type something into the terminal.

In our case, we enter the question we want to ask the user (“What’s your name?”) as a parameter to the input function. Since this question will be printed as an output, we put it into quotations.

To then print the inputted name, we could write code like the following:

  
print("Hello", input("What's your name? "))        

When we run the above code, we see the following on our terminal.

No alt text provided for this image

When we type our name and press enter, we get the following:

No alt text provided for this image

Comments

To make code easier to understand for outside readers or for your future self who may have forgotten what you wrote?x?weeks ago, it helps to add?comments?to your code. These are just annotations that help explain what’s going on.

You can write short, one-line comments by using a # and longer ones by using three sets of quotations.

  
  #This is a single-line commen
  	
  
  """This is a
  multi-line 
  comment"""
  	
  
  #None of this code will actually run.
  #Only humans will read this.t        

Data Types and Variables

When we asked our user for their name and printed it on the terminal, we asked for data to be inputted.

When we use some data in a program, we can store it in a?variable.

For example, we can store an inputted name as a variable called?name.

  
  name = input("What's your name? "
  print("Hello", name))        

Notice that in our print statement, we don’t put quotations around our variable name. Notice also that we separate the string and the variable we want to print using a comma.

Our printed output would look the exact same as it did before.

No alt text provided for this image

When we store a name as a variable, we’re storing the?string?data type, which is just data that is composed of a set of characters which can be everything from letters and numbers to punctuation.

There are several other built-in data types we use in Python, examples of which are given in the snippet below.

  
  #N.B: Not all stored data is necessarily correc
  	
  
  name = "Ada Lovelace" #string
  grade_on_test = 'A' #character
  birth_year = 1815   #integer
  favourite_number = 2.1 #float
  favourite_integers = [1, 1024, 1729] #array of integers
  favourite_icecream_flavours = ["raspberry", "pistachio", "vanilla"] #array of strings (i.e. list)
    
    empty = [] #empty arrayt        

More on List

The list is one of the most used data types there is, and so lists have their own built-in functions. The two most common functions are explained below.

  • Append: this will add an element to the end of a list.

Example:


favourite_icecream_flavours.append("mango")        

  • Pop: this will remove an element from a specified position (all elements in lists are numbered, starting from 0)

Example:


favourite_flavours.pop(0
#removes the first element of the list)        

Arithmetic and Logical Operations

Just like in mathematics, when we work with variables while programming, we can perform all sorts of operations on them.

Arithmetic Operations in Python

With numerical data, we can perform arithmetic operations. These are outlined in the following table.

No alt text provided for this image

NB: In Python, the equals sign signifies reassignment, not equality


For example, in Python, you can write:


x = x + 1         

The above statement would be incorrect as a mathematical equation, but in our code, it just increases whatever value x has by one.

Logical Operations in Python

With almost all types of data, we can perform logical operations. These are outlined in yet another table, shown below.

No alt text provided for this image

While the value returned after arithmetic operations is some number (e.g. the value of 2+3 is 5), the value outputted after logical statements is either true (2 + 3 == 5) or false (2 + 3 < 5).

Conditional Statements

Logical statements become very important when it comes to writing conditional statements. These statements are statements of the form,


if a is tru
   do b e        

Suppose you wanted to determine someone’s grade in a class. You could write a program that would take the user’s score — or percentage — in that class and then check to see if that percentage is within the boundaries for an A or a B or a C, or if it confers a failing grade (D or below).

    
    score = float(input("What was this student's score on the test?")
  	#the score is assumed to be a percentage value
  	
  
  	"""All inputs are stored as strings by default. We use the int() function
  	to store the score as a float instead.
  	"""  
  	
  
  	if score > 85:
  	    print("This student scored an A")
  	elif score > 65:
  	    print("This student scored a B")
  	elif score > 50:
  	    print("This student scored a C")
  	else:
  	    print("This student failed."))        

Let’s take a closer look at the conditional statements we’ve used in the code above. Each conditional statement checks to see if a certain condition is made. Checking each condition involves evaluating whether a logical operation is true or false.

The conditional statements each use one of the following keywords.

  • if: checks if a statement is true
  • elif?(short for else if): checks if a statement is true only if the previous statement is not true
  • else: precedes instructions for what to do if all statements are false

Loops

Suppose we wanted to do something tedious, like create a list of numbers from 1 to 100. We could type out such a list, writing every entry. We could append every entry individually as follows:


my_list.append(1
my_list.append(2)
my_list.append(3))        

Turns out, this method is even worse.

Thankfully, when we have to repeat the same step over and over again, we can write something called a loop. A loop will ensure that the same command is executed over and over again, the right number of times.

For loop

If we want some command to execute a certain number of times, we can use a?for loop.

For loops are of the following form:


for i in range(starting_number, ending_number
    execute command(s))        

The command in the above for loop will run as many times as the difference between the starting number and the ending number.

Suppose we wanted to write a for loop to add the numbers 1 to 100 to an list. We could do so as follows:


my_list = []
	

#for loop to add the numbers 1 through 100 to my list
	

for i in range(1, 101):
	my_list.append(i)
	    
print(my_list)        

When run, this code would have the following output:

No alt text provided for this image

While Loop

If we want some command to execute until a certain condition is met (or is broken) we can make use of a?while loop.

While loops use conditional statements or boolean statements, which we introduced in the previous section.

While loops are of the following form:


while condition == tru
    execute command(s)e        

Suppose we wanted to use a while loop to add another 100 numbers to the list we used before. We could write the following code to achieve this:

	
    my_list = []
  	
  
  	#for loop to add the numbers 1 through 100 to my list
  	
  
  	for i in range(1, 101):
  	    my_list.append(i)
  	
  
  	#while loop to add the next 100 numbers to my list
  	
  
  	counter = i
  	
  
  	while len(my_list) <= 200:
  	    my_list.append(counter)
  	    counter+= 1
  	
  
  	print(my_list)        

The output of this code is shown below:

No alt text provided for this image

For Loops Involving Lists

If we wanted to print just the numbers in our list, we could write the following code.

    
    my_list = []
  	
  
  	#for loop to add the numbers 1 through 100 to my list
  	
  
  	for i in range(1, 101):
  	    my_list.append(i)
  	
  
  	#while loop to add the next 100 numbers to my list
  	
  
  	counter = i
  	
  
  	while len(my_list) <= 200:
  	    my_list.append(counter)
  	    counter+= 1
  	
  
  	#for loop to print numbers in list
  	
  
  	for i in my_list:
  	    print(i)        

Running this code, we’d see the following on our terminal.

No alt text provided for this image

Functions

Functions are a way for us to group blocks of code together so that our code is more modular and easier to read, understand, and reuse. I’ve talked about their importance in another article, which I’ll link below.

Creating functions is super easy. Let’s return to the grading algorithm we wrote before.

The code we wrote was as follows:

    
    score = float(input("What was this student's score on the test?")
  	#the score is assumed to be a percentage value
  	
  
  	"""All inputs are stored as strings by default. We use the int() function
  	to store the score as a float instead.
  	"""  
  	
  
  	if score > 85:
  	    print("This student scored an A")
  	elif score > 65:
  	    print("This student scored a B")
  	elif score > 50:
  	    print("This student scored a C")
  	else:
  	    print("This student failed."))        

As a function, it would look like this instead:


def grade_student
  
  #we define our function above
	

  score = float(input("What was this student's score on the test?"))
  	
  
  if score > 85:
    print("This student scored an A")
  elif score > 65:
    print("This student scored a B")
  elif score > 50:
    print("This student scored a C")
  else:   print("This student failed.")

    	    
grade_student() 
#we call our function above so that it executes:        

So what changed?

We just added a simple preamble to box our code into the structure of a function. After we defined our function, we then called the function so that it would execute.

The structure of any Python function is as follows:


def function
    code function executes:        

Object-Oriented Programming in Python

When we write code that’s focused on functions, or procedures, we call that process procedural programming.

Instead of focusing on functions, however, we can also focus on?objects. When we do, it’s called object-oriented programming.

What are objects?

Objects in plain English are just things we can describe. It’s the same in programming.

Objects can share certain?attributes?and can do certain things, things we call?methods?in programming.

Let’s look at a clarifying example. An object could be a car. The attributes shared by cars include color, maximum speed, number of passenger seats, etc. The methods of cars include turning on, turning off, accelerating, decelerating, etc.

To construct a class in Python, we first define it using the keyword?class?followed by?def__init__(self, attribute 1, attribute 2, attribute 3, etc). Each attribute we define is attached to the class using the keyword?self.

For example, a class of cars could be written as follows:


define class
	class Car:
	   
	    def __init__(self, brand, color, manufacture_date)
	        self.brand = brand
	        self.color = color
	        self.manufacture_date = manufacture_date   
	        
	    #below is a method that returns a car's age
	    
	    def age(self):
	        today = datetime.date.today()
	        age = today.year - self.manufacture_date.year
	        return age         

We can create an object of this class as follows:


example_car = Car(
	"Mercedes", 
	"Black", 
	datetime.date(1992, 3, 12), # year, month, day
)        

When we create an object of a class, we say we have initialized it.

We can execute our custom class methods as follows:


example_car.age()        


That’s all! You now can begin your Python journey! Thank you for reading!

Shabi Rana

Professional Graphic Designer.

2 年

Good ??

回复
Naveed Akhter

Software Developer | C# | Web Forms | ASP.NET Core | .NET Framework | Oracle PL/SQL | MSSQL

2 年

It's Good for startup

Fawad Ahmad

Game Developer & Designer | Unity | 2D & 3D, VR | C# | VisionOS | Freelancer | Building Communities | Helping others

2 年

Good work

Muhammad Junaid Iqbal

Building products that turn ideas into revenue!

2 年

Thanks for sharing, keep learning and sharing ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了