Creart a comment
#this is a comment.
Multiline comments
""" This is a comment written in more than one line """
print() function
print("Hello World")
print("Hello", "how are you?")
x = ("apple", "banana", "cherry")
print(x)
Variables
x=4 #x is of type int x="Sally" #x is now of type str #If you want to specify the data type of a variable #this can be done with casting x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 x, y, z = "Orange", "Banana", "Cherry" #If you have a collection of values in a list, tuple etc. #Python allows you to extract the values into variables. #This is called unpacking fruits = ["apple", "banana", "cherry"] x, y, z = fruits
Data types
If you want to specify the data type, you can use the following constructorfunctions:
Operators
Arithmetic operators(算数运算符)
# 基本和Java一样 #** Exponentiation 求幂 x**y #// Floor division 整除 x//y #5//2=2
Assignment operators(赋值运算符)
Assignment operators are used to assign values to variables:
Comparison operators(比较运算符)
和Java一样
Logical operators(逻辑运算符)
#and x<5 and x>10 #or x<5 or x>10 #not not(x<5 and x<10)
Identity operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
Membership operators
Membership operators are used to test if a sequence is presented in an object:
Bitwise operators
Bitwise operators are used to compare (binary) numbers:
If statements
If statements
a=33
b=200
if b>a:
priny("b is greater than a")
Note: indentation(缩进) in If statement is very important.
elif in If statements
a=33
b=33
if b>a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else in If statementsa = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than or equal to b")
and/or in If statementsa = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
While loop
While loop
i = 1 while i < 6: print(i) i += 1The break statement in while
i = 1 while i < 6: print(i) if i == 3: break i += 1The continue statement in while
With the continue statement we can stop the current iteration, and continue with the next:
i = 0 while i < 6: i += 1 if i == 3: continue print(i) # Note that number 3 is missing in the resultThe else statement in while
With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
For loop
The break statement in for loop
With the break statement we can stop the loop before it has looped through all the items:
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": breakWith the continue statement we can stop the current iteration of the loop, and continue with the next:
fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) # "banana" will not be printed.The range() function
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number
for x in range(6): print(x) # 0, 1, 2, 3, 4, 5 will be printed.
for x in range(2, 6): print(x) #means values from 2 to 6 (but not including 6)The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3)
for x in range(2, 30, 3): print(x) # 2, 5, 8, 11, 14, 17, 20, 23, 26, 29 will be printed.else in for loop
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
for x in range(6):
print(x)
else:
print("Finally finished!")
Functions
Python functions
#Creating a function
#A function is defined using the def keyword:
def my_function():
print("Hello from a function")
#Calling a function
#Use the function name followed by parenthesis
my_function()
Arguments/parameters(参数)
Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
"""Output:
Emil Refsnes
Tobias Refsnes
Linus Refsnes
"""
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
#Output: Emil Refsnes
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
#Output: The youngest child is Linus
If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
#Output: His last name is Refsnes
If we call the function without argument, it uses the default value:def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function()
"""Output
I am from Sweden
I am from Norway
"""
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
""" Output:
apple
banana
cherry
"""
Return valusedef my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Python classes and objects
Creating a class
p1 = MyClass() print(p1.x)The _init_() function
All classes have a function called _init_(), which is always executed when the class is being initiated. Use the _init_() function to assign values to object properties, or other operations that are necessary to do when the object is being created:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
# john and 36 will be printed.
Object methodsObjects can also contain methods. Methods in objects are functions that belong to the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
# “Hello my name is John" will be printed.
Note: The created object and its properties can be deleted using the del keyword.



