python中字符串的if语句?

If statement for strings in python?(python中字符串的if语句?)
本文介绍了python中字符串的if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个完全的初学者,并且一直在查看 http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements 但我无法理解这里的问题.这很简单,如果用户输入 y 它应该打印这将进行计算,尽管我在 IF answer=="y"

I am a total beginner and have been looking at http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements but I can not understand the problem here. It is pretty simple, if the user enters y it should print this will do the calculation although I get a syntax error on IF answer=="y"

answer = str(input("Is the information correct? Enter Y for yes or N for no"))
proceed="y" or "Y" 
If answer==proceed:
print("this will do the calculation"):
else:
exit()

推荐答案

即使您修复了代码中错误大小写的 if 和不正确的缩进,它也不会像您预期的那样工作.要根据一组字符串检查一个字符串,请使用 in.以下是你的做法(注意 if 都是小写,if 块中的代码缩进一级).

Even once you fixed the mis-cased if and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in. Here's how you'd do it (and note that if is all lowercase and that the code within the if block is indented one level).

一种方法:

if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
    print("this will do the calculation")

另一个:

if answer.lower() in ['y', 'yes']:
    print("this will do the calculation")

这篇关于python中字符串的if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)