尽管输入有效值,程序仍拒绝运行“ if”语句

如何解决尽管输入有效值,程序仍拒绝运行“ if”语句

我对计算机编程非常陌生,目前正在PyCharm社区中编写一个程序,当给我学校的一个学生的名字时,它将打印出从学校到该学生的住所的指示。

一切都进行得很好,昨晚我已经掌握了一切。今天,我打开计算机,由于某种原因,我的程序拒绝运行我的'if'/'elif'语句,并且即使给定一个满足'if'/'elif'语句的值,它也只会运行else语句。>

我尝试重写程序,多次重新启动PyCharm,确保我与空格和制表符一致,并确保我的变量可以相互通信。我已经在这里和其他网站上搜索了一段时间,但我看不出为什么我的代码昨天能正常工作的原因,但现在除了else语句之外,其他都拒绝运行。

这是我的代码,它将询问用户“您想去哪里?”然后会收到“ house”的输入。收到此通知后,它将打印出他们的指示。取而代之的是,它每次都运行“ else”语句。

AzureDiagnostics
| where Category == "kube-audit"
| extend log_j=parse_json(log_s) 
| extend requestURI=log_j.requestURI 
| extend verb=log_j.verb 
| extend username=log_j.user.username
| extend requestObject = parse_json(log_j.requestObject)
| where verb !in ("get","list","watch","")
| where username !in ("aksService","masterclient","nodeclient")
| where username !startswith "system:serviceaccount:kube-system"
| where requestURI startswith "/api/"
| where requestURI !startswith "/api/v1/nodes/"
| where requestURI !startswith "/api/v1/namespaces/kube-system/"
| where requestURI !startswith "/api/v1/namespaces/ingress-basic/"

解决方法

casefold将字符串转换为小写,并且您的参考字符串包括大写字符。

作为一个简单的解决方法,您可以将“大卫之家”更改为“大卫之家”,等等。

从长远来看,您可能希望实现稍微不那么脆弱的比较,但这是一项艰巨的工作,取决于您将如何使用您的程序以及解析失败的后果。

,

为纠正错字并支持用户做破坏测试的事情,下面是一个使用字符串相似性比较来确定输入是否接近任何用户名的示例:

import difflib
# Storing the names and directions of users: 
#This is called a dictionary. More info here https://www.w3schools.com/python/python_dictionaries.asp
directions= {
    "David": "Directions to David's home from T... \n East on X,\n South on Y.," \
            " \n West on Z.,\n South on A.,\n first white house on the right.","Caroline": "Directions to Caroline's home from T... \n East on x,\n South on y.," \
        " \n East on z.,\n South on p.,\n East on q," \
        " \n West on t.,\n last brick house in the cul-de-sac.","William":"Directions to Will's home from T... \n East on x," \
        " \n West on z.,\n South on Fa.,\n West on b.,\n first house on the right.","Bannon":"<Insert directions to Bannon's house>"
}

# User gives a specific name and then receives a location:
while True:
    destination = input("Where would you like to go? ")

    highest = 0 #highest score between the user name and input
    user_key = "" #name of the user who most closely matches the input
    for user in directions: #iterate through all the user's names in the directions dictionary
      similarity = difflib.SequenceMatcher( #for each user's name,compare it to the input
          None,destination,user).ratio()
      if(similarity > highest): #if the similarity score is greater than the highest recorded score,update the score
        highest = similarity
        user_key = user
    
    #Code that runs if a match is too low are not found
    if(highest < 0.5): #adjust this based on how close you want the match to be. highest will always be between 0.0 and 1.0
      print("Sorry,that location wasn't found! Please try again.")
      continue

    #Print user's directions
    else:
      print('\n\nGetting directions to ' + user_key + '\'s house\n\n')
      print(directions[user_key] + "\n\n\n")

因此,如果您输入“威廉姆斯的房子”,“威廉姆斯”,“威廉姆斯的房子”,“威廉姆”或类似“威廉姆斯”的名称,您将获得前往威廉姆斯房子的路线。

在线运行:https://repl.it/@marsnebulasoup/UprightMutedSymbol

,

最小化程序并进行测试!您发布了过多的代码来演示此问题。一旦出现类似if destination.casefold() == 'Davids house':的问题,请尽量减少罐装数据的问题

destination = "david's house"
if not destination.casefold() == "Davids house":
    print(repr(destination),"failed")

此打印

"david's house" failed

casefold的帮助说返回适合无条件比较的字符串版本。。嗯,就是这样。您需要将两侧都折起来。然后就是那个讨厌的撇号。也许您需要更多规范化,例如摆脱非字母字符。

通过最小化,您为代码编写了一个很好的测试。您可以编写一个小的比较函数来执行大小写折叠和其他标准化操作。然后,您可以对该函数编写一打测试以测试所有边缘情况。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-