Python学习——实现简单的交互raw

2023-01-31 02:01:02 学习 简单 交互

row_input的使用:

>>> name=raw_input("please input your name:")
please input your name:xiaobai
>>> name
'xiaobai'

编写小程序,询问用户姓名,性别,年龄,工作,工资,以格式化的方式输出:

InfORMation of company stuff:

Name:

Age:

Sex:

Job:


代码:

[root@nfs-server ~]# vim information_of_stuff.py   
#!/bin/python
name=raw_input("Please input your name:")
age=raw_input("Please input your age:")
sex=raw_input("Please input your sex:")
job=raw_input("Please input your job:")
print '''
==============================
Information of company stuff:
Name: %s
Age: %s
Sex: %s
Job: %s
=============================='''%(name,age,sex,job)

执行:

[root@nfs-server ~]# Python information_of_stuff.py
Please input your name:xiaobai
Please input your age:25
Please input your sex:male
Please input your job:engineer
==============================
Information of company stuff:
Name: xiaobai
Age: 25
Sex: male
Job: engineer
==============================

输入一个0~100直接的数字让用户猜,并且猜测次数不能大于三次。

[root@nfs-client2 ~]# vim guess_num.py   
#!/bin/python
import os
os.system('clear')                  #执行时先清屏
real_num=int(raw_input("please input the real_num from 0 to 100:"))
os.system('clear')                  #输入让用户猜的数字后清屏
retry_count=0                       #设定循环关闭条件
while retry_count<3:                #后面加冒号
        guess_num=int(raw_input("Please input a number from 0 to 100:"))
        if guess_num>real_num:
                print "Wrong! Please try smaller!"
                retry_count+=1       #自增
        elif guess_num<real_num:     #多个条件用elif
                print "Wrong! Please try bigger!"
                retry_count+=1
        else:                        #最后一个条件用
                print "Congurations! You Got it!"
                break                #跳出循环
else:
        print "Too much times!"

Python不像shell,没有fi循环关闭符号,而是通过缩进控制代码层级,同一级代码缩进应保持一致,if和else不属于同一级,缩进不同也可执行,但不符合书写规范。

raw_input输入的是字符串,字符串与数字比较时会自动转为ASCII值进行比较,因此要使用int将其转换为整数类型,break为跳出循环。

ord:将字符串转换为ASCII对应的值。

>>> print ord("a")
97
>>> print ord("1") 
49

优化代码,以上代码输入回车或字符串会报错,且数字不是随机值,需要优化。

[root@nfs-client2 ~]# vim guess_num.py   
#!/bin/python
import os
import random
os.system('clear')
real_num=random.randrange(100)
os.system('clear')
retry_count=0
while retry_count<3:
        guess_num=raw_input("Please input a number from 0 to 100:").strip() #去空格回车
        if len(guess_num)==0:            #判断字符串长度是否为0
                continue
        if guess_num.isdigit():          #判断是否全为数字
                guess_num=int(guess_num)
        else:
                print "You should input a number instead of string!"
                continue                 #跳出当前循环,进行下一次循环
        if guess_num>real_num:
                print "Wrong! Please try smaller!"
        elif guess_num<real_num:
                print "Wrong! Please try bigger!"
        else:
                print "Congurations! You got the real number %d !"%real_num
                break
        retry_count+=1
else:
        print "Too much times! The real number is",real_num

.strip()表示将输入的空格和回车去掉;

len(guess_num)表示计算字符串的长度;

continue表示跳出当前循环,进行下一次循环;

isdigit()表示判断是否全是数字;


将上述循环更改为for循环:

[root@nfs-client2 ~]# vim guess_num_for.py    
#!/bin/python
import os
import random
os.system('clear')
real_num=random.randrange(100)
os.system('clear')
for i in range(3):
        guess_num=raw_input("Please input a number from 0 to 100:").strip()
        if len(guess_num)==0:
                continue
        if guess_num.isdigit():
                guess_num=int(guess_num)
        else:
                print "You should input a number instead of string!"
                continue
        if guess_num>real_num:
                print "Wrong! Please try smaller!"
        elif guess_num<real_num:
                print "Wrong! Please try bigger!"
        else:
                print "Congurations! You got the real number %d !"%real_num
                break
else:
        print "Too much times! The real number is",real_num

range为数组,其参数分别为起始值,末尾值,步长。

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(2,10,2)
[2, 4, 6, 8]
>>> range(2,20,5)
[2, 7, 12, 17]

设计一个多层循环,用户输入密码正确的话进入目录进行选择,并能退出循环。

[root@nfs-client2 ~]# cat mulit_loop.py    
#!/bin/python
passwd="test"
logout=False            #加跳出的flag
for i in range(3):
    passWord=raw_input("Please input your password:").strip()
    if len(password)==0:
        continue
    if password==passwd:
        print "Welcome to login!"
        while True:
            user_select=raw_input('''
            ====================================
            Please input a number to continue
            1.Send files;
            2.Send emalis;
            3.exit this level;
            4.exit the whole loop.
            ====================================
            ''').strip()
            user_select=int(user_select)
            if user_select==1:
                print "Sending files as you wish!"
            if user_select==2:
                print "Sending emails as you wish!"
            if user_select==3:
                print "Exit this level,please re-input the password!"
                break
            if user_select==4:
                print "Ok, let's have a break!"
                logout=True
                break
        if logout==True:
            break


相关文章