$ ./user_input_int.py
Enter an integer number: 23
Square of entered number is: 529
$ ./user_input_int.py
Enter an integer number: abc
Traceback (most recent call last):
File "./user_input_int.py", line 6, in <module>
usr_num = int(usr_ip)
ValueError: invalid literal for int() with base 10: 'abc'
浮點數(shù)輸入
#!/usr/bin/python3
usr_ip = input("Enter a floating point number: ")
# 需要將輸入的字符串顯式地指定為我們需要的類型
usr_num = float(usr_ip)
sqr_num = usr_num * usr_num
# 限制小數(shù)點位數(shù)
print("Square of entered number is: {0:.2f}".format(sqr_num))
$ ./user_input_float.py
Enter a floating point number: 3.232
Square of entered number is: 10.45
$ ./user_input_float.py
Enter a floating point number: 42.7e5
Square of entered number is: 18232900000000.00
$ ./user_input_float.py
Enter a floating point number: abc
Traceback (most recent call last):
File "./user_input_float.py", line 6, in <module>
usr_num = float(usr_ip)
ValueError: could not convert string to float: 'abc'
字符串輸入
#!/usr/bin/python3
usr_name = input("Hi there! What's your name? ")
usr_color = input("And your favorite color is? ")
print("{}, I like the {} color too".format(usr_name, usr_color))
不像Perl块茁,字符串輸入不需要進行類型轉(zhuǎn)換和注意換行符
$ ./user_input_str.py
Hi there! What's your name? learnbyexample
And your favorite color is? blue
learnbyexample, I like the blue color too