if __name__ =='__main__': print("城市省份查询".center(40,'*')) print("输入#退出系统") while True: city=input("输入城市名:") pv=get_pvs(city) if not pv: print("没有查到这个城市的信息".format(city)) elif city=='#': break else: print("{}所属省份是:".format(city,pv))
时间: 2024-04-16 09:24:52 浏览: 24
这段代码的作用是实现一个城市省份查询系统。在程序运行时,会先打印出一个标题,然后进入一个无限循环,循环内部会提示用户输入城市名,然后调用函数 `get_pvs(city)` 来获取该城市所属的省份信息。如果找不到该城市的信息,会打印出相应的提示;如果用户输入了 '#',则会退出系统;否则,会打印出该城市所属的省份信息。
相关问题
python if __name__ == __main__:用法
`if __name__ == "__main__":` 是 Python 中常用的一个条件语句,它通常用于判断当前模块是否是运行在主程序中,或者是被其他模块 import 而导入运行的。
具体来说,当一个 Python 文件直接被执行时,`__name__` 变量的值会被自动设置为 `"__main__"`,如果被导入时,`__name__` 的值就是模块名(即文件名)。
因此,使用 `if __name__ == "__main__":` 可以方便地将一些只在作为主程序运行时才执行的代码放在这个条件语句中,而避免在模块被导入时执行这些代码。
下面是一个简单的示例,假设我们有一个名为 `example.py` 的 Python 模块,里面包含一些函数和变量:
```
# example.py
def add(x, y):
return x + y
def sub(x, y):
return x - y
pi = 3.1415926
```
如果我们在命令行中直接执行 `example.py`,那么 `__name__` 的值就是 `"__main__"`,我们可以在条件语句中添加一些测试代码:
```
# example.py
def add(x, y):
return x + y
def sub(x, y):
return x - y
pi = 3.1415926
if __name__ == "__main__":
print("This is the main program.")
print("The result of 1 + 2 is", add(1, 2))
print("The value of pi is", pi)
```
如果我们将 `example.py` 导入到另一个模块中,那么 `__name__` 的值就是模块名(即文件名),条件语句中的代码就不会被执行:
```
# test.py
import example
print("This is a test program.")
print("The result of 3 - 4 is", example.sub(3, 4))
```
这样,当我们执行 `test.py` 时,`example.py` 中的测试代码就不会被执行,只有 `test.py` 的代码会被执行。
if __name__ == main: print(hello)没有运行
当if __name__ == 'main':条件成立时,print(hello)语句会被执行并打印出hello。如果你说if __name__ == 'main':条件没有运行,那么可能是因为当前的模块不是被直接执行的,而是作为一个模块导入到其他程序中。在这种情况下,if __name__ == 'main':条件不会成立,所以print(hello)语句不会执行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)