Nitin Raturi
Nitin Raturi's Software Engineering Blog

Follow

Nitin Raturi's Software Engineering Blog

Follow
Python Syntax Cheatsheet: Loops, Functions, If-Else, and More

Photo by Mika Baumeister on Unsplash

Python Syntax Cheatsheet: Loops, Functions, If-Else, and More

Nitin Raturi's photo
Nitin Raturi
ยทMar 19, 2023ยท

11 min read

Table of contents

Python is a high-level programming language that is known for its simplicity and readability. Its syntax is designed to be intuitive and easy to learn, making it a popular choice for beginners and experienced programmers alike.

Python syntax is a set of rules that govern how the Python programming language is written and structured. These rules determine how code is written, the structure of the code, and the meaning of symbols and keywords used in the code.

๐Ÿ’ก Complete Python Roadmap for beginners and experts.

Syntax rules

Rule 1 - Statement

In python, a statement is a single instruction that is executed by the interpreter. It typically performs an action or calculates a value, such as assigning a value to a variable, calling a function, or printing a message to the console.

x = 10

On the other hand, a code block is a group of statements that are executed together as a single unit. A code block is typically delimited by indentation, which is a series of spaces or tabs at the beginning of each line.

if x > 5:
    print("Nitin is younger than Ram")
    print("Good job!")
else:
    print("Ram is younger than Nitin")

Rule 2 - Indentation

Python uses indentation to define code blocks. All the statements in a code block must have the same level of indentation. The standard indentation level is 4 spaces.

if x > 0:
    print("x is positive")
else:
    print("x is non-positive")

In this example, the if-else statement is a code block, and all the statements inside it are indented by four spaces. The indentation is used to group the statements together.

Now you know the syntax rules, let's see the syntax for other elements in python.

Python Syntax Cheatsheet

Here is a Python syntax cheat sheet that summarizes the main syntax rules in python.

Comments Syntax

In Python, there are two types of comments: single-line comments and multi-line comments. Single-line comments start with the '#' symbol and continue until the end of the line. For example:

# This is a single-line comment

In the above example, the comment explains what the code does. Multi-line comments, also known as block comments, start and end with three quotes (''') and can span multiple lines. For example:

'''
This is a multi-line comment.
It can span multiple lines.
'''

In the above example, the comment is enclosed in three quotes at the beginning and end, and it explains what the code does in multiple lines. You can also use multi-line strings as comments, by enclosing the string in triple quotes, but not assigning it to a variable. For example:

"""
This is a multi-line string that is used as a comment.
It can span multiple lines.
"""

In the above example, the string is enclosed in three quotes, and it can be used as a comment because it is not assigned to a variable.

Variables Syntax

The syntax for creating a variable in Python is to assign a value to a name using the assignment operator (=). The name of the variable must follow the rules for valid Python identifiers. Python will automatically assign the appropriate data type based on the value that you assign to the variable.

Examples of valid variable syntax in Python include:

x = 10
my_variable = "Hello, world!"
_myVar = 3.14

You can also assign multiple values to multiple variables in a single statement using the following syntax:

variable1, variable2, variable3 = value1, value2, value3

In this syntax, the values on the right-hand side are assigned to the variables on the left-hand side in the order they are listed.

Finally, you can use the del keyword to delete a variable and its associated value from memory:

del variable_name

Operators Syntax

This example demonstrates the use of all six types of operators in Python, including arithmetic operators, comparison operators, logical operators, assignment operators, membership operators, and identity operators.

# Arithmetic operators
x = 10
y = 3
print(x + y)   # output: 13
print(x - y)   # output: 7
print(x * y)   # output: 30
print(x / y)   # output: 3.3333333333333335
print(x % y)   # output: 1
print(x ** y)  # output: 1000
print(x // y)  # output: 3

# Comparison operators
print(x == y)  # output: False
print(x != y)  # output: True
print(x < y)   # output: False
print(x > y)   # output: True
print(x <= y)  # output: False
print(x >= y)  # output: True

# Logical operators
a = True
b = False
print(a and b) # output: False
print(a or b)  # output: True
print(not a)   # output: False

# Assignment operators
z = 5
z += 3
print(z)       # output: 8

# Membership operators
string = "hello world"
print('h' in string)     # output: True
print('z' not in string) # output: True

# Identity operators
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 is list2)    # output: False
print(list1 is not list2)# output: True

Control Flow Syntax

Control flow statements are used to alter the execution of a program based on certain conditions. There are three types of control flow statements in Python: conditional statements (if and else), loop statements (for and while), and jump statements (break and continue).

If and Else Syntax

In Python, if and else are conditional statements used to execute different blocks of code based on whether a certain condition is true or false.

x = 10
y = 10

if x > y:
    print("x is greater than y")
elif x == y:
    print("x is equal to y")
else:
    print("y is greater than x")

For Loop Syntax

In Python, for loop is used to iterate over a sequence of elements such as a list, tuple, string, or any other iterable object. The basic syntax for using for loop in Python is:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

In this example, fruits is a list of strings. The for loop iterates over each element in the list, and for each element, the value of fruit variable is printed.

While Loop Syntax

In Python, while loop is used to repeatedly execute a block of code as long as a certain condition is true.

count = 0
while count < 5:
    print(count)
    count += 1

In this example, count is initialized to 0. The while loop will execute the code block inside as long as count is less than 5.

๐Ÿ’ก [Optional] Refer to install python and virtual environment guide.

Jump Statement Syntax

Jump statement is a statement that allows the program to transfer control to a different part of the program.

Break Syntax

In Python, the break statement is used to immediately exit a loop.

count = 0
while count < 5:
    print(count)
    count += 1
    if count == 3:
        break

In this example, count is initialized to 0. The while loop will be terminated as soon as count becomes 3.

Continue Syntax

In Python, the continue statement is used to skip the current iteration of a loop and continue with the next iteration.

count = 0
while count < 5:
    count += 1
    if count == 3:
        continue
    print(count)

In this example, count is initialized to 0. The while loop will execute the code block inside as long as count is less than 5. When count is equal to 3, the if statement is true, and continue is executed, skipping the print(count) statement for that iteration only.

Data Types Syntax

Here are some common data types in Python and their syntax

Integer Syntax

An integer is a whole number without a decimal point

# Hexadecimal representation
my_int = 0xFF

# Binary representation
my_int = 0b1010

# Octal representation
my_int = 0o17

Float Syntax

A float is a number with a decimal point.

# Scientific notation
my_float = 3e-2  # 0.03

# Infinity and Not a Number (NaN)
my_float = float('inf')
my_float = float('nan')

String Syntax

A string is a sequence of characters.

# Multiline string
my_string = '''Hello,
world!'''

# String concatenation
my_string = "Hello, " + "world!"

# String formatting
my_string = "My name is {} and I'm {} years old.".format("John", 30)

Boolean Syntax

A boolean is a value that can either be True or False.

# Boolean evaluation of an expression
my_bool = 2 + 2 == 4  # True

# Negation of a boolean value
my_bool = not True  # False

List Syntax

A list is a collection of values that can be of different data types.

# List slicing
my_list = [1, 2, 3, 4, 5]
my_slice = my_list[1:4]  # [2, 3, 4]

# List comprehension
my_list = [x**2 for x in range(10)]

# Modifying list elements
my_list[0] = "new value"

Tuple Syntax

A tuple is similar to a list, but it is immutable, meaning it cannot be changed after it is created.

# Tuple packing and unpacking
my_tuple = 1, "two", 3.0, True
a, b, c, d = my_tuple

# Tuple concatenation
my_tuple = (1, 2, 3) + (4, 5, 6)

Dictionary Syntax

A dictionary is a collection of key-value pairs.

# Dictionary comprehension
my_dict = {x: x**2 for x in range(10)}

# Adding or modifying dictionary elements
my_dict["new_key"] = "new value"
my_dict["existing_key"] = "modified value"

Exception Handling Syntax

Exception handling is an important feature in Python that allows you to handle errors that may occur during the execution of your code. Here is an example of the basic syntax for exception handling in Python:

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)
except ValueError:
    print("Invalid input. Please enter integers only.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Division successful.")
finally:
    print("Program complete.")

Let's break down each part of this syntax:

  • try: This is the start of the try block, where you place the code that may raise an exception.

  • except ExceptionType: This block is executed if an exception of type ExceptionType is raised. You can specify the specific type of exception you want to handle, or you can use a general except block to handle all types of exceptions.

  • else: This block is executed if no exceptions are raised in the try block. It's optional and can be omitted if you don't need it.

  • finally: This block is always executed, regardless of whether an exception was raised or not. It's used to clean up resources and perform other finalization tasks.

File Handling Syntax

File handling in Python allows you to read from and write to files on your computer. Here is an example of the basic syntax for file handling in Python:

# Open a file for reading
with open("myfile.txt", "r") as file:
    contents = file.read()
    print(contents)

# Open a file for writing
with open("myoutput.txt", "w") as file:
    file.write("Hello, world!")
    file.write("\n")
    file.write("How are you?")

Let's break down each part of this syntax:

  • with open("filename.txt", "r") as file: This line opens a file called "filename.txt" in read mode ("r") using the open() function. The file is then assigned to the variable file. The with statement ensures that the file is properly closed after we're done using it.

  • with open("filename.txt", "w") as file: This line opens a file called "filename.txt" in write mode ("w") using the open() function. The file is then assigned to the variable file. If the file already exists, it will be truncated (i.e., all contents will be deleted). If it doesn't exist, a new file will be created.

  • file.read(): This method reads the entire contents of the file and returns them as a string. You can also specify the number of bytes you want to read, like this: file.read(10).

  • file.readline(): This method reads a single line from the file and returns it as a string. You can call it multiple times to read multiple lines.

  • file.readlines(): This method reads all lines from the file and returns them as a list of strings.

  • file.write("text"): This method writes the string "text" to the file. You can also write multiple strings by calling this method multiple times.

  • file.writelines(["text1", "text2"]): This method writes a list of strings to the file.

Class and Objects Syntax

class Animal:
    def __init__(self, species, name, age):
        self.species = species
        self.name = name
        self.age = age

    def make_sound(self):
        pass

    @property
    def is_adult(self):
        return self.age >= 3

class Dog(Animal):
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

my_dog = Dog("Canine", "Buddy", 2)
my_cat = Cat("Feline", "Whiskers", 4)

print(my_dog.species)   # Output: Canine
print(my_cat.species)   # Output: Feline
print(my_dog.is_adult)  # Output: False
print(my_cat.is_adult)  # Output: True
print(my_dog.make_sound())  # Output: Woof!
print(my_cat.make_sound())  # Output: Meow!

In this example, we've defined a base class Animal with an init method that takes three arguments (species, name, and age) and assigns them to instance variables with the same names (self.species, self.name, and self.age). The make_sound method is defined to be overridden by the subclasses.

The @property decorator is used to define a is_adult property that returns True if the age of the animal is greater than or equal to 3.

We then define two subclasses of Animal called Dog and Cat, each with their own implementation of the make_sound method.

We create an instance of the Dog class called my_dog and an instance of the Cat class called my_cat, passing in the appropriate arguments to the init method.

We then access the instance variables species of my_dog and my_cat using dot notation, and call the is_adult property to check if each animal is an adult.

Finally, we call the make_sound method on each animal to hear their respective sounds.

This example showcases many of the core concepts of OOP in Python, including inheritance, encapsulation, and polymorphism.

In conclusion, understanding Python syntax is essential for writing effective and efficient code in the language. While each of these topics has its own specific syntax and nuances, mastering them can greatly enhance your ability to write Python programs. With practice and attention to detail, you can become proficient in Python syntax and develop code that is both clear and concise.

๐Ÿ’ก Complete Python Roadmap for beginners and experts.

Did you find this article valuable?

Support Nitin Raturi by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this