简体   繁体   English

无法更改python中变量的值,if语句

[英]Unable to change the value of a variable in python, if-statement

I have a very simple script, the goal is that if someone enters a number between 40 and 49 for raw_input, the value of ageRisk should change from 0 to 0.004我有一个非常简单的脚本,目标是如果有人为 raw_input 输入 40 到 49 之间的数字, ageRisk的值应该从 0 变为 0.004

age = raw_input("Enter your age: ")

ageRisk = 0

if age >= 40 and age < 50:
    ageRisk = 0.004

print ageRisk

However when I run this script entering 44 for the raw_input , the value for ageRisk remains at 0. Why is this?但是,当我运行此脚本时,为raw_input输入 44 时, ageRisk的值仍为 0。这是为什么呢?

This is because the user's input is a string .这是因为用户的输入是一个string To fix this, change your line age = raw_input("Enter your age: ") into age = int(raw_input("Enter your age: "))要解决此问题,请将您的行age = raw_input("Enter your age: ")更改为age = int(raw_input("Enter your age: "))

Try changing this:尝试改变这个:

age = raw_input("Enter your age: ")

to:到:

age = int(raw_input("Enter your age: "))

The default for input is to treat everything as a string, and if not converted your logical does not see the numerical value it needs to reassign the values.输入的默认值是将所有内容视为字符串,如果未转换,您的逻辑将看不到重新分配值所需的数值。

Your raw_input is taking in a number as a string.您的 raw_input 将数字作为字符串。 to resolve this, convert the input into an integer.要解决此问题,请将输入转换为整数。

age = int(input("Enter your age: "))

In Python 2, raw_input() returns a string , not an integer.在 Python 2 中, raw_input()返回一个string ,而不是一个整数。

You need to wrap your raw_input() in an int() call to convert it.您需要将raw_input()包装在int()调用中以进行转换。

int(raw_input()) takes user input and returns an integer (if one was entered). int(raw_input())接受用户输入并返回一个整数(如果输入了)。

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

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