25 Jul 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:
- Install Python on Windows
- Run Python on VS Code
- Run Python on Google Colab
- Run Python on Anaconda
- Run Python on PyCharm IDE Community Edition
Variables
Variables in Python are reserved memory locations. You only need to assign a value in Python, for variable declaration and that’s it!
1 2 3 4 5 6 7 8 9 |
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.
1 2 3 4 5 |
# student name sname = input("Enter student name: ") print("\nStudent Name = " + sname) |
Output
1 2 3 4 |
Enter student name: Amit Student Name = Amit |
Decision-Making Statements
Take decisions based on different conditions in Python:
- if statement
1234if condition:code will execute if condition is true; - if-else statement
123456if condition:code will execute if condition is trueelse:code will execute if condition is false - if…elif…else statement
12345678910if condition1:code will execute if condition is trueelif condition2:code will execute if another condition is trueelif condition3:code will execute if above conditions aren’t trueelse: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.
123break; - continue statement: The continue statement in Python transfers control to the conditional expression and jumps to the next iteration of the loop.
123continue;
Loops
Loops execute a block of code and this code executes while the condition is true:
- while loop
1234while (condition is true):code - for loop
1234for var in sequence:code
Numbers
To store Number types, such as integers, floats, etc., In Python3, Numbers include int, float, and complex datatypes,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# 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
1 2 3 4 5 6 7 8 |
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:
123str = 'My name is Amit!' - Slicing to access substrings:
123str[7:10] - Accessing a character:
123str[9] - Concatenate Strings:
123str1 + str2 - String Operators:
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:
12345def function_name( parameters ):function_suitereturn [expression] - Function Parameters:
123def 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.
1 2 3 |
lambda arguments: expressions |
Multiply a number by an argument with lambda:
1 2 3 4 |
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:
1 2 3 4 5 6 |
class Studyopedia: val = 100 print(Studyopedia) // <class '__main__.Studyopedia'> |
Example of Objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# 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
1 2 3 4 |
<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:
123mytuple = ("Amit", "Craig", "Ronaldo", "Messi") - Create a Tuple with int elements:
123mytuple2 = (10, 20, 50, 100) - Access values in a Tuple:
1234567#First itemmytuple[0]#Second itemmytuple[1] - Fetch a specific element with indexing in Tuples:
123456Fetch 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:
123len(mytuple) - Get the maximum value from a Tuple:
123max(mytuple) - Get the minimum value from a Tuple:
123min(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:
123mystock = {"Product": "Earphone", "Price": 800, "Quantity": 50}
- Access values in a Dictionary:
123mystock["Product"] - Print all the keys of a Dictionary:
123mystock.keys() - Print all the values of a Dictionary:
123mystock.values() - Get the length of a Dictionary:
123len(mystock)
Lists
Lists in Python are ordered. It is modifiable and changeable, unlike Tuples.
- Create a List with int elements:
123mylist = [25, 50, 75, 100, 125, 150, 175, 200 ]; - Create a List with string elements:
123mylist = ["Nathan", "Darren", "Blair", "Bryce", "Stacey" ]; - Access values from a List:
123print(mylist[2]) - Indexing in Lists:
123456Fetch 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:
123len(mylist) - Get the maximum from a List:
123max(mylist) - Get the minimum from a List:
123min(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
123myset = {"amit", "john", "kane", "warner", "steve"} - Create a Set with string elements
123myset2 = {5, 10, 15, 20, 25, 30} - Get the length of a Set
123len(myset) - Return the difference between the two sets:
123res = myset1.difference(myset2) - Keep only the duplicate items in the two sets:
123myset1.intersection_update(myset2) - Keep all the items in the two sets except the duplicates:
123myset1.symmetric_difference_update(myset2) - Union of Sets
123res = 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:
1 2 3 |
import module1,module2, module3 ... module n |
Example:
1 2 3 |
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:
123import math - statistics:
The statistics module in Python is used to perform statistical tasks, with statistical functions, including, mean, median, mode, stdev(), etc.
123import 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.
123import random
Learn Python via video course (English)
Learn Python via video course (Hindi)
What next?
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
No Comments