简体   繁体   中英

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

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?

This is because the user's input is a string . To fix this, change your line age = raw_input("Enter your age: ") into 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. 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.

You need to wrap your raw_input() in an int() call to convert it.

int(raw_input()) takes user input and returns an integer (if one was entered).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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