python字串拼接 + if while for迴圈例子

來源:互聯網
上載者:User


注釋

單行注釋 #

多行注釋 ''' 三個單引號或者三個雙引號 """

''' 用三引號引住可以多行賦值

使用者互動 input

字串拼接

+  ""%() "".format()推薦使用

name = input("name:")

age = int(input("age:"))

sex = input("sex:")

例:+

# 字串拼接+

info1 = '''----info in ''' + name + '''---

name:''' + name + '''

age:''' + age + '''

sex:''' + sex + '''

'''

例:""%()

# %格式化字串

info = '''------info in %s -------

name:%s

age:%d

sex:%s

''' % ("name", "name", age, "sex")

#"".format()

info3 = '''---info in {_name}---

name:{_name}

age:{_age}

sex:{_sex}

'''.format(_name=name,

_age=age,

_sex=sex)

info4 = '''---info in {0}---

name:{0}

age:{1}

sex:{2}'''.format(name, age, sex)

模組定義:

密文密碼:getpass  引用後使用,getpass.getpass()

if else 使用

例:

username = "username"

password = "123456"

_Username = input("Username:")

_Passwd = input("Password:")

if username == _Username and password == _Passwd:

print("welcome user {name} to beij".format(name=username))

else:

print("Invalid  username or passwd")

if elif else

例:

Myage = 37

InputAge = int(input("please input my age:"))

if InputAge == Myage:

print("It's right")

elif InputAge > Myage:

print("Think small")

else:

print("Think big")

While else 迴圈

count = 0

while count < 3:

Myage = 37

InputAge = int(input("please input my age:"))

if InputAge == Myage:

print("It's right")

break

elif InputAge > Myage:

print("Think small")

else:

print("Think big")

count+=1

else:

print("fuck you!")

break    跳出當前整個迴圈

continue 跳出當前迴圈,進入下次迴圈

作業

編寫登陸介面

輸入使用者名稱密碼
認證成功後顯示歡迎資訊
輸錯三次後鎖定
old_uname = open(r'C:\Users\Administrator\Desktop\username.txt', 'r').readlines()
count = 0
while count < 3:
    username = input("please your username:")
    passwd = input("please your passwd:")
    for i in old_uname:
        if i == username:
            print("wolcome to your blogs:{_uname}".format(_uneme=username))
            break
        else:
            continue
    else:
        count += 1
        if count == 3:
            continue
        print("The password you entered is incorrect!please input again...")
else:
    print("三次錯誤,帳號鎖定")
    open(r'C:\Users\Administrator\Desktop\lockname.txt', 'a').write(username + '\n')


字串基礎
(1)、逸出字元串            
(2)、raw字串--轉義機制  open(r'c:\tmp\a.txt','a+')
(3)、Unicode字串
(4)、格式化字串  "age %d,sex %s,record %m.nf"%(20,"man",73.45)
字串基礎操作
 + 串連 、* 重複、s[i] 索引(index)、s[i:j] 切片(slice)、for迴圈遍曆

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.