1、生成指定位數的隨機字符串
# -*- coding:utf-8 -*-
import random
def my_char(length):
s=" abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKL MNOPQRSTUVIXYZ!aN$x*6*( )?"
p = "" .join(random.sample(s,length ))
return p
a = my_char(5)
print(a)
2、猜數字游戲
在這個游戲中,任務是創建一個腳本,能夠在一個范圍內生成一個隨機數。如果用戶在三次機會中猜對了數字,那么用戶贏得游戲,否則用戶輸。
import random
number = random.randint(1, 20)
print(number)
for i in range(0, 3):
user = int(input("guess the number:\n"))
if user ==number:
print("Nice")
print("you guess the number right it's {}".format(number))
elif user > number:
print("you guess is too high")
elif user < number:
print("you guess is too low")
else:
print("沒機會了...")
3、已知一個字符串 "hello_world_test" ,如何得到一個列表 ["hello","world","test"]
使用split方法:
在Python的高級特性里有切片(split)操作符,可以對字符串進行截取。
語法
看一下源碼:
def split(self, *args, **kwargs): # real signature unknown
"""
Return a list of the words in the string, using sep as the delimiter string.
# 使用sep作為分隔符字符串,返回字符串中的單詞列表
# 有兩個參數:sep, maxsplit
sep
The delimiter according which to split the string. # 用於拆分字符串的分隔符。
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
# 分割次數
-1 (the default value) means no limit.
"""
pass
例子1
t = "Baidu JD Taobao Facebook"
print(t.split())
# 結果:
# ['Baidu', 'JD', 'Taobao', 'Facebook']
結論:當不帶參數時,默認是以空字符作為參數進行分割,空字符全部被分割。
例子2
t = "Baidu JD Taobao Facebook"
print(t.split(" ", 1))
# 結果:
# ['Baidu', 'JD Taobao Facebook']
結論: 以 空格 為分隔符,指定第二個參數為 1,返回兩個參數列表。
所以題目的答案:
test = "hello_world_test"
print(test.split("_"))
# 結果:
# ['hello', 'world', 'test']
4、編程輸出1/1+1/3+1/5...1/99的和
#coding=utf-8
def mysum(num):
sum=0
for i in range(num):
if(i%2) == 1:
sum=sum+1/i
return sum
if __name__=='__main__':
res=mysum(100)