Python Cheat Sheet - Studyopedia

Python Cheat Sheet

The Python Cheat Sheet will guide you to work on Python with basics and advanced topics. Cheat Sheet for students, engineers, and professionals.

Introduction

Python is a powerful, interpreted, object-oriented programming language. It is used in many areas for development and is considered a perfect language for scripting.

Features of Python

  • Cross-platform
  • Open Source
  • Multiple Programming-paradigms
  • Fewer lines of code
  • Powerful Libraries

Install and Run Python

Python can be easily installed on any OS. You can also use any of the below platforms to run Python:

Variables

Variables in Python are reserved memory locations. You only need to assign a value in Python, for variable declaration and that’s it!

val1 = 6;
val2 = 10;
 
#sum
val3 = val1 + val2;
 
print val3;

Scope of Variables

The existence of a variable in a region is called its scope, or the accessibility of a variable defines its scope:

  • Local Scope: Whenever a variable is defined in a function, it can be used only in that function.
  • Global Scope: A variable has Global Scope, if it’s created outside the function i.e. the code body, and is accessible from anywhere.
  • GLOBAL keyword: To change the value of a global variable inside the function, use the GLOBAL keyword

Tokens

Python Tokens are individual units in a program. The following are the types of Tokens:

  • Keywords: Keywords are reserved words used in programming languages, for example, if, else, not, continue, return, try, etc.
  • Identifiers: Identifiers in Python are used for naming variables, functions, and arrays. Do not use keywords as identifiers.
  • Literals: Literals are the values assigned to each constant variable:
    • String Literals: Enclose the text in quotes. We can use both single as well as double quotes. Use triple quotes for multi-line strings.
    • Numeric Literals: Includes int, long, float, and complex.
    • Boolean Literals: Can have either True or False values

Operators

Python Operators perform operations by taking one or more values, to give another value. The following are the operators:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison/ Relational operators
  • Identity Operators
  • Membership Operators
  • Bitwise Operators

Type Conversion

Type Conversion in Python allows users to convert int type to another, for example, float to int, int to complex, int to float, etc. To convert a number from one type to another, for example, int to float, we have the following methods in Python:

  • float(num): To convert from num int to float type.
  • int(num): To convert num to int type.
  • long(num): To convert num to long type.
  • complex(num): To convert from num int to complex type.
  • Complex (num1, num2): To convert num1 and num2 to complex type where num1 will be the real part, whereas num2 will be the imaginary part with j.

Get User Input

With Python, easily get user input, instead of hard coding the values. Similar to Java, C++, and C, Python also supports the concept of user input. The input() method in Python is used to get input from the user.

# student name
sname = input("Enter student name: ")
print("\nStudent Name = " + sname)

Output

Enter student name: Amit
Student Name = Amit

Decision-Making Statements

Take decisions based on different conditions in Python:

  • if statement
    if condition:
        code will execute if condition is true;
  • if-else statement
    if condition:
        code will execute if condition is true
    else:
        code will execute if condition is false
    
  • if…elif…else statement
    if condition1:
        code will execute if condition is true
    elif condition2:
        code will execute if another condition is true
    elif condition3:
        code will execute if above conditions aren’t true
    else:
        code will execute if all the above given conditions are false
  • break statement: The current loop is terminated and the execution of the program aborted. After termination, the control reaches the next line after the loop.
    break;
  • continue statement: The continue statement in Python transfers control to the conditional expression and jumps to the next iteration of the loop.
    continue;

Loops

Loops execute a block of code and this code executes while the condition is true:

  • while loop
    while (condition is true):
      code
  • for loop

    for var in sequence:
      code

Numbers

To store Number types, such as integers, floats, etc., In Python3, Numbers include int, float, and complex datatypes,

# int datatype
val1 = 1    
val2 = 100
print("Value 1 (Integer): ",val1)
print("Value 2 (Integer): ",val2)
 
# float datatype
val3 = 6.7
val4 = 5E3
print("Value 3 (Float): ",val3)
print("Value 4 (Float): ",val4)
 
# complex datatype
val5 = 1j 
val6 = 3.25+6.30j
print("Value 5 (Complex):",val5)
print("Value 6 (Complex):",val6)

Output

Value 1 (Integer):  1
Value 2 (Integer):  100
Value 3 (Float):  6.7
Value 4 (Float):  5000.0
Value 5 (Complex): 1j
Value 6 (Complex): (3.25+6.3j)

Strings

Strings in Python are sequences of characters that can be easily created:

  • Create a String:
    str = 'My name is Amit!'
  • Slicing to access substrings:
    str[7:10]
  • Accessing a character:

    str[9]
  • Concatenate Strings:

    str1 + str2
  • String Operators:String Operators in Python

Functions

A function in Python is an organized block of reusable code, that avoids repeating the tasks. Functions in Python begin with the keyword def and are followed by the function name and parentheses.

  • Create a Function:
    def function_name( parameters ):
        function_suite
        return [expression]
  • Function Parameters:
    def function_name(parameter1, parameter2, … ):

Lambda Functions

A lambda function is a function without a name i.e. an anonymous function. The keyword lambda is used to define a lambda function in Python and has only a single expression.

lambda arguments: expressions

Multiply a number by an argument with lambda:

val = lambda i: i *2
print("Result = ",val(25)) // Result = 50

Classes & Objects

A class is the basis of object-oriented programming in Python. A class is a template for an object, whereas an object is an instance of a class. Example of a Class:

class Studyopedia:
  val = 100
 
print(Studyopedia) // <class '__main__.Studyopedia'>

Example of Objects:

# creating a class with a property val
# the class keyword is used to create a class
class Studyopedia:
  val = 100
 
print(Studyopedia)
 
# object ob
ob = Studyopedia()
 
# displaying the value using the object ob
print("Value = ",ob.val)

Output

<class '__main__.Studyopedia'>
Value =  100

Tuples

Tuple is a sequence in Python, a collection of objects. Also, Python Tuples are immutable i.e. you cannot update a tuple or any of its elements.

  • Create a Tuple with string elements:
    mytuple = ("Amit", "Craig", "Ronaldo", "Messi")
  • Create a Tuple with int elements:
    mytuple2 = (10, 20, 50, 100)
    
  • Access values in a Tuple:
    #First item
    mytuple[0]
     
    #Second item
    mytuple[1]
  • Fetch a specific element with indexing in Tuples:
    Fetch a specific element at 1st position: mytuple[0]
    Fetch a specific element at 2nd position: mytuple[1]
    Fetch a specific element at 3rd position: mytuple[2]
    Fetch a specific element at 4th position: mytuple[3]
  • Length of Tuple:
    len(mytuple)
  • Get the maximum value from a Tuple:
    max(mytuple)
  • Get the minimum value from a Tuple:
    min(mytuple)

Dictionary

The dictionary represents the key-value pair in Python, enclosed in curly braces. Keys are unique and a colon separates them from value, whereas a comma separates the items.

  • Create a Dictionary:

    mystock = {"Product": "Earphone", "Price": 800, "Quantity": 50}
    

    Python Dictionary

  • Access values in a Dictionary:

    mystock["Product"]
  • Print all the keys of a Dictionary:

    mystock.keys()
  • Print all the values of a Dictionary:

    mystock.values()
  • Get the length of a Dictionary:

    len(mystock)

Lists

Lists in Python are ordered. It is modifiable and changeable, unlike Tuples.

Python Tuples vs Python Lists

  • Create a List with int elements:
    mylist = [25, 50, 75, 100, 125, 150, 175, 200 ];
  • Create a List with string elements:
    mylist = ["Nathan", "Darren", "Blair", "Bryce", "Stacey" ];
  • Access values from a List:
    print(mylist[2])
  • Indexing in Lists:
    Fetch a specific element at 1st position: mylist[0]
    Fetch a specific element at 2nd position: mylist[1]
    Fetch a specific element at 3rd position: mylist[2]
    Fetch a specific element at 4th position: mylist[3]
  • Get the length of a List:

    len(mylist)
  • Get the maximum from a List:
    max(mylist)
  • Get the minimum from a List:

    min(mylist)

Sets

A Set is a collection in Python. Set items i.e. elements are placed inside curly braces {}:

  • Create a Set with int elements
    myset = {"amit", "john", "kane", "warner", "steve"}
  • Create a Set with string elements

    myset2 = {5, 10, 15, 20, 25, 30}
  • Get the length of a Set

    len(myset)
  • Return the difference between the two sets:

    res = myset1.difference(myset2)
  • Keep only the duplicate items in the two sets:

    myset1.intersection_update(myset2)
  • Keep all the items in the two sets except the duplicates:

    myset1.symmetric_difference_update(myset2)
  • Union of Sets

    res = myset1.union(myset2)

Modules

The modules in Python are used to organize the code. We can easily import a module in Python using the import statement:

import module1,module2, module3 ... module n

Example:

import math

Here are the types of modules:

  • math: The math module in Python is used to perform mathematical tasks, with functions, including, trigonometric, logarithmic, etc:
    import math
  • statistics:
    The statistics module in Python is used to perform statistical tasks, with statistical functions, including, mean, median, mode, stdev(), etc.

    import statistics
  • random
    The random module in Python is used to form random numbers. Here, we will see how to import a random module in a Python program.

    import random

Learn Python via video course (English)

Learn Python via video course (Hindi)

What next?

After completing Python, follow the below tutorials and learn Python Libraries:

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Python Programming Examples
Python Online Quiz
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment