繁体   English   中英

sys.stdin.readline()和if else(Python)

[英]sys.stdin.readline() with if else (Python)

我是Python的新手,需要一点帮助。 我试图使用下一个命令以便从屏幕上获取用户输入:sys.stdin.readline()

当我想打印某些东西时一切都很好,但是当我尝试合并一个if else语句时,似乎用户输入忽略了我在if ==中编写的区分大小写的字符串,即使在编写时也总是返回else输入“ Sam”

我想做一个简单的任务,像这样:

print("What is your name ?")

name = sys.stdin.readline()

print("Hello", name)

if name == 'Sam' :
    print ('You are in our group')
else :
    print('You are not in our group')

我应该在sys.stdin.readline()中做什么来确认if ==参数?

谢谢你的帮助

该行将包含行尾字符'\\n'docs )。 因此,它永远不会等于'Sam' (可能在文件末尾除外)。

也许使用name = name.strip()删除它和任何多余的空白字符。

关于主要职位:

我在同一代码中使用了sys.stdin.readline()和input()。 两次都工作。 以下是代码:

import sys
print('how much was your meal')
price = int(input())
print('how much would you like to tip in percentage')
tip = int(input())
tipamount = price * (tip/100)
print('your tip amount is %s' %tipamount + 'dollars')

第二个代码:

#import sys
#price = int(sys.stdin.readline())
#print('how much would you like to tip in percentage')
#tip = int(sys.stdin.readline())
#tipamount = price * (tip/100)
#print('your tip amount is %s' %tipamount + 'dollars') 

但是,当我在以下代码中使用sys.stdin.readline时,它不起作用。 相反,input()起作用了。 有人可以解释为什么sys.stdin.readline在第一个代码中起作用而在这个代码中不起作用吗?

import sys
print('are you looking to study digital media in australia?')
answer = str(sys.stdin.read())
if answer == 'yes':
print('Deakin University has one of the best Digital Science Program!')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM