Python first line of code

1, Simple use

① Swap two variables

# a = 4 b = 5
a,b = b,a
# print(a,b) >> 5,4

  let's start by swapping two variables. This method is one of the simplest and most intuitive methods. It can be written without using temporary variables or applying arithmetic operations.

② Assignment of multiple variables

a,b,c = 4,5.5,'Hello'
#print(a,b,c) >> 4,5.5,hello

  you can use commas and variables to assign multiple values to variables at once. Using this technique, you can assign multiple data types at once. You can use lists to assign values to variables. The following is an example of assigning multiple values in a list to a variable.

a,b,*c = [1,2,3,4,5]
> 1 2 [3,4,5]

③ Even sum in list

a = [1,2,3,4,5,6]
s = sum([num for num in a if num%2 == 0])
>> 12

  there are many ways to do this, but the best and simplest way is to use list index and sum function.

④ Remove multiple elements from the list

#### Deleting all even
a = [1,2,3,4,5]
del a[1::2]
>[1, 3, 5]<br>

   del is a keyword used in Python to delete a value from a list.

⑤ Read file

lst = [line.strip() for line in open('data.txt')]

   here we use lists to deal with it. First, we open a text file and use the for loop to read it line by line. Finally, use strip to remove all unnecessary space. By using the list function, the code is simpler and shorter.

##Using with will also close the file after use
with open("data.txt") as f:
    lst=[line.strip() for line in f]

⑥ Write data to file

with open("data.txt",'a',newline='\n') as f: 
    f.write("Python is awsome")

  the above code first creates a file data Txt (if not), and then it will write Python is awesome in the file.

⑦ Create list

lst = [i for i in range(0,10)]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


lst = list(range(0,10))

  we can also use the same method to create a string list.

lst = [("Hello "+i) for i in ['Karl','Abhay','Zen']]
> ['Hello Karl', 'Hello Abhay', 'Hello Zen']

⑧ Mapping list or type conversion entire list

> [1, 2, 3]

> [1.0, 2.0, 3.0]

[float(i) for i in [1,2,3]]
> [1.0, 2.0, 3.0]

  sometimes in our project, we need to change the data type of all elements in the list. The first way you think of might be to use a loop, then access all the elements in the list, and then change the data type of the elements one by one. This method is old-fashioned. In Python, we have a mapping function that can do these jobs for us.

⑨ Create collection

#### Square of all even numbers in an range
{x**2 for x in range(10) if x%2==0}

> {0, 4, 16, 36, 64}

  the method we use to create lists can also be used to create collections. Let's create a set using the square root method that contains all even numbers in the range.

⑩ Fizz Buzz

  in this test, we need to write a program to print numbers from 1 to 20. However, if it is a multiple of 3, print Fizz; if it is a multiple of 5, print Buzz; if it is a multiple of 3 and 5 at the same time, print FizzBuzz; otherwise, print numbers. It seems that we have to use loops and multiple if else statements. If you try to do it in other languages, you may need to write 10 lines of code, but with Python, we can implement FizzBuzz in only one line of code.

['FizzBuzz' if i%3==0 and i%5==0
    else 'Fizz' if i%3==0 
    else 'Buzz' if i%5==0 
    else i  for i in range(1,20)]

  in the above code, we use list understanding to run a loop from 1 to 20, and then in each iteration of the loop, we check whether the number can be divided by 3 or 5. If so, then we replace the value with Fizz or Buzz, or use FizzBuzz value.

⑩ ① palindrome

A palindrome is a number or string that looks the same when it is inverted.

text = 'level'
ispalindrome = text == text[::-1]

> True

⑩ ② space separated integers into a list

lis = list(map(int, input().split()))

> 1 2 3 4 5 6 7 8
[1, 2, 3, 4, 5, 6, 7, 8]

⑩ ③ Lambda function

The lambda function is a small anonymous function. Lambda functions can accept any number of arguments, but only one expression.

# Function that returns square of any number
sqr = lambda x: x * x

> 100

⑩ ④ check the existence of numbers in the list

num = 5
if num in [1,2,3,4,5]:

> present

⑩ ⑤ print pattern

  in Python, we only need one line of code to draw amazing patterns.

⑩ ⑥ find factorial

   factorial is the product of an integer and all integers below it.

import math
n = 6

> 720

⑩ ⑦ Fibonacci sequence

  a set of numbers in which each number (Fibonacci number) is the sum of the first two numbers. The simplest Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13 and so on. You can create Fibonacci sequences in a range using list derivation and for loops.

fibo = [0,1]
[fibo.append(fibo[-2]+fibo[-1]) for i in range(5)]

> [0, 1, 1, 2, 3, 5, 8]

⑩ ⑧ prime number

  prime number is a number that can only be divided by itself and 1. For example: 2, 3, 5, 7, etc. In order to generate prime numbers in a range, we can use the list function with filter and lambda to generate prime numbers.

list(filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 13)))

> [2, 3, 5, 7, 11]

⑩ ⑨ find the maximum value

findmax = lambda x,y: x if x > y else y 

> 14


   in the above code, we use the lambda function to check the comparison condition and return the maximum value according to the returned value. Or use the max() built-in function.

② ⑩ linear algebra

  sometimes we need to scale the elements in the list two to five times. The following code explains how to do this.

def scale(lst, x):
    return [i*x for i in lst] 

scale([2,3,4], 2)

> [4,6,8]

② ① matrix transpose

  you need to convert all rows to columns and vice versa. In Python, you can use the zip function to replace a matrix in a line of code.

transpose = [list(i) for i in zip(*a)] 

> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

② ② counting

  this is an important and useful use case when we need to know the number of times a value appears in the text. In Python, there is a re library to help you do this.

import re

len(re.findall('python','python is a programming language. python is python.'))

> 3

② ③ replace the text with other text

"python is a programming language.python is python".replace("python",'Java')

> Java is a programming language. Java is Java

② ④ simulate coin tossing

  this may not be that important, but it can be very useful when you need to generate some random choices from a given set of choices.

import random


> Head

② ⑤ generation group

groups = [(a, b) for a in ['a', 'b'] for b in [1, 2, 3]] 

> [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]

Keywords: Python Back-end

Added by BITRU on Tue, 01 Mar 2022 03:09:03 +0200