程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Practical Python Exercise 1: Getting User Input

編輯:Python

實用 Python

字符輸入

輸入字符串類型 int

練習 1(和答案)

Create a program that asks the user to enter their name and age.Print out a message to them,Tell them a year they will be full 100 歲.注意:對於此練習,You are expected to write the year explicitly(So next year is out of date).If you want to do it in a generic way,請參見練習 39.

例外:

  1. Added to the previous program by asking the user for other numbers and printing out many copies of the previous message.(提示:Python 中存在操作順序)
  2. Print out many copies of the previous message on separate lines.(提示:字符串 "\n 與按 Enter 按鈕相同)

討論

  • 獲取用戶輸入
  • 操縱字符串(幾種方式).練習 38 Shows another way to manipulate and display strings

Python User input in

要獲取Python 3 User input in ,the command you used input() .Store the result in a variable,and use it to your heart's content.請記住,Even if they enter numbers,The result you get from the user will also be a string.

例如:

name = input("Give me your name: ")print("Your name is " + name)

This will be in the terminal(or shell,you are running Python 中)What is printed in is:

>>> name = input("Give me your name: ")Give me your name: 宇宙之一粟>>> print("Your name is " + name)Your name is 宇宙之一粟>>> 

input() What happens at the end is,It waits for the user to type something and press Enter .Only when the user presses ENTER Execute the program to continue after executing the program.

操作字符串(幾種方式)

你從 input() What you get in the function is a string.你能做什麼?

首先:Turn a string into a number.Suppose you are inputting a number to the user 100% 肯定的.You can turn strings into functions int() 的整數:

age = input("Enter your age: ")age = int(age)

在這兩種情況下,Age will have an integer variable,Now you can do math with it.

(請注意,您還可以使用 str() The function does the exact opposite of turning integers into strings)

第二:Do math with strings.

print("Were" + "wolf")print("Door" + "man")print("4" + "chan")print(str(4) + "chan")

Multiplication works the same way:

print(4 * "test")

But division and subtraction don't work that way.就乘法而言,The idea of ​​multiplying two strings together is not well defined.What does it mean to multiply two strings first?但是,It makes sense to specify somehow that the string is multiplied by a number - Just repeat the string as many times as you want.

Try all the arithmetic operations with numbers and strings in your own program - The best way to learn is to try it out!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved