print("----------------猜字游戏-------------------")
temp = input ("请输入我现在心里想的数字:")
guess = int(temp)
if guess!=8:
print("oh,你猜错了")
else:
print("恭喜,你猜对了")
print("游戏结束")
*
Python中变量不用声明,但必须先赋值再用。*
input()
打印括号里的话,并输入内容,无论输入的是什么,变量都为字符型。
input()以字符串的方式获取用户输入:
1 >>> x = input()
2 4.5
3 >>> type(x)
4 <class 'str'>
5 >>> y = input()
6 Do you love python?
7 >>> type(y)
8 <class 'str'>
输入的字符串可以通过运算符进行连接、复制等操作:
1 >>> x = input()
2 abc
3 >>> x * 3
4 'abcabcabc'
5 >>> y = input()
6 123
7 >>> x + y
8 'abc123'
但无法直接参与算术运算,如:
1 >>> x = input()
2 5
3 >>> x + 5
4 Traceback (most recent call last):
5 File "<stdin>", line 1, in <module>
6 TypeError: must be str, not int
7 >>> x * 5
8 '55555'
9 >>> y = input()
10 6
11 >>> x * y
12 Traceback (most recent call last):
13 File "<stdin>", line 1, in <module>
14 TypeError: can't multiply sequence by non-int of type 'str'
此时可以使用转换,方法有多种:
1.指定类型转换
1 >>> y = int(input())
2 10
3 >>> type(y)
4 <class 'int'>
2.自动转换
函数eval() 用来执行一个字符串表达式,并返回表达式的值
eval(expression, globals[ ], locals[ ])
global 和 locals 分别相当于全局和局部变量,eval函数会优先在局部变量存储空间中检索
1 >>> y = eval(input())
2 4.5
3 >>> type(y)
4 <class 'float'>
3.切割转换
利用函数split()通过指定分隔符对字符串进行切片。
str.split(str="", num=string.count(str))
str为分割符,包括空格、\n,\t 等 ,num是分割次数。
python中tab代替大括号区分层次。
Python区分大小写。
在一些编程语言,我们可以将两个字符串“相加”在一起,如:‘I’ + ‘Love’ + ‘FishC’ 会得到 ‘ILoveFishC’,在 Python 里,这种做法叫做拼接字符串。
Python3 中,一行可以书写多个语句吗?
可以,多个语句用分号隔开
Python3 中,一个语句可以分成多行书写吗?
可以,不过需要加 \
猜测数字的游戏
import random
times = 3
secret = random.randint(1,5)
print ("--------欢迎来到猜数字游戏--------\n")
guess = 0
print ("猜一下1-5中的哪个值?:",end=" ")
while (guess != secret) and (times > 0) :
guess = int(input())
times = times - 1
if guess == secret:
print("\n猜对了,你是怎么这么利害?!!\n")
print("但是猜对了也没有奖励\n")
else:
if guess > secret:
print("\n大了大了~\n")
else:
print("\n呵呵 小了~\n")
if times > 0:
print("再试一次把: ",end=" ")
else:
print("3次机会都用光了!~\n")
print("游戏结束,不玩了^_^\n")
// bif是内置函数的意思,input是一个内置函数