1. 程式人生 > >用戶輸入與while循環

用戶輸入與while循環

一段時間 16px -s for 信息 if語句 rep file error

函數input()的工作原理:
函數input()讓程序短暫運行,等待用戶輸入一些文本,獲取用戶輸入後將其存儲在一個變量中

測試input()功能——

#!/usr/bin/env python
#filename:input().py

message=input("tell me something and, I will repeat back to you: ")
print(message)

效果:

[[email protected] Day3]# ./input.py
tell me something and, I will repeat back to you: hello


hello

在有些時候,input()也許不能滿足需求,例如:

>>> age=input("How old are you?")
How old are you?26
>>> age >= 18
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() >= int()

#可以發現這裏出錯了。因為input()函數存放用戶輸入的結果為字符串,字符串是無法和數字去比較的,

如何滿足這類需求?#

通過int()函數,把字符串中的數字轉換為整數

>>> age = input("how old are you?\n")
how old are you?
26
>>> age=int(age)
>>> age>=18
True

while循環

for循環用於針對集合中的每個元素的一個代碼塊,而while循環則是不斷的運行,直到指定的條件不滿足為止。

故while循環必須要設置一個打破條件,不然會無線循環下去!

用while來數數

#!/usr/bin/env python

#filename = num.py

number = 0

while number < 1000000000000000:

print(number)

number+=1

在這個循環中,設定了一個變量 number = 0

循環條件是number ≤ 100000000000000000,故這個程序一定會導致一段時間的刷頻。

讓用戶選擇何時退出:

#!/usr/bin/env python

#filename parrot.py

prompt = "\nTell me something and, I will repeat back to you:\n"

prompt += "Enter ‘quit‘ to end the program\n"

message = ""

while message != ‘quit‘:

message=input(prompt)

print(message)

#這裏我們定義了一條提示信息,告訴用戶他有兩個選擇

1、輸入什麽返回什麽

2、輸入quit結束程序

效果:#

[[email protected] Day3]# ./parrot.py

Tell me something and, I will repeat back to you:
Enter ‘quit‘ to end the program
hello
hello

Tell me something and, I will repeat back to you:
Enter ‘quit‘ to end the program
cat
cat

Tell me something and, I will repeat back to you:
Enter ‘quit‘ to end the program
quit
quit

[[email protected] Day3]#

這個腳本的不足之處在於每次退出的時候,‘quit’也被print了

解決辦法只需要加入一個if語句就可以了

while message != ‘quit‘:

message=input(prompt)

if message != ‘quit‘:

print(message)

#加入一個判斷,只有當message不等於‘quit’的時候,才會進行print

測試效果:

[[email protected] Day3]# ./parrot.py

Tell me something and, I will repeat back to you:

Enter ‘quit‘ to end the program

hello

hello

Tell me something and, I will repeat back to you:

Enter ‘quit‘ to end the program

quit

[[email protected] Day3]#

使用標誌:

在要求很多條件都滿足才繼續運行的程序中,可定義一個變量,用於判斷整個程序是否處於活動狀態,這個變量稱之為標誌。

#標誌#可以看做程序的信號燈,可以讓設置信號燈為true的時候程序繼續運行,一旦信號燈=false,則程序立即終止。

#!/usr/bin/env python

#filename active.py

prompt = "\nTell me something and, I will repeat back to you:\n"

prompt += "Enter ‘quit‘ to end the program\n"

active = True

while active:

message=input(prompt)

if message == ‘quit‘:

active = False

else:

print(message)

測試:

編寫一個腳本,讓程序可以列出1-30中的奇數

#filename even.py

number = 0

while number <= 29:

number += 1

if number % 2 == 0:

continue

print(number)

首先,把number 設置成0,由於它小於29就開始進入了循環,每次+1,然後進行mod2運算(取余數),如果余數=0,則繼續加1(因為偶數的余數都是0)

如果余數≠0,則進行print

用戶輸入與while循環