SoFunction
Updated on 2024-11-21

Life is short I use python How to get started quickly with python?

Let's say you wish to learn Python as a language but are struggling to find a short and comprehensive tutorial to get started. Then this tutorial will take you through the doors of Python in ten minutes. The content of this article is somewhere between a tutorial and a CheatSheet, so it will only cover some basic concepts. Obviously, if you want to get really good at a language, you'll still need to get your hands dirty. Here, I'll assume that you already have some basic knowledge of programming, so I'll skip most of the non-Python language related content. This article will highlight important keywords so you can see them easily. Also note that due to the limited length of this tutorial, there is a lot of content that I will illustrate directly in code with a few comments.

Language Features of Python

Python is a programming language that is strongly typed (i.e., variable types are mandatory), dynamic, implicitly typed (you don't need to make variable declarations), case-sensitive (var and VAR represent different variables), and object-oriented (everything is an object).

Getting Help

You can easily get help through the Python interpreter. If you want to know how an object (object) works, then all you need to do is call help(<object>)! There are also some useful methods, dir() will show you all the methods for that object, and <object>. __doc__ will show its documentation:

>>> help(5)
Help on int object:
(etc etc)>>> dir(5)
['__abs__', '__add__', ...]>>> abs.__doc__'abs(number) -> number

Return the absolute value of the argument.'

grammatical

There is no mandatory statement termination character in Python, and code blocks are indicated by indentation. Indentation indicates the beginning of a block, and reverse indentation indicates the end of a block. Statements are terminated with a colon (:) character and open an indentation level. Single-line comments begin with the tic-tac-toe character (#), and multi-line comments appear as multi-line strings. Assignment (in effect, binding an object to a name) is accomplished with the equals sign ("="), double equals signs ("==") are used for equality judgments, and "+=" and "-=" are used for increase/decrease operations (the value to be increased/decreased is determined by the value to the right of the symbol). This applies to many data types, including strings. You can also use multiple variables on a single line. Example:

>>> myvar = 3>>> myvar += 2>>> myvar5>>> myvar -= 1>>> myvar4"""This is a multiline comment.
The following lines concatenate the two strings.""">>> mystring = "Hello">>> mystring += " world.">>> print mystring
Hello world.# This swaps the variables in one line(!).# It doesn't violate strong typing because values aren't# actually being assigned, but new objects are bound to# the old names.>>> myvar, mystring = mystring, myvar


data type

Python has three basic data structures: lists, tuples, and dictionaries, while sets are included in the collection library (but have been built-in since Python 2.5). Lists are similar to one-dimensional arrays (of course, you can also create "lists of lists" that are similar to multi-dimensional arrays), dictionaries are associative arrays (often called hash tables), and tuples are immutable one-dimensional arrays ("arrays" in Python). " in Python can contain any type of element, so you can use a mix of elements, such as integers, strings, or nested containment lists, dictionaries, or tuples). The first element in an array has an index value (subscript) of 0. Negative index values allow you to access an array element from back to front, and -1 means the last element. Array elements can also point to functions. See the following usage:

>>> sample = [1, ["another", "list"], ("a", "tuple")]>>> mylist = ["List item 1", 2, 3.14]>>> mylist[0] = "List item 1 again" # We're changing the item.>>> mylist[-1] = 3.21 # Here, we refer to the last item.>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}>>> mydict["pi"] = 3.15 # This is how you change dictionary values.>>> mytuple = (1, 2, 3)>>> myfunction = len>>> print myfunction(mylist)3

You can access a section of an array using the :operator, if :left is null it means start at the first element, similarly :right is null it means end at the last element. A negative index then indicates a position counting from back to front (-1 is the last item), for example:

>>> mylist = ["List item 1", 2, 3.14]>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]>>> print mylist[0:2]
['List item 1', 2]>>> print mylist[-3:-1]
['List item 1', 2]>>> print mylist[1:]
[2, 3.14]# Adding a third parameter, "step" will have Python step in# N item increments, rather than 1.# ., this will return the first item, then go to the third and# return that (so, items 0 and 2 in 0-indexing).>>> print mylist[::2]
['List item 1', 3.14]

string (computer science)

Strings in Python are labeled using either single quotes (') or double quotes ("), and you have the ability to use another type of labeling in strings that are labeled by one (e.g. "He said 'hello'. ") "). Multi-line strings can be punctuated by three consecutive single quotes ("') or double quotes ("""), and Python can be used to punctuate strings with syntax like u "This is a unicode string Python can use Unicode strings with syntax like u "This is a unicode string". If you want to fill the string with variables, then you can use the modulo operator (%) and a tuple. This is done by using %s to refer to the position of the variable from left to right in the target string, or by using a dictionary instead, as shown in the following example:

>>>print "Name: %s\
Number: %s\
String: %s" % (, 3, 3 * "-")
Name: Poromenos
Number: 3String: ---

strString = """This is
a multiline
string."""# WARNING: Watch out for the trailing s in "%(key)s".>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.

process control

Flow control can be implemented in Python using if, for and while. select is not available in Python, instead it is implemented using if. Use for to enumerate the elements of a list. If you wish to generate a list of numbers, use the range(<number>) function. The following is an example of the syntax of these statements:

rangelist = range(10)>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]for number in rangelist: # Check if number is one of
 # the numbers in the tuple.
 if number in (3, 4, 7, 9):  # "Break" terminates a for without
  # executing the "else" clause.
  break
 else:  # "Continue" starts the next iteration
  # of the loop. It's rather useless here,
  # as it's the last statement of the loop.
  continueelse: # The "else" clause is optional and is
 # executed only if the loop didn't "break".
 pass # Do nothingif rangelist[1] == 2: print "The second item (lists are 0-based) is 2"elif rangelist[1] == 3: print "The second item (lists are 0-based) is 3"else: print "Dunno"while rangelist[1] == 1: pass

function (math.)

Functions are declared using the "def" keyword. Optional parameters appear in the function declaration as a set and are followed by mandatory parameters, which can be given a default value in the function declaration. Named parameters require assignment. Functions can return a tuple (using tuple unwrapping can effectively return more than one value.) Lambda functions are special functions consisting of a single statement, where the arguments are passed by reference, but cannot be changed for immutable types (e.g., tuples, integers, strings, etc.). This is because only the memory address of the variable is passed, and the variable can only be bound to an object after the old object is discarded, so immutable types are replaced rather than altered (Translator's note: although the form of the argument passed by Python is essentially a reference pass, it produces the effect of a value pass). Example:

# Equivalent to def funcvar(x): return x + 1funcvar = lambda x: x + 1>>> print funcvar(1)2# an_int and a_string are optional arguments that have default values # If passing_example is called with one argument, an_int defaults to 2 and a_string defaults to A default string. If passing_example is called with only one argument, then an_int defaults to 2 and a_string defaults to A default string. a_string still defaults to A default string if passing_example is called with the first two arguments specified. a_list is required because it does not specify a default value. def passing_example(a_list, an_int=2, a_string="A default string").
 a_list.append("A new item")
 an_int = 4
 return a_list, an_int, a_string>>> my_list = [1, 2, 3]>>> my_int = 10>>> print passing_example(my_list, my_int)
([1, 2, 3, 'A new item'], 4, "A default string")>>> my_list
[1, 2, 3, 'A new item']>>> my_int10

resemble

Python supports a limited form of multiple inheritance. Private variables and methods can be declared by adding at least two leading underscores and at most one trailing underscore (e.g., "__spam", which is a convention, not a Python mandate). Of course, we can also give instances of the class arbitrary names. For example:

class MyClass(object):
 common = 10
 def __init__(self):
   = 3
 def myfunction(self, arg1, arg2):
  return  # This is the class instantiation>>> classinstance = MyClass()>>> (1, 2)3# This variable is shared by all classes.>>> classinstance2 = MyClass()>>> classinstance.common10>>> classinstance2.common10# Note how we use the class name# instead of the instance.>>>  = 30>>> classinstance.common30>>> classinstance2.common30# This will not update the variable on the class,# instead it will bind a new object to the old# variable name.>>>  = 10>>> classinstance.common10>>> classinstance2.common30>>>  = 50# This has not changed, because "common" is# now an instance variable.>>> classinstance.common10>>> classinstance2.common50# This class inherits from MyClass. The example# class above inherits from "object", which makes# it what's called a "new-style class".# Multiple inheritance is declared as:# class OtherClass(MyClass1, MyClass2, MyClassN)class OtherClass(MyClass):
 # The "self" argument is passed automatically
 # and refers to the class instance, so you can set
 # instance variables as above, but from inside the class.
 def __init__(self, arg1):
   = 3
  print arg1>>> classinstance = OtherClass("hello")
hello>>> (1, 2)3# This class doesn't have a .test member, but# we can add one to the instance anyway. Note# that this will only be a member of classinstance.>>>  = 10>>> classinstance.test10

exceptions

Exceptions in Python are handled by the try-except [exceptionname] block, for example:

def some_function():
 try:  # Division by zero raises an exception
  10 / 0
 except ZeroDivisionError:  print "Oops, invalid."
 else:  # Exception didn't occur, we're good.
  pass
 finally:  # This is executed after the code block is run
  # and all exceptions have been handled, even
  # if a new exception is raised while handling.
  print "We're done with that.">>> some_function()
Oops, invalid.
We're done with that.

import (data)

External libraries can be imported using the import [libname] keyword. Also, you can use from [libname] import [funcname] to import the desired function. For example:

import randomfrom time import clock
randomint = (1, 100)>>> print randomint64

File I/O

Python has a number of built-in libraries that can be called for file processing. For example, here's a demonstration of how to serialize a file (using the pickle library to convert a data structure to a string):

import pickle
mylist = ["This", "is", 4, 13327]# Open the file C:\\ for writing. The letter r before the# filename string is used to prevent backslash  = open(r"C:\\", "w")
(mylist, myfile)
()

myfile = open(r"C:\\", "w")
("This is a sample string")
()

myfile = open(r"C:\\")>>> print ()'This is a sample string'()# Open the file for  = open(r"C:\\")
loadedlist = (myfile)
()>>> print loadedlist
['This', 'is', 4, 13327]

Other miscellaneous

  • Numeric judgments can be used in a linked fashion, e.g. 1<a<3 determines whether the variable a is between 1 and 3.
  • You can use del to delete variables or to delete elements of an array.
  • List Comprehension provides a powerful tool for creating and manipulating lists. List Comprehension consists of an expression and a for statement immediately following the expression, the for statement can be followed by zero or more if or for statements, see the following example:
>>> lst1 = [1, 2, 3]>>> lst2 = [3, 4, 5]>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]# Check if an item has a specific property.# "any" returns true if any item in the list is true.>>> any([i % 3 for i in [3, 3, 4, 4, 3]])True# This is because 4 % 3 = 1, and 1 is true, so any()# returns True.# Check how many items have this property.>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)2>>> del lst1[0]>>> print lst1
[2, 3]>>> del lst1

Global variables are declared outside of a function and can be read without any special declaration, but if you want to change the value of a global variable, you must declare it with the global keyword at the beginning of the function, otherwise Python will treat this variable as a new local variable (be warned, it's easy to get screwed if you don't pay attention). Example:

number = 5def myfunc():
 # This will print 5.
 print numberdef anotherfunc():
 # This raises an exception because the variable has not
 # been bound before printing. Python knows that it an
 # object will be bound to it later and creates a new, local
 # object instead of accessing the global one.
 print number
 number = 3def yetanotherfunc():
 global number # This will correctly change the global.
 number = 3

Recommended Book List:

All the Python experts you know should have this list of books.

Python Book Lists Not to be compromised

Ten great Python books not to be missed

This is the whole content of this article, I hope it will help you to learn more.