Python基础代码

  • 格式:docx
  • 大小:10.79 KB
  • 文档页数:2

以下是一些常见的Python基础代码:

1. 输出Hello World:

```python

print("Hello World")

```

2. 声明变量:

```python

age = 25

name = "John"

```

3. 输入和输出:

```python

name = input("What is your name?")

print("Nice to meet you, "+ name)

```

4. 条件语句:

```python

if age < 18:

print("You are too young to vote")

elif age >=18 and age < 21:

print("You can vote but cannot drink")

else:

print("You can vote and drink")

```

5. 循环语句:

```python

for i in range(1, 11):

print(i)

while n < 10:

print(n)

n += 1

```

6. 列表操作:

```python

my_list = ["apple", "banana", "cherry"]

my_list.append("orange")

my_list.remove("banana")

print(my_list)

```

7. 字典操作:

```python

my_dict = {"name": "John", "age": 25}

my_dict["gender"] = "male"

del my_dict["age"]

print(my_dict)

```

8. 函数:

```python

def add(a, b):

return a + b

sum = add(2, 3)

print(sum)

```

9. 类:

```python

class Person:

def __init__(self, name, age):

= name

self.age = age

def greeting(self):

print("Hello, my name is "+ )

person1 = Person("John", 25)

person1.greeting()

```

以上只是一些简单的Python基础代码,更多复杂的代码可以在学习过程中逐渐掌握。