前两天由于出去兼职拍照,玩耍,没有继续学习!!
1.5 程序解析
len()函数
查看字符串中的字数
len('ni hao')
6
str()函数:
可以传入一个整型值,并求值为它的字符串形式,可以将数字转化为字符串
str(18)
print('my size is '+str(18)+',do you believe me?')
结果
my size is 18,do you believe me?
要是没有str(),则:
print('my size is '+18+',do you believe me?')
结果(error):
*Traceback (most recent call last):
File "E:/APP/16 python/xn_study/20230620.py", line 2, in <module>
print('my size is '+18+',do you believe me?')
TypeError: can only concatenate str (not "int") to str*
可以理解成吧整型,变成了字符串类型了。
int() , float()
2. 控制流
布尔”数据类型
只有两种值:True 和 False
比较操作符
== 等于, != 不等于, < 小于, > 大于, <= 小于等于, >= 大于等于
not or and 操作符
elif 语句
“否则如果”,总是跟在 if 或另一条 elif 语句后面,在Python中,elif应该是在if语句的后面,而不是在else语句之后
例子:
print('what is your age?')
age = input()
age = int(age)
print('what is your name?')
name = input()
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('you are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')
通过chatgpt,得到一些给出的实例,从这里也可以知道,它可以解决一些基础的问题!
示例运行:
what is your age?
18
what is your name?
Alice
Hi, Alice.
what is your age?
10
what is your name?
Bob
you are not Alice, kiddo.
what is your age?
25
what is your name?
Eve
You are neither Alice nor a little kid.
请注意,代码中使用input()函数来获取用户的输入。用户将被要求输入年龄和名称,并根据条件输出相应的消息。
while语句
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
运行实例:
Please type your name.
Alice
Please type your name.
Bob
Please type your name.
your name
Thank you!
在这个示例中,程序将一直要求用户输入名称。只有当用户输入为"your name"时,循环才会被终止,并打印"Thank you!"。请注意,代码中使用了break语句来跳出循环。