用python 用while遍历字符串 hello world
时间: 2023-06-02 22:06:30 浏览: 123
当然可以。可以使用以下代码:
string = "hello world"
i = 0
while i < len(string):
print(string[i])
i += 1
输出:
h
e
l
l
o
w
o
r
l
d
相关问题
python使用while循环输出十遍hello world
可以使用以下代码来使用 while 循环输出十遍 "hello world":
```python
count = 1
while count <= 10:
print("hello world")
count += 1
```
在这个代码中,我们先初始化一个变量 `count`,并赋值为 1。然后,使用 while 循环来判断条件:只要 `count` 的值小于等于 10,就执行循环体内的代码。循环体内打印 "hello world" 并将 `count` 的值加 1。这样,每次循环都会输出一次 "hello world",直到循环执行了十次为止。
Python中循环遍历
Python中循环遍历有多种方式,比较常用的方式有for循环和while循环。下面是两种方式的示例:
1. for循环:
```python
# 遍历列表
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print(i)
# 遍历字典
my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
for key, value in my_dict.items():
print(key, value)
# 遍历字符串
my_str = 'hello world'
for char in my_str:
print(char)
```
2. while循环:
```python
# 遍历列表
my_list = [1, 2, 3, 4, 5]
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
# 遍历字典
my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
keys = list(my_dict.keys())
i = 0
while i < len(keys):
key = keys[i]
value = my_dict[key]
print(key, value)
i += 1
# 遍历字符串
my_str = 'hello world'
i = 0
while i < len(my_str):
print(my_str[i])
i += 1
```