我对python很新,对于我的生活,我无法让它工作.我想设置这个小脚本来检查用户输入的内容是否等于列表中的任何名称以及是否执行了一个函数.如果用户输入的内容不是其中一个名称,则应该执行不同的功能.这似乎应该很简单,但我无法弄清楚.我已经使用多个elif语句来检查每个案例,但似乎应该有一个更优雅的解决方案,然后每次我想检查名称时只输入50个elif语句.
当前脚本:
names=['Scott', 'Doug', 'Sam', 'Harry']
typedname=str(input('What is your name?: '))
if typedname==['Scott' or 'Doug' or 'Sam' or 'Harry']:
print('you are '+typedname)
else:
print('You are not in the names list')
Run Code Online (Sandbox Code Playgroud)
if typedname in ['Scott', 'Doug', 'Sam', 'Harry']:
print('You are', typedname):
else:
print('You are not in the names list')
Run Code Online (Sandbox Code Playgroud)
Python 3.2为这些案例带来了一个optmization:
if typedname in {'Scott', 'Doug', 'Sam', 'Harry'}:
Run Code Online (Sandbox Code Playgroud)
将被转换为a frozenset并且搜索将处于恒定时间,并且将在编译字节码时构建该集合.
| 归档时间: |
|
| 查看次数: |
3325 次 |
| 最近记录: |