Something You Need to Know to Get Start Programming in Python 3 (1)

Abstract

These days, I have been learning the basic knowledge and operation in Python. And my study is quite fruitful in my scheme of things. Therefore, I intend to summarize my studying notes in several articles hoping to help those people who want to get start programming in Python3. And here comes the first article talking about variables, data types and data structures in Python.

1.Variables & Data Types

1.1 the Use of Variables
Variables, regarded as the containers of information, make it easy handling all kinds of data. To illustrate, let’s first see the application of variables in writing a story.

name="Ross"
print("There once was a man named "+ name+". ")
print("He really liked the name "+ name+". ")
name="Joey"
print("There once was a man named "+ name+". ")
print("He really liked the name "+ name+". ")

Here comes the result of running the code:
在这里插入图片描述
In a story, we just need to change a variable such as the “name” in the above code if we want a new name of a character. Apparently, it’s quite a convenient way for a long story.

1.2 Rules of Variable Names

  1. Variable names can be composed of letters, underscores, and numbers.
  2. Variable names don’t start with a number.
  3. Variables cannot be named with keywords in Python.
  4. Identifiers in Python are case sensitive.

1.3 Common Data Types in Python
There are three common data types used in Python, strings, numbers and Bollean values. All these three types of data can be stored in variables.

name="Ross" # a string
num1=50 # an integer number
num2=50.23 # a float number
is_male1=False # a Boolean value
is_male2=True # a Boolean value

1.4 Working with Strings
Strings are plain text. Here are some methods to do with strings.

phrase="Scut"
print(phrase.upper())
print(phrase.isupper())
print(phrase.upper().isupper())
print(len(phrase))
print(phrase[0])
print(phrase.index("S"))
print(phrase.index("cut"))
print(phrase.replace("t","s"))

在这里插入图片描This述
“.upper()”, “.isupper()”, “len()” etc. are actually some built-in functions.

1.5 Working with Numbers
1.5.1

my_num=5
print(str(my_num)+" is my favourite")

The elements connected by “+” are supposed to be in the same data type.
Therefore, we use “str()” to convert the number value stored in the variable “my_num” to a string value.
Here comes the result.

5 is my favourite

1.5.2

my_num=-5
print(abs(my_num))
print(pow(3,2))
print(max(4.6,5.3))
print(round(3.2))
print(round(3.7))

Here comes the result.
在这里插入图片描述
“abs()”, “pow()”,“round()” etc. are actually some built-in functions.

1.5.3

from math import*
print(floor(3.7))
print(ceil(3.7))
print(sqrt(36))
print(exp(1))

“math” is a module stored in the system. It gives us more access to math functions. If we want to use those functions in the module, we should write the code “from math import*” at the very front.
Here comes the result.

3
4
6.0
2.718281828459045

1.6 Getting Input from Users
In order to realize the interaction of data between users and Python, we can use the code below.

name=input("Enter a name: ")
print("Hello "+name+"!")

Here comes the result.

Enter a name: Rachel
Hello Rachel!

There’s a thing we should know that python is always going to convert the input from users into strings by default. Here comes an instance and corresponding result.

num1=input("Enter a number: ")
num2=input("Enter another number: ")
result=num1+num2
print(result)

Enter a number: 50
Enter another number: 50.23
5050.23

As a result of the unwanted answer, we should revise the code.

num1=input("Enter a number: ")
num2=input("Enter another number: ")
result=int(num1)+int(num2)
print(result)

However, if we input any decimal, the program will break down on the grounds that the “int()” function is not able to attain an integer. Therefore, we are supposed to use “float()” function instead.

num1=input("Enter a number: ")
num2=input("Enter another number: ")
result=float(num1)+float(num2)
print(result)

2.Built-in Data Structures in Python

Apparently, data structures are structures that store data, and the way we organize data is called a data structure. There are three basic and common built-in data structures in Python, lists, tuples, and dictionaries . Next, we are going to see how to use these structures to organize data.

2.1 Lists
2.1.1 Linear Arrays
In C++, only can we put the same type of data in a list. However, the list in Python can store different types of data as the example below.

friends=["Ross",39,True]

If we intend to search for specific elements in the list, we can use index flexibly. The code below shows the usage of index in Python.

friends=["Ross","Rachel","Joey"]
print(friends)
print(friends[0])
print(friends[-2])
print(friends[1:])
print(friends[0:2])
friends[2]="Chandler"
print(friends)

Compared with C++, we can use reversed index in Python, such as the fourth line of the code.
Here displays the result.

['Ross', 'Rachel', 'Joey']
Ross
Rachel
['Rachel', 'Joey']
['Ross', 'Rachel']
['Ross', 'Rachel', 'Chandler']

Next, we are going to learn some functions used in the list.

numbers1=[1,2,3,4,5]
numbers2=numbers1.copy()
# With this function, we can make a copy of "numbers1".
numbers=[1,2,3,4,5]
numbers.reverse()
# Using this function, we can reverse the elements in the list.
numbers=[9,3,6,8]
numbers.sort()
print(numbers)
# [3, 6, 8, 9]

If the elements stored in the list are strings, it will sort in alphabetical order. There is another thing we are supposed to know that the sort function above doesn’t support a list containing different types of data.

There are still a couple of functions we’d better know. However, I’m not going to make a thorough introduction. You can use pycharm or the command prompts in Windows (terminal in Mac) to try running these functions.

friends=["Ross","Rachel","Joey","Phobe","Monica"]
numbers=[1,2,3,4,5]
friends.extend(numbers)

friends=["Ross","Rachel","Joey","Phobe","Monica"]
friends.append("Chandler")

friends=["Ross","Rachel","Joey","Phobe","Monica"]
friends.insert(2,"Chandler")

friends=["Ross","Rachel","Joey","Phobe","Monica"]
print(friends.index("Rachel"))
print(friends.count("Steven"))

friends=["Ross","Rachel","Joey","Phobe","Monica"]
friends.remove("Phobe")

friends=["Ross","Rachel","Joey","Phobe","Monica"]
friends.pop() # remove the last element of the list
friends.clear()# clear all the elements in the list

2.1.2 Using Command Prompts to Test Code
Talking about using the command prompts in Windows (terminal in Mac) to run those functions above, I intend to show you how to use it to do some quick and dirty tests. (I use Windows.)
First, open the command prompts. You can input “cmd” in the search window to get a quick access to it.
Second, input “python” at the very beginning. Press “Enter” and you can see the content below.
在这里插入图片描述Then, you can input your code after “>>>”.
在这里插入图片描述If you have a try in person, you will find it convenient to do a quick test of your code.

2.1.3 2D Lists
The code below shows you the basic way to create a 2D list and how to search for the elements in it.

number_grid=[
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [0]
]
print(number_grid)
print(number_grid[2])
print(number_grid[2][1])

Here comes the result.
在这里插入图片描述
2.2 Tuples
Tuples, which can store all kinds of data, are quite similar to lists. Basically, once you get a good command of lists, you almost master tuples.

coordinates=(2,"r",True)

However, there is a big difference between tuples and lists. The code below and its corresponding result will reveal the difference clearly.

coordinates=(2,3,4)
coordinates[1]=10
print(coordinates)

在这里插入图片描述Therefore, lists are mutable, while tuples are immutable. Once a tuple is created, it can’t be changed.

2.3 Dictionaries
The dictionary is another built-in data structure in Python. It is based on the dictionary prototype in real life. There is a concept called “key-value pairs” in Python which we are supposed to know studying dictionaries. The “key” here is like the word we look up in a dictionary, and the “value” is the definition corresponding to the word.

monthConversions={
    "Jan":"January", # "Jan" is a key, and "January" is a value.
    "Feb":"February",
    "Mar":"March",
}
print(monthConversions["Mar"])
print(monthConversions.get("Mon"))
print(monthConversions.get("Mon","Not a valid Key"))
print(monthConversions.get("Jan","Not a valid Key"))
"""
 "Not a valid Key" after the comma is a default value
"""

Here displays the result.
在这里插入图片描述
In “key-value pairs”, “value” is mutable while “key” is immutable. Though “value” can be repeated, and be any sort of data like a number or a Boolean value, “key” must be unique.

That’s the end of my first article. I wish it would help your study in Python to some extent.

Resources:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值