Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Python cheatsheet for beginners
Vishnu Sivan
Vishnu Sivan

Posted on • Edited on

     

Python cheatsheet for beginners

Python is ranked #1 in the PYPL index. It is considered the simplest language ever made because of its code readability and simpler syntax. It also has the ability to express the concepts in fewer lines of code.

The richness of various AI and machine learning libraries such as NumPy, pandas, and TensorFlow treats python as one of the core requirements. If you are a data scientist or beginner in AI/machine learning then python is the right choice to start your journey.

Getting Started

In this section, we are trying to explore some of the basics of python programming.

Data Types

The data type is a specification of data that can be stored in a variable. It is helpful for the interpreter to make a memory allocation for the variable based on its type.

In python, everything is treated as classes and objects. So, data types are the classes and variables are their objects.
These are the various data types in python,

data types

Variables

Variables are reserved memory locations to store values. We can think of it as a location for storing our data. Variable name is a unique string used to identify the memory location in our program.

There are some rules defined for creating a variable in our program. It is defined as follows,

  • Variable name should be only one word and nor begin with a number.
  • Variable name contains only letters, numbers, and underscore (_) character (white spaces are not allowed and considered as two variables).
  • Variable name starting with an underscore (_) are considered as unuseful and should not be used again in the code.
var1 = 'Hello World'var2 = 16_unuseful = 'Single use variables'
Enter fullscreen modeExit fullscreen mode

Lists

List is a mutable ordered collection of items like dynamically sized arrays. It may not be homogeneous and we can create a single list with different data types like integers, strings and objects.

>>> companies = ["apple","google","tcs","accenture"]>>> print(companies)['apple', 'google', 'tcs', 'accenture']>>> companies.append("infosys")>>> print(companies)['apple', 'google', 'tcs', 'accenture', 'infosys']>>> print(len(companies))5>>> print(companies[2])tcs>>> print(companies[-2])accenture>>> print(companies[1:])['google', 'tcs', 'accenture', 'infosys']>>> print(companies[:1])['apple']>>> print(companies[1:3])  ['google', 'tcs']>>> companies.remove("infosys")>>> print(companies)["apple","google","tcs","accenture"]>>> companies.pop()>>> print(companies)["apple","google","tcs"]
Enter fullscreen modeExit fullscreen mode

Sets

Set is an unordered collection of elements without any repetition. It is quite useful for removing duplicate entries from a list effortlessly. It also supports various mathematical operations like union, intersection and difference.

>>> set1 = {1,2,3,7,8,9,3,8,1}>>> print(set1){1, 2, 3, 7, 8, 9}>>> set1.add(5)>>> set1.remove(9)>>> print(set1){1, 2, 3, 5, 7, 8}>>> set2 = {1,2,6,4,2} >>> print(set2){1, 2, 4, 6}>>> print(set1.union(set2))        # set1 | set2{1, 2, 3, 4, 5, 6, 7, 8}>>> print(set1.intersection(set2)) # set1 & set2{1, 2}>>> print(set1.difference(set2))   # set1 - set2{8, 3, 5, 7}>>> print(set2.difference(set1))   # set2 - set1{4, 6}
Enter fullscreen modeExit fullscreen mode

Dictionaries

Dictionary is a mutable unordered collection of items as key value pairs. Unlike other data types, it holds data in akey:value pair format instead of storing a single data. This feature makes it as a best data structure to map the json responses.

>>> # example 1>>> user = { 'username': 'Vishnu Sivan', 'age': 27, 'mail_id': 'codemaker2015@gmail.com', 'phone': '9961907453' }>>> print(user){'mail_id': 'codemaker2015@gmail.com', 'age': 27, 'username': 'Vishnu Sivan', 'phone': '9961907453'}>>> print(user['age'])27>>> for key in user.keys():>>>     print(key)mail_idageusernamephone>>> for value in user.values():>>>  print(value)codemaker2015@gmail.com27Vishnu Sivan9961907453>>> for item in user.items():>>>  print(item)('mail_id', 'codemaker2015@gmail.com')('age', 27)('username', 'Vishnu Sivan')('phone', '9961907453')>>> # example 2>>> user = {>>>     'username': "Vishnu Sivan",>>>     'social_media': [>>>         {>>>             'name': "Linkedin",>>>             'url': "https://www.linkedin.com/in/codemaker2015">>>         },>>>         {>>>             'name': "Github",>>>             'url': "https://github.com/codemaker2015">>>         },>>>         {>>>             'name': "Medium",>>>             'url': "https://codemaker2015.medium.com">>>         }>>>     ],>>>     'contact': [>>>         {>>>             'mail': [>>>                     "mail.vishnu.sivan@gmail.com",>>>                     "codemaker2015@gmail.com">>>                 ],>>>             'phone': "9961907453">>>         }>>>     ]>>> }>>> print(user){'username': 'Vishnu Sivan', 'social_media': [{'url': 'https://www.linkedin.com/in/codemaker2015', 'name': 'Linkedin'}, {'url': 'https://github.com/codemaker2015', 'name': 'Github'}, {'url': 'https://codemaker2015.medium.com', 'name': 'Medium'}], 'contact': [{'phone': '9961907453', 'mail': ['mail.vishnu.sivan@gmail.com', 'codemaker2015@gmail.com']}]}>>> print(user['social_media'][0]['url'])https://www.linkedin.com/in/codemaker2015>>> print(user['contact']) [{'phone': '9961907453', 'mail': ['mail.vishnu.sivan@gmail.com', 'codemaker2015@gmail.com']}]
Enter fullscreen modeExit fullscreen mode

Comments

  • Single-Line Comments — Starts with a hash character (#), followed by the message and terminated by the end of the line.
# defining the age of the userage = 27dob = ‘16/12/1994’ # defining the date of birth of the user
Enter fullscreen modeExit fullscreen mode
  • Multi-Line Comments — Enclosed in special quotation marks (“””) and inside that you can put your messages in multi lines.
"""Python cheatsheet for beginnersThis is a multi line comment"""
Enter fullscreen modeExit fullscreen mode

Basic Functions

  • print()The print() function prints the provided message in the console. Also, user can provide file or buffer input as the argument to print on the screen.

print(object(s), sep=separator, end=end, file=file, flush=flush)

print("Hello World")               # prints Hello World print("Hello", "World")            # prints Hello World?x = ("AA", "BB", "CC")print(x)                           # prints ('AA', 'BB', 'CC')print("Hello", "World", sep="---") # prints Hello---World
Enter fullscreen modeExit fullscreen mode
  • input()Theinput() function is used to collect the user input from the console. Note that, theinput() converts whatever you enter as input it into a string. So, if you provide your age as an integer value but the input() method return it as a string and developer needs to convert it as a integer manually.
>>> name = input("Enter your name: ")Enter your name: Codemaker>>> print("Hello", name)Hello Codemaker
Enter fullscreen modeExit fullscreen mode
  • len()Provides the length of the object. If you put string then gets the number of characters in the specified string.
>>> str1 = "Hello World">>> print("The length of the string  is ", len(str1))The length of the string  is 11
Enter fullscreen modeExit fullscreen mode
  • str()Used to convert other data types to string values.

str(object, encoding=’utf-8', errors=’strict’)

>>> str(123)123>>> str(3.14)3.14int()Used to convert string to an integer.>>> int("123")123>>> int(3.14)3
Enter fullscreen modeExit fullscreen mode

Conditional statements

Conditional statements are the block of codes used to change the flow of the program based of specific conditions. These statements are executed only when the specific conditions are met.

In Python, we use if, if-else, loops (for, while) as the condition statements to change the flow of the program based on some conditions.

  • if else statement
>>> num = 5>>> if (num > 0):>>>    print("Positive integer")>>> else:>>>    print("Negative integer")
Enter fullscreen modeExit fullscreen mode
  • elif statement
>>> name = 'admin'>>> if name == 'User1':>>>     print('Only read access')>>> elif name == 'admin':>>>     print('Having read and write access')>>> else:>>>     print('Invalid user')Having read and write access
Enter fullscreen modeExit fullscreen mode

Loop statements

Loop is a conditional statement used to repeat some statements (in its body) until a certain condition is met.

In Python, we commonly use for and while loops.

  • for loop
>>> # loop through a list>>> companies = ["apple", "google", "tcs"]>>> for x in companies:>>>     print(x)applegoogletcs>>> # loop through string>>> for x in "TCS":>>>  print(x)TCS
Enter fullscreen modeExit fullscreen mode

Therange() function returns a sequence of numbers and it can be used as a for loop control. It basically takes three arguments where second and third are optional. The arguments are start value, stop value, and a step count. Step count is the increment value of the loop variable for each iteration.

>>> # loop with range() function>>> for x in range(5):>>>  print(x)01234>>> for x in range(2, 5):>>>  print(x)234>>> for x in range(2, 10, 3):>>>  print(x)258
Enter fullscreen modeExit fullscreen mode

We can also execute some statements when the loop is finished using the else keyword. Provide else statement in the end of the loop with the statement needs to be executed when the loop is finished.

>>> for x in range(5):>>>  print(x)>>> else:>>>  print("finished")01234finished
Enter fullscreen modeExit fullscreen mode
  • while loop
>>> count = 0>>> while (count < 5):>>>  print(count)>>>  count = count + 101234
Enter fullscreen modeExit fullscreen mode

We can use else in the end of the while loop similar to the for loop to execute some statements when the condition becomes false.

>>> count = 0>>> while (count < 5):>>>  print(count)>>>  count = count + 1>>> else:>>>  print("Count is greater than 4")01234Count is greater than 4
Enter fullscreen modeExit fullscreen mode

Functions

A function is a block of reusable code that is used to perform a task. It is quite useful to implement modularity in the code and make the code reusable.

>>> # This prints a passed string into this function>>> def display(str):>>>  print(str)>>>  return>>> display("Hello World")Hello World
Enter fullscreen modeExit fullscreen mode

Exception Handling

Even though a statement is syntactically correct, it may cause an error while executing it. These type of errors are called Exceptions. We can use the exception handling mechanisms to avoid such kinds of issues.

In Python, we use try, except and finally keywords to implement exception handling in our code.

>>> def divider(num1, num2):>>>     try:>>>         return num1 / num2>>>     except ZeroDivisionError as e:>>>         print('Error: Invalid argument: {}'.format(e))>>>     finally:>>>         print("finished")>>>>>> print(divider(2,1))>>> print(divider(2,0))finished2.0Error: Invalid argument: division by zerofinishedNone
Enter fullscreen modeExit fullscreen mode

String manipulations

A string is a collection of characters enclosed with double or triple quotes (“,’’’) . We can perform various operations on the string like concatenation, slice, trim, reverse, case change and formatting using the built in methods likesplit(),lower(),upper(),endswith(),join() ,ljust(),rjust() andformat().

>>> msg = 'Hello World'>>> print(msg)Hello World>>> print(msg[1])e>>> print(msg[-1])d>>> print(msg[:1])H>>> print(msg[1:])ello World>>> print(msg[:-1])Hello Worl>>> print(msg[::-1])dlroW olleH>>> print(msg[1:5])ello>>> print(msg.upper())HELLO WORLD>>> print(msg.lower())hello world>>> print(msg.startswith('Hello'))True>>> print(msg.endswith('World'))True>>> print(', '.join(['Hello', 'World', '2021']))Hello, World, 2021>>> print(' '.join(['Hello', 'World', '2021']))Hello World 2021>>> print("Hello World 2021".split())['Hello', 'World', '2021']>>> print("Hello World 2021".rjust(25, '-'))---------Hello World 2021>>> print("Hello World 2021".ljust(25, '*'))Hello World 2021*********>>> print("Hello World 2021".center(25, '#'))#####Hello World 2021####>>> name = "Codemaker">>> print("Hello %s" % name)Hello Codemaker>>> print("Hello {}".format(name))Hello Codemaker>>> print("Hello {0}{1}".format(name, "2025"))Hello Codemaker2025
Enter fullscreen modeExit fullscreen mode

Regular Expressions

  • Import theregex module withimport re.
  • Create a Regex object with there.compile() function.
  • Pass the search string into thesearch() method.
  • Call thegroup() method to return the matched text.
>>> import re>>> phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')>>> mob = phone_num_regex.search('My number is 996-190-7453.')>>> print('Phone number found: {}'.format(mob.group()))Phone number found: 996-190-7453>>> phone_num_regex = re.compile(r'^\d+$')>>> is_valid = phone_num_regex.search('+919961907453.') is None>>> print(is_valid)True>>> at_regex = re.compile(r'.at')>>> strs = at_regex.findall('The cat in the hat sat on the mat.')>>> print(strs)['cat', 'hat', 'sat', 'mat']
Enter fullscreen modeExit fullscreen mode

Thanks for reading this article.

If you enjoyed this article, please click on the heart button ♥ and share to help others find it!

Python-cheatsheet.pdf

Originally posted on Medium -
Python cheatsheet for beginners

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Seasoned professional, forward looking software engineer with 4+ years of experience in creating and executing innovative solutions in immersive field to enhance business productivity.
  • Location
    Ernakulam, Kerala, India
  • Education
    Mar Athanasius College Kothamangalam
  • Work
    Game Development | Web Development | Mobile App Development | AI | AR, VR | Jumber, Jumbo Games
  • Joined

More fromVishnu Sivan

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp