Python Cheat Sheet! For beginners

Python Cheat Sheet! For beginners

In this article we are going to understand the simplest and quick way to learn python By this Cheat Sheet!

Getting Started

Python is a popular general-purpose programming language that can be used for a wide variety of applications. It includes high-level data structures, dynamic typing, dynamic binding, and many more features that make it useful for complex application development.

It is a super beginner-friendly language.

Data Type

We will talk about the most used data type only!

Every value in python is called "Python". And every object has a specific data type.

The Three most-used data type are as follow:

Integer (int) : This data type is used to represent integer value i.e -2,-1,0,1,2.

Floating-point (float): It is used to represent the floating(decimal) numbers i.e 1.3, 2.66, -8.99.

Strings: In Python, a string is a sequence of Unicode characters. For example the word "python". and is immutable in python that means if you already defined it, you cannot change it later on but you can modify it with the help of functions like replace(), join(), etc.

strings --> 'hi', 'Hello World', "Hi Today is 18th May".

Another three data types are worth mentioning. these data types are list, dictionary, and tuples. we will discuss them also.

string.PNG

You can create a string in three ways using single, double, and triple quotes. Let's understand with an example

Basic Python String:

my_string = "using double quote"
another_string = 'using single quote'
long_string = '''This is long string. you can extend this string in multiple lines also there will be no problem!'''

You can choose any method to use a string in your program!

Now To output anything like int, string you have to use the print() function Example :

print("let's print out this function!")

String concatenation: It is a way to add two or more strings together using the + operator. Here's how it's done!

string1 = "Hello"
string2 = " My Name is Nishant!"

string3 = string1 + string2

Output: Hello My Name is Nishant!

Note: you can not apply + operator to two different data types like a string + int

String Replication:

This command lets you repeat the same string several times. This is done by * operator. This replication functionality can be achieved by this operator only and only on the string data type.

string = "Nishant"
print(string*3)

Output: NishantNishantNishant

Maths Operator

For reference, here is the list of other math operations you can apply towards numbers:

mathoperator.png

How To Store Strings in Variable:

Variables in python are the object that assigns a specific storage location to a value that's tied to it.

Storing string in a variable makes it easier to deal with the complex problem and it also helps us to assess the same string multiple times.

Syntax:

we have also used this syntax in the above example.

string = "This is my string"

builtin.PNG

You already know the most popular function in Python — print(). Now let’s take a look at its equally popular cousins that are in-built in the platform.

input() Function:

input() function is a simple way to prompt the user for some input (e.g. provide their name). All user input is stored as a string. Syntax:

name = input(“Hi! What’s your name? “)
print("Nice to meet you " + name + "!")
age = input(“How old are you “)
print("So, you are already " + str(age) + " years old, "+ name + "!")

Output: Hi! What’s your name? “Nishant”
Nice to meet you, Nishant!
How old are you? 21
So, you are already 21 years old, Nishant!

len() Function:

len() function helps you find the length of any string, list, tuple, dictionary, or another data type. It’s a handy command to determine excessive values and trim them to optimize the performance of your program.

string1 = "Hope you are having fun with learning"
print("The length  of the string is",len(string1))

Output: The length of the string is 37

There are many other built In functions Here is the list of them. For More Detail

builtinfucntion.PNG

functions.PNG

Apart from using in-built functions, Python also allows you to define your own functions for your program. To recap, a function is a block of coded instructions that perform a certain action. Once properly defined, a function can be reused throughout your program i.e. re-use the same code. Here’s a quick walkthrough explaining how to define a function in Python: First, use the def keyword followed by the function name():. The parentheses can contain any parameters that your function should take (or stay empty).

def name():

Next, you’ll need to add a second code line with a 4-space indent to specify what this function should do

def name():
     print(“What’s your name?”)

Now, you have to call this function to run the code

Name.py

def name():
    print(“What’s your name?”)
name()

Now, let’s take a look at a defined function with a parameter — an entity, specifying an argument that a function can accept.

def sum(x, y, z):
     a = x + y
     b = x + z
     c = y + z
     print(a, b, c)
sum(1, 2, 3)

Output: a = 1 + 2 b = 1 + 3 c = 2 +

How to Pass Keyword Arguments to a Function

A function can also accept keyword arguments. In this case, you can use parameters in random order as the Python interpreter will use the provided keywords to match the values to the parameters. Here’s a simple example of how you pass a keyword argument to a function.

# Define function with parameters
def product_info(product name, price):
     print("productname: " + product name)
     print(“Price “ + str(dollars))
# Call function with parameters assigned as above
product_info("White T-shirt", 15 dollars)
# Call function with keyword arguments
product_info(productname=”jeans”, price=45)

Output: Productname: White T-shirt
Price: 15
Productname: Jeans
Price: 45

list.PNG

Lists are another cornerstone data type in Python used to specify an ordered sequence of elements. In short, they help you keep related data together and perform the same operations on several values at once. Unlike strings, lists are mutable (=changeable).

Each value inside a list is called an item and these are placed between square brackets.

Example:

my_list = [1, 2, 3]
my_list2 = ["a","b","c"]
my_list3 = ["4", d, "book", 5]

Alternatively, you can use the list() function to do the same:

list1 = list(("1", "2", "3"))
print(list1)

How to Add Items to a List

You have two ways to add new items to existing lists. The first one is using the append() function:

list1 = ["apple", "banana", "orange"]
list1.append("grape”")
print(list1)

The second option is to insert() function to add an item at the specified index:

insert(index,element)

list2 = ["apple", "banana", "orange"]
list2.insert(2, "grape")
print(list2)

How to Remove an Item from a List

Again, you have several ways to do so. First, you can use the remove() function:

list = ["apple", "banana", "orange"]
list.remove("apple")
print(list)

Secondly, you can use the pop() function. If no index is specified, it will remove the last item

list = ["apple", "banana", "orange"]
list.pop()
print(list)

The last option is to use a del keyword to remove a specific item:

list = ["apple", "banana", "orange"]
del list [1]
print(list)

Sort a List Use the sort() function to organize all items in your list

list = [34, 23, 67, 100, 88, 2]
list.sort()
print(list)
# output [2, 23, 34, 67, 88, 100]

Slice a List: Now, if you want to call just a few elements from your list (e.g. the first 4 items), you need to specify a range of index numbers separated by a colon [x:y]. Here’s an example:

list[0:4]
# output [2, 23, 34, 67]

Change Item Value on Your List You can easily overwrite a value of one list items:

list = ["apple", "banana", "orange"]
list[1] = "pear"
print(list)

output [‘apple’, ‘pear’, ‘cherry’]

Loop Through the List

Using for loop you can multiply the usage of certain items, similarly to what * operator does. Here’s an example:

for x in range(1,4):
   beta_list += [‘fruit’]
   print(beta_list)

tuple.PNG

Tuples are similar to lists — they allow you to display an ordered sequence of elements. However, they are immutable and you can’t change the values stored in a tuple. The advantage of using tuples over lists is that the former is slightly faster. So it’s a nice way to optimize your code.

How to create a Tuple

my_tuple = (1, 2, 3, 4, 5)
my_tuple[0:3]
(1, 2, 3)

Note: Once you create a tuple, you can’t add new items to it or change it in any other way

looping is the same as List

Convert Tuple into list Since Tuples are immutable, you can’t change them. What you can do though is convert a tuple into a list, make an edit and then convert it back to a tuple. Here’s how to accomplish this:

x = (“apple”, “orange”, “pear”)
y = list(x)
y[1] = “grape”
x = tuple(y)
print(x)

dict.PNG

A dictionary holds indexes with keys that are mapped to certain values. These key-value pairs offer a great way of organizing and storing data in Python. They are mutable, meaning you can change the stored information. A key value can be either a string, Boolean, or integer. Here’s an example dictionary illustrating this:

Customer1= {‘username’: ‘john-sea’, ‘online’: false,‘friends’:100}

How to Create a Python Dictionary

Here’s a quick example showcasing how to make an empty dictionary. Option 1: new_dict = {} Option 2: other_dict= dict()

And you can use the same two approaches to add values to your dictionary:

new_dict = { "brand": "Honda",
 "model": "Civic",
 "year": 1995
}
print(new_dict)

How to Access a Value in a Dictionary You can access any of the values in your dictionary the following way

x = new_dict["brand"]

You can also use the following methods to accomplish the same.

  • dict.keys() isolates keys
  • dict.values() isolates values
  • dict.items() returns items in a list format of (key, value) tuple pairs

Change Item Value: To change one of the items, you need to refer to it by its key name:

#Change the “year” to 2021:
new_dict= {
 “brand”: “Honda”,
 “model”: “Civic”,
 “year”: 1995
}
new_dict[“year”] = 2021

if.PNG

Just like other programming languages, Python supports the basic logical conditions from math:

Equals: a == b

  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to a <= b
  • Greater than a > b
  • Greater than or equal to a >= b

If Statement Example

if 5 > 1:
      print("That’s True!")

Output: That’s True!

Nested If

For more complex operations, you can create nested if statements. Here’s how it looks:

x = 35
if x > 20:
     print(“Above twenty,”)
     if x > 30:
           print(“and also above 30!”)

If Else Statements

else keyword helps you add some additional filters to your condition clause. Here’s how an if-elif-else combo looks:

if age < 4:
   ticket_price = 0
elif age < 18:
   ticket_price = 10
else: 
   ticket_price = 15

Python Loops

Python has two simple loop commands that are good to know:

  • for loops
  • while loops

Let’s take a look at each of these.

For Loop As already illustrated in the other sections of this Python checklist, for loop is a handy way for iterating over a sequence such as a list, tuple, dictionary, string, etc. Here’s an example showing how to loop through a string:

for x in "apple":
   print(x)

Plus, you’ve already seen other examples for lists.

While Loops

While loop enables you to execute a set of statements as long as the condition for them is true

#print as long as x is less than 8
i = 1
while i< 8:
      print(x)
      i += 1

How to Break a Loop You can also stop the loop from running even if the condition is met. For that, use the break statement both in while and for loops:

i = 1
while i < 8:
   print(i)
   if i == 4:
        break
   i += 1

All the Basic Concepts had been covered in this cheat sheet. Sorry If I missed something. I have skipped some topics due to the length constraint of this article.

Now you have learned all the basic concepts of python. you are now all set to write your first program in python.

Stay tuned with this python journey

I hope you liked it!. Let's catch up in the next articles.

If you liked it, Please Support Me

Did you find this article valuable?

Support Nishant Gour by becoming a sponsor. Any amount is appreciated!