Python最常用的函数、基础语句有哪些?你都知道吗
大数据DT
共 2647字,需浏览 6分钟
·
2022-04-18 00:41
导读:Python有很多好用的函数和模块,这里给大家整理下我常用的一些方法及语句。
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
zip(iterable1,iterable2, ...)
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
... print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
filter(function,data)
def is_even(x):
if x % 2 == 0:
return True
else:
return False
l1 = [1, 2, 3, 4, 5]
fl = filter(is_even, l1)
list(fl)
>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # 是元组中的一个返回 True
True
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
# 格式化字符串
print('{} {}'.format('hello','world'))
# 浮点数
float1 = 563.78453
print("{:5.2f}".format(float1))
string1 = "Linux"
string2 = "Hint"
joined_string = string1 + string2
print(joined_string)
# Assign a numeric value
number = 70
# Check the is more than 70 or not
if (number >= 70):
print("You have passed")
else:
print("You have not passed")
for循环
# Initialize the list
weekdays = ["Sunday", "Monday", "Tuesday","Wednesday", "Thursday","Friday", "Saturday"]
print("Seven Weekdays are:\n")
# Iterate the list using for loop
for day in range(len(weekdays)):
print(weekdays[day])
while循环
# Initialize counter
counter = 1
# Iterate the loop 5 times
while counter < 6:
# Print the counter value
print ("The current counter value: %d" % counter)
# Increment the counter
counter = counter + 1
# Initialize values
vacation1 = "Summer Vacation"
vacation2 = "Winter Vacation"
# Import another python script
import vacations as v
# Initialize the month list
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
# Initial flag variable to print summer vacation one time
flag = 0
# Iterate the list using for loop
for month in months:
if month == "June" or month == "July":
if flag == 0:
print("Now",v.vacation1)
flag = 1
elif month == "December":
print("Now",v.vacation2)
else:
print("The current month is",month)
# Create a list of characters using list comprehension
char_list = [ char for char in "linuxhint" ]
print(char_list)
# Define a tuple of websites
websites = ("google.com","yahoo.com", "ask.com", "bing.com")
# Create a list from tuple using list comprehension
site_list = [ site for site in websites ]
print(site_list)
#Assign the filename
filename = "languages.txt"
# Open file for writing
fileHandler = open(filename, "w")
# Add some text
fileHandler.write("Bash\n")
fileHandler.write("Python\n")
fileHandler.write("PHP\n")
# Close the file
fileHandler.close()
# Open file for reading
fileHandler = open(filename, "r")
# Read a file line by line
for line in fileHandler:
print(line)
# Close the file
fileHandler.close()
var1 = 'Hello World!'
var2 = "zhihu"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
定义和调用函数
# Define addition function
def addition(number1, number2):
result = number1 + number2
print("Addition result:",result)
# Define area function with return statement
def area(radius):
result = 3.14 * radius * radius
return result
# Call addition function
addition(400, 300)
# Call area function
print("Area of the circle is",area(4))
定义和实例化类
# Define the class
class Employee:
name = "Mostak Mahmud"
# Define the method
def details(self):
print("Post: Marketing Officer")
print("Department: Sales")
print("Salary: $1000")
# Create the employee object
emp = Employee()
# Print the class variable
print("Name:",emp.name)
# Call the class method
emp.details()
# Try block
try:
# Take a number
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Number is even")
else:
print("Number is odd")
# Exception block
except (ValueError):
# Print error message
print("Enter a numeric value")
延伸阅读👇
延伸阅读《Python 3标准库》
干货直达👇
评论